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
|
---|---|---|---|---|---|---|---|
c719b252cb154e73673deed3f760883a9f60a7c7
|
Add failing spec
|
spec/api-desktop-capturer-spec.js
|
spec/api-desktop-capturer-spec.js
|
const assert = require('assert');
const desktopCapturer = require('electron').desktopCapturer;
describe('desktopCapturer', function() {
it('should return a non-empty array of sources', function(done) {
desktopCapturer.getSources({
types: ['window', 'screen']
}, function(error, sources) {
assert.equal(error, null);
assert.notEqual(sources.length, 0);
done();
});
});
});
|
JavaScript
| 0.000002 |
@@ -401,13 +401,450 @@
);%0A %7D);
+%0A%0A it('does not throw an error when called twice (regression)', function(done) %7B%0A var callCount = 0;%0A var callback = function(error, sources) %7B%0A callCount++;%0A assert.equal(error, null);%0A assert.notEqual(sources.length, 0);%0A if (callCount === 2) done();%0A %7D%0A%0A desktopCapturer.getSources(%7Btypes: %5B'window', 'screen'%5D%7D, callback);%0A desktopCapturer.getSources(%7Btypes: %5B'window', 'screen'%5D%7D, callback);%0A %7D)
%0A%7D);%0A
|
b6b7b7a5672e7bedf7863ee96a50ef55a2b4ee36
|
Update player_model.js
|
src/model/player_model.js
|
src/model/player_model.js
|
import AbstractByteSequenceAwareModel from "./abstract_byte_sequence_aware_model";
const FLAG_HUMAN_CONTROLLED = 0x01;
export default class PlayerModel extends AbstractByteSequenceAwareModel {
constructor() {
super();
this.id = 'undefined';
this.username = this.email = 'undefined';
}
getId() {
return this.id;
}
setId(id) {
this.id = id;
}
getUsername() {
return this.username;
}
setUsername(username) {
this.username = username;
}
getEmail() {
return this.email;
}
setEmail(email) {
this.email = email;
}
isHumanControlled() {
return this.hasSequence(this.constructor.getHumanFlag());
}
static getHumanFlag() {
return FLAG_HUMAN_CONTROLLED;
}
}
|
JavaScript
| 0.000001 |
@@ -274,29 +274,12 @@
his.
-username = this.email
+name
= '
@@ -394,21 +394,17 @@
%0A get
-Usern
+N
ame() %7B%0A
@@ -419,28 +419,24 @@
return this.
-user
name;%0A %7D%0A
@@ -447,25 +447,14 @@
set
-Username(username
+Name(v
) %7B%0A
@@ -470,135 +470,16 @@
his.
-user
name =
-username;%0A %7D%0A%0A getEmail() %7B%0A return this.email;%0A %7D%0A%0A setEmail(email) %7B%0A this.email = email
+v
;%0A
|
0f345935ca5c1fa42b3ed67166cc6e5845160b41
|
Make sure elements share the same scope
|
spec/javascripts/zen_mode_spec.js
|
spec/javascripts/zen_mode_spec.js
|
/* eslint-disable space-before-function-paren, no-var, one-var, one-var-declaration-per-line, object-shorthand, comma-dangle, no-return-assign, new-cap, padded-blocks, max-len */
/* global Dropzone */
/* global Mousetrap */
/* global ZenMode */
/*= require zen_mode */
(function() {
var enterZen, escapeKeydown, exitZen;
describe('ZenMode', function() {
var fixtureName = 'issues/open-issue.html.raw';
fixture.preload(fixtureName);
beforeEach(function() {
fixture.load(fixtureName);
spyOn(Dropzone, 'forElement').and.callFake(function() {
return {
enable: function() {
return true;
}
};
// Stub Dropzone.forElement(...).enable()
});
this.zen = new ZenMode();
// Set this manually because we can't actually scroll the window
return this.zen.scroll_position = 456;
});
describe('on enter', function() {
it('pauses Mousetrap', function() {
spyOn(Mousetrap, 'pause');
enterZen();
return expect(Mousetrap.pause).toHaveBeenCalled();
});
return it('removes textarea styling', function() {
$('textarea').attr('style', 'height: 400px');
enterZen();
return expect('textarea').not.toHaveAttr('style');
});
});
describe('in use', function() {
beforeEach(function() {
return enterZen();
});
return it('exits on Escape', function() {
escapeKeydown();
return expect($('.zen-backdrop')).not.toHaveClass('fullscreen');
});
});
return describe('on exit', function() {
beforeEach(function() {
return enterZen();
});
it('unpauses Mousetrap', function() {
spyOn(Mousetrap, 'unpause');
exitZen();
return expect(Mousetrap.unpause).toHaveBeenCalled();
});
return it('restores the scroll position', function() {
spyOn(this.zen, 'scrollTo');
exitZen();
return expect(this.zen.scrollTo).toHaveBeenCalled();
});
});
});
enterZen = function() {
return $('.js-zen-enter').click();
};
exitZen = function() { // Ohmmmmmmm
return $('.js-zen-leave').click();
};
escapeKeydown = function() {
return $('textarea').trigger($.Event('keydown', {
keyCode: 27
}));
};
}).call(this);
|
JavaScript
| 0 |
@@ -1141,24 +1141,36 @@
%0A $('
+.notes-form
textarea').a
@@ -1242,17 +1242,31 @@
expect(
-'
+$('.notes-form
textarea
@@ -1267,16 +1267,17 @@
xtarea')
+)
.not.toH
@@ -1513,16 +1513,28 @@
pect($('
+.notes-form
.zen-bac
@@ -2108,32 +2108,44 @@
%7B%0A return $('
+.notes-form
.js-zen-enter').
@@ -2145,32 +2145,32 @@
nter').click();%0A
-
%7D;%0A%0A exitZen
@@ -2211,16 +2211,28 @@
turn $('
+.notes-form
.js-zen-
@@ -2277,32 +2277,32 @@
= function() %7B%0A
-
return $('te
@@ -2299,16 +2299,28 @@
turn $('
+.notes-form
textarea
|
edd5a3878a841f00eebcbfdd7114e81ce26ae09a
|
fix redefined variables
|
lib/6to5/transformation/transformers/es6-computed-property-names.js
|
lib/6to5/transformation/transformers/es6-computed-property-names.js
|
var util = require("../../util");
var t = require("../../types");
exports.ObjectExpression = function (node, parent, file) {
var hasComputed = false;
for (var i in node.properties) {
hasComputed = t.isProperty(node.properties[i], { computed: true });
if (hasComputed) break;
}
if (!hasComputed) return;
var objId = util.getUid(parent, file);
var body = [];
var container = t.functionExpression(null, [], t.blockStatement(body));
container._aliasFunction = true;
var props = node.properties;
// normalise key
for (i in props) {
var prop = props[i];
var key = prop.key;
if (!prop.computed && t.isIdentifier(key)) {
prop.key = t.literal(key.name);
}
}
// add all non-computed properties and `__proto__` properties to the initializer
var initProps = [];
var broken = false;
for (i in props) {
var prop = props[i];
if (prop.computed) {
broken = true;
}
if (!broken || t.isLiteral(prop.key, { value: "__proto__" })) {
initProps.push(prop);
props[i] = null;
}
}
// add a simple assignment for all Symbol member expressions due to symbol polyfill limitations
// otherwise use Object.defineProperty
for (i in props) {
var prop = props[i];
if (!prop) continue;
var key = prop.key;
var bodyNode;
if (prop.computed && t.isMemberExpression(key) && t.isIdentifier(key.object, { name: "Symbol" })) {
bodyNode = t.assignmentExpression(
"=",
t.memberExpression(objId, key, true),
prop.value
);
} else {
bodyNode = t.callExpression(file.addDeclaration("define-property"), [objId, key, prop.value]);
}
body.push(t.expressionStatement(bodyNode));
}
// only one node and it's a Object.defineProperty that returns the object
if (body.length === 1) {
var first = body[0].expression;
if (t.isCallExpression(first)) {
first.arguments[0] = t.objectExpression([]);
return first;
}
}
//
body.unshift(t.variableDeclaration("var", [
t.variableDeclarator(objId, t.objectExpression(initProps))
]));
body.push(t.returnStatement(objId));
return t.callExpression(container, []);
};
|
JavaScript
| 0.000002 |
@@ -140,32 +140,64 @@
omputed = false;
+%0A var prop;%0A var key;%0A var i;
%0A%0A for (var i i
@@ -189,20 +189,16 @@
%0A for (
-var
i in nod
@@ -585,36 +585,32 @@
in props) %7B%0A
-var
prop = props%5Bi%5D;
@@ -610,28 +610,24 @@
ops%5Bi%5D;%0A
-var
key = prop.k
@@ -875,36 +875,32 @@
in props) %7B%0A
-var
prop = props%5Bi%5D;
@@ -1249,20 +1249,16 @@
) %7B%0A
-var
prop = p
@@ -1296,20 +1296,16 @@
e;%0A%0A
-var
key = pr
|
d8b0d338c0df3a8dee40b1f13520f3b6dcad6bd0
|
Use 'const' instead of 'var'
|
lib/cartodb/models/mapconfig/provider/create-layergroup-provider.js
|
lib/cartodb/models/mapconfig/provider/create-layergroup-provider.js
|
var MapStoreMapConfigProvider = require('./map-store-provider');
const QueryTables = require('cartodb-query-tables');
/**
* @param {MapConfig} mapConfig
* @param {String} user
* @param {UserLimitsBackend} userLimitsBackend
* @param {Object} params
* @constructor
* @type {CreateLayergroupMapConfigProvider}
*/
function CreateLayergroupMapConfigProvider(
mapConfig,
user,
userLimitsBackend,
pgConnection,
affectedTablesCache,
params
) {
this.mapConfig = mapConfig;
this.user = user;
this.userLimitsBackend = userLimitsBackend;
this.pgConnection = pgConnection;
this.affectedTablesCache = affectedTablesCache;
this.params = params;
this.cacheBuster = params.cache_buster || 0;
}
module.exports = CreateLayergroupMapConfigProvider;
CreateLayergroupMapConfigProvider.prototype.getMapConfig = function(callback) {
if (this.mapConfig && this.params && this.context) {
return callback(null, this.mapConfig, this.params, this.context);
}
var context = {};
this.userLimitsBackend.getRenderLimits(this.user, this.params.api_key, (err, renderLimits) => {
if (err) {
return callback(err);
}
context.limits = renderLimits;
this.context = context;
return callback(err, this.mapConfig, this.params, context);
});
};
CreateLayergroupMapConfigProvider.prototype.getKey = MapStoreMapConfigProvider.prototype.getKey;
CreateLayergroupMapConfigProvider.prototype.getCacheBuster = MapStoreMapConfigProvider.prototype.getCacheBuster;
CreateLayergroupMapConfigProvider.prototype.filter = MapStoreMapConfigProvider.prototype.filter;
CreateLayergroupMapConfigProvider.prototype.createKey = MapStoreMapConfigProvider.prototype.createKey;
CreateLayergroupMapConfigProvider.prototype.createAffectedTables = function (callback) {
this.getMapConfig((err, mapConfig) => {
if (err) {
return callback(err);
}
const { dbname } = this.params;
const token = mapConfig.id();
const queries = [];
this.mapConfig.getLayers().forEach(layer => {
queries.push(layer.options.sql);
if (layer.options.affected_tables) {
layer.options.affected_tables.map(table => {
queries.push(`SELECT * FROM ${table} LIMIT 0`);
});
}
});
const sql = queries.length ? queries.join(';') : null;
if (!sql) {
return callback();
}
this.pgConnection.getConnection(this.user, (err, connection) => {
if (err) {
return callback(err);
}
QueryTables.getAffectedTablesFromQuery(connection, sql, (err, affectedTables) => {
if (err) {
return callback(err);
}
this.affectedTablesCache.set(dbname, token, affectedTables);
callback(null, affectedTables);
});
});
});
};
CreateLayergroupMapConfigProvider.prototype.getAffectedTables = function (callback) {
this.getMapConfig((err, mapConfig) => {
if (err) {
return callback(err);
}
const { dbname } = this.params;
const token = mapConfig.id();
if (this.affectedTablesCache.hasAffectedTables(dbname, token)) {
const affectedTables = this.affectedTablesCache.get(dbname, token);
return callback(null, affectedTables);
}
return this.createAffectedTables(callback);
});
};
|
JavaScript
| 0.001211 |
@@ -1,11 +1,13 @@
-var
+const
MapStor
@@ -1013,11 +1013,13 @@
-var
+const
con
|
387e653c06eaa7a7690f275d6778c18250e9dd93
|
fix sending on closed socket
|
server/websocketserver.js
|
server/websocketserver.js
|
/*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF2 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var debug = require('debug')('happyfuntimes:websocketserver');
var HeartMonitor = require('./heart-monitor');
var WSServer = function(server) {
debug('Using WebSockets directly');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({server: server});
var WSClient = function(client) {
this.client = client;
var eventHandlers = { };
var heartMonitor;
this.send = function(msg) {
var str = JSON.stringify(msg);
try {
this.client.send(str);
} catch (e) {
console.error(e);
}
};
this.on = function(eventName, fn) {
if (eventName === 'disconnect') {
eventName = 'close';
// Wrap close event so it only happens once.
if (fn) {
fn = function (origFn) {
return function() {
eventHandlers[eventName] = undefined;
origFn();
};
}(fn);
}
}
if (!eventHandlers[eventName]) {
this.client.on(eventName, function() {
var fn = eventHandlers[eventName];
if (fn) {
fn.apply(this, arguments);
}
}.bind(this));
}
if (eventName === 'message') {
fn = function(origFn) {
return function(data) {
if (data === 'P') {
heartMonitor.acknowledgePing();
return;
}
if (origFn) {
try {
origFn(JSON.parse(data));
} catch (e) {
console.error(e, data.substr(0, 40));
}
}
};
}(fn);
}
eventHandlers[eventName] = fn;
};
this.clearTimeout = function() {
heartMonitor.close();
};
this.close = function() {
debug('close wsclient');
heartMonitor.close();
this.client.close();
};
heartMonitor = new HeartMonitor({
onDead: function() {
debug('dead: closed');
this.close();
}.bind(this),
pingFn: function() {
try {
this.client.send('P');
} catch (e) {
console.error(e);
}
}.bind(this),
});
};
this.on = function(eventName, fn) {
if (eventName === 'connection') {
wss.on(eventName, function(client) {
var wrapper = new WSClient(client);
fn(wrapper);
});
} else {
wss.on(eventName, fn); // does this case exist?
}
};
this.close = function() {
wss.close();
};
};
module.exports = WSServer;
|
JavaScript
| 0 |
@@ -2011,24 +2011,99 @@
tion(msg) %7B%0A
+ if (this.client.readyState !== 1) %7B // OPEN%0A return;%0A %7D%0A
var st
@@ -3692,32 +3692,112 @@
n: function() %7B%0A
+ if (this.client.readyState !== 1) %7B // open%0A return;%0A %7D%0A
try %7B%0A
|
3f7da31a6239812197d72ca61a49e8d2b5e890cc
|
Update userRoutes
|
app/userRoutes.js
|
app/userRoutes.js
|
/**
* New node file
*/
var User = require('../app/models/user');
//Post
//'/users'
exports.addUser = function(req, res) {
var newUser = new User();
User.count({userId:{$exists: true}},
function (err, count) {
newUser.userId = count + 1;
newUser.firstName = req.param('firstName');
newUser.lastName = req.param('lastName');
newUser.emaiId = req.param('emaiId');
newUser.mobile = req.param('mobile');
newUser.save(function(err) {
if(err) {
res.status(500).json({status:'failure'});
console.log(err);
console.log("failure to add new user");
}
else {
res.status(200).json({
userId : newUser.userId,
firstName : newUser.firstName,
lastName : newUser.lastName,
emaiId : newUser.emaiId,
mobile : newUser.mobile
});
}
});
});
};
|
JavaScript
| 0.000001 |
@@ -363,16 +363,17 @@
ser.emai
+l
Id%09%09= re
@@ -385,16 +385,17 @@
am('emai
+l
Id');%0D%0A%09
@@ -775,21 +775,21 @@
%09%09%09%09emai
+l
Id %09
-%09
: newUse
@@ -794,16 +794,17 @@
ser.emai
+l
Id,%0D%0A%09%09%09
|
e0bcc16bee979c13cdf38c4ebfdb74b0cb655b36
|
add helper for post form data
|
app/utils/http.js
|
app/utils/http.js
|
/* eslint-disable import/no-unresolved */
// import 'whatwg-fetch';
/* eslint-enable import/no-unresolved */
function patchProtocal(url) {
if (/^\/\//.test(url)) {
return url.replace(/^/, window.location.protocol);
}
return url;
}
function requestFactory(requestOption = {}) {
return (url, additionOption = {}) => new Promise((resolve, reject) => {
const options = { ...requestOption, ...additionOption };
fetch(patchProtocal(url), options).then((response) => {
if (options.jsonOutput === true) {
response.json().then(resolve).catch(reject);
} else {
response.text().then(resolve).catch(reject);
}
}).catch((err) => {
reject(err);
});
});
}
const GET = requestFactory({
method: 'get',
credentials: 'include',
});
const POST = requestFactory({
method: 'post',
credentials: 'include',
});
const PUT = requestFactory({
method: 'put',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json',
}),
});
export {
GET,
POST,
PUT,
};
|
JavaScript
| 0 |
@@ -861,24 +861,286 @@
lude',%0A%7D);%0A%0A
+const POST_FORM = (url, formDataObj, options = %7B%7D) =%3E %7B%0A const formData = new FormData();%0A Object.keys(formDataObj).forEach((key) =%3E formData.append(key, formDataObj%5Bkey%5D);)%0A /* eslint-disable new-cap */%0A return POST(url, %7B ...options, body: formData %7D);%0A%7D%0A%0A
const PUT =
|
6f0fc55ba1100890e885868bc3b0f8933dfc0472
|
remove _detach feature completely.
|
lib/output/dom.js
|
lib/output/dom.js
|
"use strict";
var myUtil = require("../util");
var inherits = require("util").inherits;
var HtmlOutput = require("./html.js");
function DomOutput(state, writer, target, opts) {
this.html = new HtmlOutput(state, opts);
target.innerHTML = "<div style='visibility:hidden;'></div>";
this.spacer = target.firstChild;
this.cursorView = null;
DomOutput.super_.apply(this, arguments);
this._opts.adhesiveCursor = true;
this._updateRowCount();
}
inherits(DomOutput, require("./live_base.js"));
module.exports = DomOutput;
DomOutput.prototype._detach = function(view, blk) {
var parent = view.parentNode;
var next = view.nextSibling;
parent.removeChild(view);
blk.call(this, view);
if(next)
parent.insertBefore(view, next);
else
parent.appendChild(view);
return view;
};
DomOutput.prototype.createView = function() {
var e = this.target.ownerDocument.createElement("div");
return e;
};
DomOutput.prototype.removeLine = function(number, view) {
this._updateRowCount();
return this.target.removeChild(view);
};
DomOutput.prototype.changeLine = function(number, view, line, cursor) {
// replace a node with its modified clone ist much faster as setting innerHTML directly.
// see: http://blog.stevenlevithan.com/archives/faster-than-innerhtml
view.innerHTML = this.html._renderLine(line, cursor);
//return this._detach(view, function(v) {
// v.innerHTML = this.html._renderLine(line, cursor);
// this.html._mkAttr(line.attr, {$line:true}, v);
//});
};
DomOutput.prototype.insertLine = function(number, view, line, cursor) {
view.innerHTML = this.html._renderLine(line, cursor);
this.html._mkAttr(line.attr, {$line:true}, view);
this.target.insertBefore(view, this.target.childNodes[number]);
this._updateRowCount();
return view;
};
DomOutput.prototype.changeLed = function(l1, l2, l3, l4) {
};
DomOutput.prototype.setCursor = function(x, y) {
};
DomOutput.prototype.resize = function(size) {
this.target.lastChild.innerHTML = this.html._genColumnsString();
};
DomOutput.prototype.commit = function() {
};
DomOutput.prototype._updateRowCount = function() {
var diff = this.state.rows - this.state.getBufferRowCount();
var html = myUtil.repeat("<div> </div>", diff) +
"<div style='line-height:0'>" + myUtil.repeat(" ", this.state.columns) + "</div>";
this._detach(this.spacer, function(s) {
s.innerHTML = html;
s.lineHeight = diff === 0 ? "0" : "inherit";
});
};
DomOutput.canHandle = function(target) {
// Test if target is some kind of DOM-Element
return target !== null && typeof target === "object" && "ownerDocument" in target;
};
|
JavaScript
| 0 |
@@ -1097,376 +1097,59 @@
%7B%0A%09
-// replace a node with its modified clone ist much faster as setting innerHTML directly.%0A%09// see: http://blog.stevenlevithan.com/archives/faster-than-innerhtml%0A%09view.innerHTML = this.html._renderLine(line, cursor);%0A%09//return this._detach(view, function(v) %7B%0A%09//%09v.innerHTML = this.html._renderLine(line, cursor);%0A%09//%09this.html._mkAttr(line.attr, %7B$line:true%7D, v);%0A%09//%7D
+view.innerHTML = this.html._renderLine(line, cursor
);%0A%7D
|
33e5ab9693626efcc9ea1582f366ec0290bd2094
|
add NORMAL_PRIORITY constant to Permission
|
lib/permission.js
|
lib/permission.js
|
var AuthRequest = require('./authRequest');
/**
* A permission in Nitrogen is a grant that has been made to principal(s) for a particular set of actions.
*
* @class Permissino
* @namespace nitrogen
*/
function Permission(json) {
for(var key in json) {
if(json.hasOwnProperty(key)) {
this[key] = json[key];
}
}
}
/**
* Create a permission with the Nitrogen service.
*
* @method create
* @async
* @param {Object} session An open session with a Nitrogen service.
* @param {Object} callback Callback for the create.
* @param {Object} callback.err If the create failed, this will contain the error.
* @param {Object} callback.permission The created permission returned by the service.
**/
Permission.prototype.create = function(session, callback) {
AuthRequest.post(session, { url: session.service.config.permissions_endpoint, json: this }, function(err, resp, body) {
if (err) return callback(err);
if (resp.statusCode != 200) return callback(resp.statusCode, null);
if (callback) callback(null, new Permission(body.permission));
});
};
/**
* Find permissions filtered by the passed query and limited to and sorted by the passed options.
*
* @method find
* @async
* @param {Object} session An open session with a Nitrogen service.
* @param {Object} query A query using MongoDB query format.
* @param {Object} options Options for the query.
* @param {Number} options.limit The maximum number to be returned.
* @param {String} options.sort The field that the results should be sorted on.
* @param {Number} options.dir The direction that the results should be sorted.
* @param {Object} options.skip The number of results that should be skipped before pulling results.
* @param {Object} callback Callback at completion of execution.
* @param {Object} callback.err If the find failed, find will callback with the error.
* @param {Array} callback.permissions The set found with this query.
**/
Permission.find = function(session, query, options, callback) {
if (!session) return callback("session required for find");
AuthRequest.get(session, {
url: session.service.config.permissions_endpoint,
query: query,
queryOptions: options,
json: true
}, function(err, resp, body) {
if (err) return callback(err);
var permissions = body.permissions.map(function(permission) {
return new Permission(permission);
});
callback(null, permissions);
});
};
/**
* Save this permission to the service.
*
* @method save
* @async
* @param {Object} session An open session with a Nitrogen service.
* @param {Object} callback Callback for the save.
* @param {Object} callback.err If the save failed, this will contain the error.
* @param {Object} callback.permission The saved permission returned by the service.
**/
Permission.prototype.save = function(session, callback) {
if (!this.id) return callback("Permission must have id to be saved.");
AuthRequest.put(session, { url: session.service.config.permissions_endpoint + "/" + this.id, json: this }, function(err, resp, body) {
if (err) return callback(err);
if (resp.statusCode != 200) return callback(body, null);
if (callback) callback(null, new Permission(body.permission));
});
};
module.exports = Permission;
|
JavaScript
| 0.001845 |
@@ -3370,16 +3370,56 @@
%7D);%0A%7D;%0A%0A
+Permission.NORMAL_PRIORITY = 10000000;%0A%0A
module.e
|
2b06f05b89f0669c4870c927bba1cbf8e9a9acf6
|
Fix application adapter swallowing errors
|
app/adapters/application.js
|
app/adapters/application.js
|
import DS from 'ember-data';
export default DS.JSONAPIAdapter.extend({
namespace: '/v1'
});
|
JavaScript
| 0.000035 |
@@ -4,92 +4,2672 @@
ort
-DS from 'ember-data';%0A%0Aexport default DS.JSONAPIAdapter.extend(%7B%0A namespace: '/v1'%0A%7D);
+%7B runInDebug, warn %7D from 'ember-data/-private/debug';%0Aimport %7B TimeoutError, AbortError %7D from 'ember-data/adapters/errors';%0Aimport DS from 'ember-data';%0Aimport Ember from 'ember';%0Aimport parseResponseHeaders from 'ember-data/-private/utils/parse-response-headers';%0A%0Aconst %7B run %7D = Ember;%0Aconst %7B Promise %7D = Ember.RSVP;%0A%0Aexport default DS.JSONAPIAdapter.extend(%7B%0A namespace: '/v1',%0A%0A ajax(url, type, options) %7B%0A const adapter = this; // eslint-disable-line consistent-this%0A const requestData = %7B url, method: type %7D;%0A%0A return new Promise((resolve, reject) =%3E %7B%0A const hash = this.ajaxOptions(url, type, options);%0A%0A hash.success = function(payload, textStatus, jqXHR) %7B%0A const response = ajaxSuccess(adapter, jqXHR, payload, requestData);%0A Ember.run.join(null, resolve, response);%0A %7D;%0A%0A hash.error = function(jqXHR, textStatus, errorThrown) %7B%0A const responseData = %7B textStatus, errorThrown %7D;%0A const error = ajaxError(adapter, jqXHR, requestData, responseData);%0A run.join(null, reject, error);%0A %7D;%0A%0A adapter._ajaxRequest(hash);%0A %7D, %60DS: RESTAdapter#ajax $%7Btype%7D to $%7Burl%7D%60);%0A %7D%0A%7D);%0A%0Afunction ajaxSuccess(adapter, jqXHR, payload, requestData) %7B%0A let response;%0A%0A try %7B%0A response = adapter.handleResponse(%0A jqXHR.status,%0A parseResponseHeaders(jqXHR.getAllResponseHeaders()),%0A payload,%0A requestData%0A );%0A %7D catch (error) %7B%0A return Promise.reject(error);%0A %7D%0A%0A if (response && response.isAdapterError) return Promise.reject(response);%0A return response;%0A%7D%0A%0Afunction ajaxError(adapter, jqXHR, requestData, responseData) %7B%0A runInDebug(function() %7B%0A const message =%0A %60The server returned an empty string for $%7BrequestData.method%7D %5C%0A $%7BrequestData.url%7D, which cannot be parsed into a valid JSON. Return %5C%0A either null or %7B%7D.%60;%0A const validJSONString =%0A !(responseData.textStatus === 'parsererror' && jqXHR.responseText === '');%0A warn(message, validJSONString, %7B%0A id: 'ds.adapter.returned-empty-string-as-JSON'%0A %7D);%0A %7D);%0A%0A let error;%0A%0A if (responseData.errorThrown instanceof Error) %7B%0A error = responseData.errorThrown;%0A %7D else if (responseData.textStatus === 'timeout') %7B%0A error = new TimeoutError();%0A %7D else if (responseData.textStatus === 'abort') %7B%0A error = new AbortError();%0A %7D else %7B%0A try %7B%0A error = adapter.handleResponse(%0A jqXHR.status,%0A parseResponseHeaders(jqXHR.getAllResponseHeaders()),%0A adapter.parseErrorResponse(jqXHR.responseText) %7C%7C%0A responseData.errorThrown,%0A requestData%0A );%0A %7D catch (e) %7B%0A error = e;%0A %7D%0A %7D%0A%0A return error;%0A%7D
%0A
|
5b90fcc4f3dbf0f6d5616ee0aef3769388f5f0e1
|
fix monosnap re
|
inline-images.js
|
inline-images.js
|
// (c) 2011-2013 Alexander Solovyov
// under terms of ISC License
var UNIQUE_CLASS_NAME = 'very-inline-node';
var IMAGE_SERVICES = [
{test: /\.(png|jpg|jpeg|gif)$/i},
{test: new RegExp('^https://i.chzbgr.com/')},
{test: new RegExp('^http://img-fotki.yandex.ru/get/')},
{test: new RegExp('^http://img.leprosorium.com/')},
{test: new RegExp('^https?://pbs.twimg.com/media/')},
{
test: new RegExp('^https?://(www\\.)?monosnap.com/image/(\\w+)', 'i'),
link: function(href, m) {
return 'http://api.monosnap.com/image/download?id=' + m[1];
}
},
{
// all links which do not have slash as a second character in path,
// because imgur.com/a/stuff is an album and not an image
test: new RegExp('^http://imgur.com/.[^/]', 'i'),
link: function(href, m) {
return href.replace('imgur.com', 'i.imgur.com') + '.jpg';
}
},
{
test: new RegExp('^https?://twitter.com/[^/]+/status/\\d+'),
link: function(href, m) {
return m[0];
},
createNode: function(href, cb) {
JSONP.get('https://api.twitter.com/1/statuses/oembed.json',
{url: href},
function(data) {
var div = document.createElement('div');
div.innerHTML = data.html;
cb(div);
});
}
}
];
function defaultCreateNode(href, cb) {
var img = document.createElement("img");
img.src = href;
img.setAttribute('style', 'max-width: 100%; max-height: 100%;');
cb(img);
}
function inlineNode(node, href, m, rule) {
var imageUrl = rule.link ? rule.link(href, m) : href;
var shouldScroll = coalescedHTML.shouldScroll || nearBottom();
var createNode = rule.createNode || defaultCreateNode;
createNode(imageUrl, function(inline) {
inline.className = UNIQUE_CLASS_NAME;
node.parentNode.replaceChild(inline, node);
inline.addEventListener('click', revertInline(node));
if (shouldScroll) {
inline.addEventListener('load', scrollToBottom);
}
});
}
function revertInline(orig) {
return function(e) {
if (e.target.tagName === 'A') {
return;
}
e.preventDefault();
e.stopPropagation();
var node = e.target;
do {
if (node.className === UNIQUE_CLASS_NAME) {
node.parentNode.replaceChild(orig, node);
break;
}
} while (node = node.parentNode);
};
}
function handleLink(e) {
var rule,
matches,
href = e.target.href;
for (var i = 0; i < IMAGE_SERVICES.length; i++) {
rule = IMAGE_SERVICES[i];
matches = typeof rule.test === 'function' ?
rule.test(href) :
href.match(rule.test);
if (matches) {
e.preventDefault();
e.stopPropagation();
return inlineNode(e.target, href, matches, rule);
}
}
}
document.getElementById('Chat').addEventListener('click', function(e) {
if (e.target.tagName !== 'A' ||
e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) {
return;
}
handleLink(e);
});
/*
* Lightweight JSONP fetcher
* Copyright 2010-2012 Erik Karlsson. All rights reserved.
* BSD licensed
*/
var JSONP = (function(){
var counter = 0, head, window = this, config = {};
function load(url, pfnError) {
var script = document.createElement('script'),
done = false;
script.src = url;
script.async = true;
var errorHandler = pfnError || config.error;
if (typeof errorHandler === 'function') {
script.onerror = function(ex){
errorHandler({url: url, event: ex});
};
}
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState ||
this.readyState === "loaded" ||
this.readyState === "complete") ) {
done = true;
script.onload = script.onreadystatechange = null;
if (script && script.parentNode) {
script.parentNode.removeChild(script);
}
}
};
if ( !head ) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild( script );
}
function jsonp(url, params, callback, callbackName) {
var query = (url||'').indexOf('?') === -1 ? '?' : '&', key;
callbackName = (callbackName || config.callbackName || 'callback');
var uniqueName = callbackName + "_json" + (++counter);
params = params || {};
for (key in params) {
if ( params.hasOwnProperty(key) ) {
query += encodeURIComponent(key) + "=" +
encodeURIComponent(params[key]) + "&";
}
}
window[uniqueName] = function(data){
callback(data);
window[uniqueName] = null;
try {
delete window[uniqueName];
} catch (e) {}
};
load(url + query + callbackName + '=' + uniqueName);
return uniqueName;
}
function setDefaults(obj){
config = obj;
}
return {get: jsonp, init: setDefaults};
}());
|
JavaScript
| 0 |
@@ -432,16 +432,18 @@
tps?://(
+?:
www%5C%5C.)?
|
f70cd70905926679debbe93c08d027ab2093ef62
|
Update Jumbotron.js
|
app/components/Jumbotron.js
|
app/components/Jumbotron.js
|
var React = require("react");
var Search = React.createClass({
render: function() {
return (
<div className="jumbotron">
<h1>The History Of Remedan</h1>
<p>Ramadan is a holy month of fasting, introspection and prayer for Muslims, the followers of Islam. Fasting is one of the five fundamental principles of Islam. Each day during Ramadan, Muslims do not eat or drink from sunrise to sunset. They are also supposed to avoid impure thoughts and bad behavior. Muslims break their daily fasts by sharing meals with family and friends, and the end of Ramadan is celebrated with a three-day festival known as Eid al-Fitr, one of Islam’s major holidays.</p>
</div>
);
}
});
module.exports = search;
|
JavaScript
| 0 |
@@ -142,541 +142,53 @@
%3Ch1%3E
-The History Of Remedan%3C/h1%3E%0A %3Cp%3ERamadan is a holy month of fasting, introspection and prayer for Muslims, the followers of Islam. Fasting is one of the five fundamental principles of Islam. Each day during Ramadan, Muslims do not eat or drink from sunrise to sunset. They are also supposed to avoid impure thoughts and bad behavior. Muslims break their daily fasts by sharing meals with family and friends, and the end of Ramadan is celebrated with a three-day festival known as Eid al-Fitr, one of Islam%E2%80%99s major holidays.%3C/p%3E
+Search The Item You Looking For?%3C/h1%3E%0A
%0A
|
c283eea20997ffcbc5b7167fbdde2c406673c915
|
Use the right hook for ocre-step initialisation
|
app/components/ocre-step.js
|
app/components/ocre-step.js
|
import Ember from 'ember';
import _ from 'lodash/lodash';
import steps from '../ressources/ocre-quest';
import OcreItem from '../objects/ocre-item';
export default Ember.Component.extend({
progress: '',
stepIndex: 0,
target: 0,
isFiltered: false,
onChange: () => {},
parsedItems: null,
progressBars: null,
actions: {
update(item, delta) {
let updatedValue = item.get('value') + delta;
let progress = this.get('progress');
progress = progress.split('');
progress[item.get('itemIndex')] = updatedValue;
progress = progress.join('');
item.set('value', updatedValue);
this._updateProgressBars();
this.get('onChange')(progress, this.get('stepIndex'));
Ember.run.debounce(this, '_hideCompletedItems', 5000);
},
updateAll(delta) {
const updatedProgress =_.reduce(this.get('parsedItems'), (progress, item) => {
const oldValue = item.get('value');
const updatedValue = oldValue + delta;
if (updatedValue <= 9 && updatedValue >= 0) {
item.set('value', updatedValue);
return progress + updatedValue;
}
return progress + oldValue;
}, '');
this._updateProgressBars();
this.get('onChange')(updatedProgress, this.get('stepIndex'));
Ember.run.debounce(this, '_hideCompletedItems', 5000);
}
},
didReceiveAttrs() {
if (this.get('parsedItems')) {
return;
}
this.set('parsedItems', _.map(steps[this.get('stepIndex') - 1], (item, index) => {
return OcreItem.create({
stepIndex: this.get('stepIndex'),
itemIndex: index,
value: parseInt(this.get('progress')[index], 10),
target: this.get('target')
});
}));
this._updateProgressBars();
},
isFilteredObserver: Ember.observer('isFiltered', function() {
if (this.get('isFiltered')) {
this._hideCompletedItems();
} else {
this._showItems();
}
}),
_hideCompletedItems() {
const $items = this.$('._ocre-item');
const $completedItems = this.$('._ocre-item[data-completed="true"]');
$completedItems.hide();
if ($items.length === $completedItems.length) {
this.$().hide();
}
},
_showItems() {
this.$('._ocre-item').show();
this.$().show();
},
_updateProgressBars() {
const parsedItems = this.get('parsedItems');
this.set('progressBars', _.times(this.get('target'), index => {
return _.filter(parsedItems, parsedItem => parsedItem.get('value') > index).length / parsedItems.length;
}));
},
targetObserver: Ember.observer('target', function() {
const target = this.get('target');
_.each(this.get('parsedItems'), parsedItem => {
parsedItem.set('target', target);
});
this._updateProgressBars();
}),
minimum: Ember.computed('progress', function() {
const progress = this.get('progress');
return Math.min(..._.map(progress.split(''), number => parseInt(number, 10)));
}),
sanitizedSummary: Ember.computed('parsedItems', function() {
return _.map(this.get('parsedItems'), parsedItem => parsedItem.sanitizedName).join('-');
}),
cantGloballyAdd: Ember.computed('progress', function() {
return /^9+$/.test(this.get('progress'));
}),
cantGloballyRemove: Ember.computed('progress', function() {
return /^0+$/.test(this.get('progress'));
})
});
|
JavaScript
| 0 |
@@ -1541,97 +1541,16 @@
-didReceiveAttrs() %7B%0A if (this.get('parsedItems')) %7B%0A return;%0A %7D%0A
+init() %7B
%0A
@@ -1927,24 +1927,60 @@
gressBars();
+%0A%0A this._super(...arguments);
%0A %7D,%0A%0A
|
3a0269092389274c7458375b26dbfb0a2288499c
|
add styled-components theme provider
|
app/containers/App/index.js
|
app/containers/App/index.js
|
import React from 'react'
import Helmet from 'react-helmet'
import styled from 'styled-components'
import { Switch, Route } from 'react-router-dom'
import Header from 'components/Header'
import Footer from 'components/Footer'
import HomePage from 'containers/HomePage/Loadable'
import FeaturePage from 'containers/FeaturePage/Loadable'
import NotFoundPage from 'containers/NotFoundPage/Loadable'
const AppWrapper = styled.div`
max-width: calc(768px + 16px * 2);
margin: 0 auto;
display: flex;
min-height: calc(100vh - 172px); // min height for App wrapper should account for nav and footer
padding: 0 16px;
flex-direction: column;
`
export default function App () {
return (
<div>
<Helmet
titleTemplate='%s - React.js Boilerplate'
defaultTitle='React.js Boilerplate'
>
<meta name='description' content='A React.js Boierlplate application with Redux' />
</Helmet>
<Header />
<AppWrapper>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/features' component={FeaturePage} />
<Route path='' component={NotFoundPage} />
</Switch>
</AppWrapper>
<Footer />
</div>
)
}
|
JavaScript
| 0 |
@@ -66,16 +66,35 @@
t styled
+, %7B ThemeProvider %7D
from 's
@@ -410,16 +410,180 @@
dable'%0A%0A
+const theme = %7B%0A primary: '#434C5E',%0A lightShade: '#E9E6D9',%0A lightAccent: '#77938D',%0A darkAccent: '#5472A1',%0A darkShade: '#1B1720',%0A whiteMain: '#FAFAFA'%0A%7D%0A%0A
const Ap
@@ -705,18 +705,18 @@
00vh - 1
-72
+60
px); //
@@ -868,16 +868,52 @@
eturn (%0A
+ %3CThemeProvider theme=%7Btheme%7D%3E%0A
%3Cdiv
@@ -914,16 +914,18 @@
%3Cdiv%3E%0A
+
%3CH
@@ -930,16 +930,18 @@
%3CHelmet%0A
+
@@ -990,16 +990,18 @@
+
+
defaultT
@@ -1034,18 +1034,22 @@
'%0A
-%3E%0A
+ %3E%0A
@@ -1138,16 +1138,18 @@
%3E%0A
+
%3C/Helmet
@@ -1156,16 +1156,18 @@
%3E%0A
+
+
%3CHeader
@@ -1165,24 +1165,26 @@
%3CHeader /%3E%0A
+
%3CAppWr
@@ -1198,16 +1198,18 @@
+
%3CSwitch%3E
@@ -1205,24 +1205,26 @@
%3CSwitch%3E%0A
+
%3CR
@@ -1269,32 +1269,34 @@
e%7D /%3E%0A
+
+
%3CRoute path='/fe
@@ -1332,32 +1332,34 @@
e%7D /%3E%0A
+
%3CRoute path='' c
@@ -1393,16 +1393,18 @@
+
+
%3C/Switch
@@ -1401,24 +1401,26 @@
%3C/Switch%3E%0A
+
%3C/AppW
@@ -1433,16 +1433,18 @@
%3E%0A
+
+
%3CFooter
@@ -1454,15 +1454,38 @@
+
%3C/div%3E%0A
+ %3C/ThemeProvider%3E%0A
)%0A
|
2e4f0c043868c764fa2719ab11964a929d74bf01
|
Set organization code to fhirdemo
|
app/domain/ebmeds/System.js
|
app/domain/ebmeds/System.js
|
var moment = require('moment');
var System = {
create: function(activityInstance, user, language, nation) {
var now = moment();
return {
"User": {
"HealthCareRole": user.startsWith("Patient") ? "Citizen" : "Physician",
"HealthCareOrganization": {
"CodeValue": {},
"CodeSystem": {},
"CodeSystemVersion": {}
},
"HealthCareSpecialty": {
"CodeValue": {},
"CodeSystem": {},
"CodeSystemVersion": {}
},
"Language": {
"CodeValue": language,
"CodeSystem": "2.16.840.1.113883.6.99",
"CodeSystemVersion": {}
},
"Nation": {
"CodeValue": nation,
"CodeSystem": "ISO 3166-1",
"CodeSystemVersion": {}
}
},
"Application": {
"QueryID": activityInstance,
"FeedbackType": "S",
"CheckMoment": {
"CheckDate": now.format('YYYY-MM-DD'),
"CheckTime": now.format('HH:mm:ss')
}
}
};
}
};
module.exports = System;
|
JavaScript
| 0.000002 |
@@ -333,34 +333,42 @@
%22CodeValue%22:
-%7B%7D
+%22fhirdemo%22
,%0A
|
21ba4f40af1545daa43d24e4d6bc5df403a8ed2e
|
fix error messsage
|
lib/novaform/lib/output.js
|
lib/novaform/lib/output.js
|
var AWSResource = require('./awsresource')
, fn = require('./fn')
, util = require('util');
function Output(name, value, description) {
if (!(this instanceof Output)) {
return new Output(name, value, description);
}
if (!(value instanceof AWSResource) && !(value instanceof fn.Function) && !(typeof value === 'string')) {
var msg = util.format('Output "%s" value for can only be a string or another resource or a join, getatt or an other function. '+
'Got "%s" instead ("%s")', name, typeof value, value);
throw new Error(msg);
}
if (description && !(typeof description !== 'string')) {
throw new Error('Output description must be string');
}
this.name = name;
this.value = value;
this.description = description;
}
Output.prototype.toObject = function() {
value = this.value;
if (value instanceof AWSResource) {
value = fn.ref(value);
}
return {
Value : value,
Description : this.description,
};
}
module.exports = Output;
|
JavaScript
| 0.000001 |
@@ -398,12 +398,8 @@
lue
-for
can
|
d95c8aad0f41b3ebf905e1c874b230bcebd91f5e
|
Update ai.js
|
mixly_arduino/blockly/generators/mixpy_python/ai.js
|
mixly_arduino/blockly/generators/mixpy_python/ai.js
|
'use strict';
goog.provide('Blockly.Python.AI');
goog.require('Blockly.Python');
Blockly.Python.AI_ChooseAndGet = function(){
var type = this.getFieldValue('TYPE');
Blockly.Python.definitions_['import_FileDialog'] = 'import FileDialog';
var code = 'FileDialog.' + type + '()';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_client = function(){
var ctype = this.getFieldValue('CTYPE');
Blockly.Python.definitions_['import_aip_' + ctype] = 'from aip import '+ ctype;
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var app_id = Blockly.Python.valueToCode(this, 'APP_ID', Blockly.Python.ORDER_ATOMIC);
var api_key = Blockly.Python.valueToCode(this, 'API_KEY', Blockly.Python.ORDER_ATOMIC);
var secret_key = Blockly.Python.valueToCode(this, 'SECRET_KEY', Blockly.Python.ORDER_ATOMIC);
var code = v + ' = ' + ctype + '(' + app_id + ', ' + api_key + ', ' + secret_key + ')\n';
return code;
};
Blockly.Python.AI_Speech_synthesis = function(){
Blockly.Python.definitions_['import_aip_AipSpeech'] = 'from aip import AipSpeech';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var s = Blockly.Python.valueToCode(this, 'STR', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.synthesis(' + s + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Speech_asr = function(){
Blockly.Python.definitions_['import_aip_AipSpeech'] = 'from aip import AipSpeech';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var f = Blockly.Python.valueToCode(this, 'FUNC', Blockly.Python.ORDER_ATOMIC);
var fn = Blockly.Python.valueToCode(this, 'FILE', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.'+ f +'(' + fn + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_ImageClassify = function(){
Blockly.Python.definitions_['import_aip_AipImageClassify'] = 'from aip import AipImageClassify';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var addr = Blockly.Python.valueToCode(this, 'ADDR', Blockly.Python.ORDER_ATOMIC);
var f = Blockly.Python.valueToCode(this, 'FUNC', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.'+ f +'(' + addr + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Ocr = function(){
Blockly.Python.definitions_['import_aip_Ocr'] = 'from aip import Ocr';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var addr = Blockly.Python.valueToCode(this, 'ADDR', Blockly.Python.ORDER_ATOMIC);
var f = Blockly.Python.valueToCode(this, 'FUNC', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.'+ f +'(' + addr + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp = function(){
Blockly.Python.definitions_['import_aip_Nlp'] = 'from aip import Nlp';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var s = Blockly.Python.valueToCode(this, 'STR', Blockly.Python.ORDER_ATOMIC);
var f = Blockly.Python.valueToCode(this, 'FUNC', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.'+ f +'(' + s + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp_Sim = function(){
Blockly.Python.definitions_['import_aip_Nlp'] = 'from aip import Nlp';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var s1 = Blockly.Python.valueToCode(this, 'STR1', Blockly.Python.ORDER_ATOMIC);
var s2 = Blockly.Python.valueToCode(this, 'STR2', Blockly.Python.ORDER_ATOMIC);
var f = Blockly.Python.valueToCode(this, 'FUNC', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.'+ f +'(' + s1 + ',' + s2 + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp_Topic = function(){
Blockly.Python.definitions_['import_aip_Nlp'] = 'from aip import Nlp';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var s1 = Blockly.Python.valueToCode(this, 'STR1', Blockly.Python.ORDER_ATOMIC);
var s2 = Blockly.Python.valueToCode(this, 'STR2', Blockly.Python.ORDER_ATOMIC);
var code = v + '.topic(' + s1 + ',' + s2 + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp_newsSummary = function(){
Blockly.Python.definitions_['import_aip_Nlp'] = 'from aip import Nlp';
var v = Blockly.Python.valueToCode(this, 'SUB', Blockly.Python.ORDER_ATOMIC);
var s = Blockly.Python.valueToCode(this, 'STR', Blockly.Python.ORDER_ATOMIC);
var n = Blockly.Python.valueToCode(this, 'LEN', Blockly.Python.ORDER_ATOMIC);
var attr = Blockly.Python.valueToCode(this, 'ATTR', Blockly.Python.ORDER_ATOMIC) || '{}';
var code = v + '.newsSummary(' + s + ',' + n + ', options=' + attr + ')';
return [code,Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_ImageClassify_Func = function () {
var code = this.getFieldValue('TYPE');
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Ocr_Func = function () {
var code = this.getFieldValue('TYPE');
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp_Func = function () {
var code = this.getFieldValue('TYPE');
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python.AI_Nlp_Func_sim = function () {
var code = this.getFieldValue('TYPE');
return [code, Blockly.Python.ORDER_ATOMIC];
};
|
JavaScript
| 0.000001 |
@@ -419,32 +419,96 @@
e('CTYPE');%0A
+Blockly.Python.definitions_%5B'import_aip'%5D = 'import aip';%0A //
Blockly.Python.d
@@ -943,24 +943,25 @@
var code =
+
v + ' = ' +
@@ -957,24 +957,32 @@
v + ' = ' +
+'aip.' +
ctype + '('
|
c6cffcfa07c35a4e9a07cd7bdce1b4852b36c114
|
Update sl.js
|
source/js/Core/Language/locale/sl.js
|
source/js/Core/Language/locale/sl.js
|
/* Slovenian LANGUAGE SLOVENIAN
================================================== */
if (typeof VMM != 'undefined') {
VMM.Language = {
lang: "sl",
api: {
wikipedia: "sl"
},
date: {
month: ["januar", "februar", "marec", "april", "maj", "junij", "julij", "avgust", "september", "oktober", "november", "december"],
month_abbr: ["jan.", "feb.", "marec", "april", "maj", "junij", "july", "avg.", "sept.", "okt.", "nov.", "dec."],
day: ["nedelja", "ponedeljek", "torek", "sreda", "čertek", "petek", "sobota"],
day_abbr: ["ned.", "pon.", "tor.", "sre.", "Čet.", "pet.", "sob."]
},
dateformats: {
year: "yyyy",
month_short: "mmm",
month: "mmmm yyyy",
full_short: "d mmm",
full: "d mmmm yyyy",
time_short: "h:MM:ss TT",
time_no_seconds_short: "h:MM",
time_no_seconds_small_date: "h:MM' 'd mmmm' 'yyyy",
full_long: "d mmm yyyy 'ob' hh:MM",
full_long_small_date: "hh:MM' d mmm yyyy"
},
messages: {
loading_timeline: "Nalagam časovni trak... ",
return_to_title: "Nazaj na naslov",
expand_timeline: "Razširi časovni trak",
contract_timeline: "Pokrči časovni trak",
wikipedia: "Vir Wikipedija",
loading_content: "Nalaganje vsebine",
loading: "Nalaganje"
}
}
}
|
JavaScript
| 0 |
@@ -570,9 +570,9 @@
%22, %22
-%C4%8C
+%C4%8D
et.%22
|
1b685f1f6a2780d909d3761e96f551c33d2e4540
|
Add ChemPhysics as a coming soon hexagon in the filter.
|
app/js/app/services/Tags.js
|
app/js/app/services/Tags.js
|
/**
* Copyright 2014 Ian Davies
*
* 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.
*/
define([], function() {
return function TagsConstructor() {
this.tagArray = [
// Subjects
{
id: "physics"
}, {
id: "maths"
},
// Physics fields
{
id: "mechanics",
parent: "physics"
}, {
id: "waves",
parent: "physics",
enabled: false,
comingSoon: true,
}, {
id: "fields",
parent: "physics"
}, {
id: "circuits",
parent: "physics",
enabled: false,
comingSoon: true,
},
// Mechanics topics
{
id: "statics",
parent: "mechanics"
}, {
id: "dynamics",
parent: "mechanics"
}, {
id: "shm",
title: "SHM",
parent: "mechanics"
}, {
id: "angular_motion",
parent: "mechanics"
}, {
id: "circular_motion",
parent: "mechanics"
}, {
id: "kinematics",
parent: "mechanics"
},
// Fields topics
{
id: "electric",
parent: "fields"
}, {
id: "magnetic",
parent: "fields"
}, {
id: "gravitational",
parent: "fields"
}, {
id: "combined",
parent: "fields"
},
// Maths fields
{
id: "geometry",
parent: "maths"
}, {
id: "calculus",
parent: "maths"
}, {
id: "algebra",
parent: "maths"
}, {
id: "functions",
parent: "maths",
comingSoon:true,
}, {
id: "probability",
parent: "maths",
comingSoon:true,
},
// Geometry topics
{
id: "geom_vectors",
title: "Vectors",
parent: "geometry"
}, {
id: "trigonometry",
parent: "geometry"
}, {
id: "shapes",
parent: "geometry"
}, {
id: "symmetry",
parent: "geometry",
comingSoon: true,
},
// Calculus topics
{
id: "integration",
parent: "calculus"
}, {
id: "differentiation",
parent: "calculus"
}, {
id: "differential_eq",
title: "Differential Equations",
parent: "calculus"
},
// Algebra topics
{
id: "simultaneous",
title: "Simultaneous Equations",
parent: "algebra"
}, {
id: "quadratics",
parent: "algebra"
}, {
id: "manipulation",
parent: "algebra"
}, {
id: "series",
parent: "algebra"
},
// Functions topics
{
id: "special",
parent: "functions"
}, {
id: "trigonometric",
parent: "functions"
}, {
id: "curve_sketching",
parent: "functions"
},
// Probability topics
{
id: "means",
parent: "probability"
}, {
id: "prob_functions",
title: "Functions",
parent: "probability"
}, {
id: "distributions",
parent: "probability"
}
];
this.getById = function(id) {
for (var i in this.tagArray) {
if (this.tagArray[i].id === id) {
return this.tagArray[i];
}
}
};
this.getSubjectTag = function(tagArray) {
if (tagArray == null) return null;
for (var i in tagArray) {
var tag = this.getById(tagArray[i]);
if (tag != null && tag.type === "subject") {
return tag;
}
}
};
this.getDeepestTag = function(tagArray) {
if (tagArray == null) return null;
var deepestTag = null;
for (var i in tagArray) {
var tag = this.getById(tagArray[i]);
if (tag != null && (deepestTag == null || tag.level > deepestTag.level)) {
deepestTag = tag;
}
}
return deepestTag;
};
this.getDescendents = function(tagId) {
var descs = [];
for (var i in this.tagArray) {
if (this.tagArray[i].parent == tagId) {
descs.push(this.tagArray[i]);
descs = descs.concat(this.getDescendents(this.tagArray[i].id));
}
}
return descs;
}
var tagHeirarchy = ["subject", "field", "topic"];
var generateTitle = function(tag) {
if (tag.title)
return tag.title;
return tag.id.replace(/_/g, " ").replace(/\w*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
for (var i in this.tagArray) {
this.tagArray[i].title = generateTitle(this.tagArray[i]);
var j = 0;
if (this.tagArray[i].parent) {
var parent = this.getById(this.tagArray[i].parent);
j++;
while (parent.parent) {
j++;
parent = this.getById(parent.parent);
}
}
this.tagArray[i].type = tagHeirarchy[j];
this.tagArray[i].level = j;
}
};
});
|
JavaScript
| 0 |
@@ -1042,24 +1042,154 @@
true,%0A%09%09%09%7D,
+ %0A%09%09%09%7B%0A%09%09%09%09id: %22chemphysics%22,%0A%09%09%09%09title: %22Chemical Physics%22,%0A%09%09%09%09parent: %22physics%22,%0A%09%09%09%09enabled: false,%0A%09%09%09%09comingSoon: true%0A%09%09%09%7D,
%0A%0A%09%09%09// Mech
|
4fcc18c8969f491fd461d3700b7e8ea9e490a7ce
|
Remove depreciated props from v1.0
|
src/mixins/props.js
|
src/mixins/props.js
|
/**
* Component props
*/
const mixin = {
props: {
// Depreciated
arrows: {
type: Boolean,
default: true
},
/**
* Set the carousel to be the navigation of other carousels
*/
asNavFor: {
type: Array,
default: function () {
return []
}
},
/**
* Enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Autoplay interval in milliseconds
*/
autoplaySpeed: {
type: Number,
default: 3000
},
/**
* Enable centered view when slidesToShow > 1
*/
centerMode: {
type: Boolean,
default: false
},
/**
* Slides padding in center mode
*/
centerPadding: {
type: String,
default: '15%'
},
/**
* Slide change delay in milliseconds
*/
changeDelay: {
type: Number,
default: 0
},
/**
* Enable dot indicators/pagination
*/
dots: {
type: Boolean,
default: true
},
/**
* Enable fade effect
*/
fade: {
type: Boolean,
default: false
},
/**
* Infinite loop sliding
*/
infinite: {
type: Boolean,
default: true
},
/**
* Index of slide to start on
*/
initialSlide: {
type: Number,
default: 0
},
/**
* Enable mobile first calculation for responsive settings
*/
mobileFirst: {
type: Boolean,
default: true
},
/**
* Enable prev/next navigation buttons
*/
navButtons: {
type: Boolean,
default: true
},
// Depreciated
nextArrow: {
type: String,
default: null
},
/**
* All settings as one object
*/
options: {
type: Object,
default: () => null
},
/**
* Pause autoplay when a dot is hovered
*/
pauseOnDotsHover: {
type: Boolean,
default: false
},
/**
* Pause autoplay when a slide is hovered
*/
pauseOnHover: {
type: Boolean,
default: true
},
// Depreciated
prevArrow: {
type: String,
default: null
},
/**
* Object containing breakpoints and settings objects
*/
responsive: {
type: Array,
default: () => null
},
/**
* Enable right-to-left mode
*/
rtl: {
type: Boolean,
default: false
},
/**
* Number of slides to scroll
*/
slidesToScroll: {
type: Number,
default: 1
},
/**
* Number of slides to show
*/
slidesToShow: {
type: Number,
default: 1
},
/**
* Slide animation speed in milliseconds
*/
speed: {
type: Number,
default: 300
},
/**
* Transition timing function
* Available: ease, linear, ease-in, ease-out, ease-in-out
*/
timing: {
type: String,
default: 'ease'
},
/**
* Disable Agile carousel
*/
unagile: {
type: Boolean,
default: false
}
},
computed: {
// Initial settings based on props
initialSettings: function () {
// options prop is excluded
const { options, ...initialSettings } = this.$props
return initialSettings
}
}
}
export default mixin
|
JavaScript
| 0 |
@@ -50,78 +50,8 @@
: %7B%0A
-%09%09// Depreciated%0A%09%09arrows: %7B%0A%09%09%09type: Boolean,%0A%09%09%09default: true%0A%09%09%7D,%0A%0A
%09%09/*
@@ -1358,80 +1358,8 @@
%7D,%0A%0A
-%09%09// Depreciated%0A%09%09nextArrow: %7B%0A%09%09%09type: String,%0A%09%09%09default: null%0A%09%09%7D,%0A%0A
%09%09/*
@@ -1694,80 +1694,8 @@
%7D,%0A%0A
-%09%09// Depreciated%0A%09%09prevArrow: %7B%0A%09%09%09type: String,%0A%09%09%09default: null%0A%09%09%7D,%0A%0A
%09%09/*
|
145277d83af7658604a1e936912ecb5fa938e220
|
correct indentation
|
lib/properties.js
|
lib/properties.js
|
/*
* properties
*
* Copyright (c) 2013 Matt Steele
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs');
exports.of = function() {
var objs = {};
var makeKeys = function(j) {
if(j && j.indexOf('#') !== 0) {
var splitIndex = j.indexOf('=');
var key = j.substring(0, splitIndex);
var value = j.substring(splitIndex + 1);
objs[key.trim()] = value.trim();
}
};
/* adds a file to the properties */
var addFile = function(file) {
var data = fs.readFileSync(file, 'utf-8');
var items = data.split(/\r?\n/);
items.forEach(makeKeys);
};
for (var i=0; i < arguments.length; i++) {
addFile(arguments[i]);
}
var get = function(key) {
if (objs.hasOwnProperty(key)) {
return typeof objs[key] === 'undefined' ? '' : interpolate(objs[key]);
}
return undefined;
};
var set = function(key, value) {
objs[key] = value;
};
var interpolate = function(s) {
return s
.replace(/\\\\/g, '\\')
.replace(/\$\{([A-Za-z0-9\.]*)\}/g, function(match) {
return get(match.substring(2, match.length - 1));
});
};
/* gets all the keys of the property file */
var getKeys = function () {
var keys = [];
for (var key in objs) {
keys.push(key);
}
return keys;
};
/* reset the properties */
var reset = function() {
objs = {};
};
return {
get: get,
set: set,
interpolate: interpolate,
getKeys : getKeys,
reset : reset,
addFile : addFile
};
};
|
JavaScript
| 0.003018 |
@@ -166,16 +166,18 @@
on() %7B%0D%0A
+
var ob
@@ -186,20 +186,20 @@
= %7B%7D;%0D%0A
-
%0D%0A
+
var ma
@@ -225,16 +225,18 @@
) %7B%0D%0A
+
if(j &&
@@ -256,24 +256,27 @@
) !== 0) %7B%0D%0A
+
var spl
@@ -303,24 +303,27 @@
'=');%0D%0A
+
+
var key = j.
@@ -345,24 +345,27 @@
litIndex);%0D%0A
+
var val
@@ -400,24 +400,27 @@
+ 1);%0D%0A
+
+
objs%5Bkey.tri
@@ -444,19 +444,23 @@
();%0D%0A
+
%7D%0D%0A
+
%7D;%0D%0A%0D%0A
|
9082a887ca33afaf7346de042dc322e52d80a35b
|
Fix a JavaScript error in personal_options.js for Chrome OS.
|
chrome/browser/resources/options/personal_options.js
|
chrome/browser/resources/options/personal_options.js
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('options', function() {
var OptionsPage = options.OptionsPage;
//
// PersonalOptions class
// Encapsulated handling of personal options page.
//
function PersonalOptions() {
OptionsPage.call(this, 'personal', templateData.personalPage,
'personalPage');
// State variables.
this.syncEnabled = false;
this.hasSetupCompleted = false;
}
cr.addSingletonGetter(PersonalOptions);
PersonalOptions.prototype = {
// Inherit PersonalOptions from OptionsPage.
__proto__: options.OptionsPage.prototype,
// Initialize PersonalOptions page.
initializePage: function() {
// Call base class implementation to starts preference initialization.
OptionsPage.prototype.initializePage.call(this);
$('sync-customize').onclick = function(event) {
OptionsPage.showPageByName('sync');
};
$('start-sync').onclick = function(event) {
//TODO(sargrass): Show start-sync subpage, after dhg done.
};
Preferences.getInstance().addEventListener('sync.has_setup_completed',
function(event) {
var personalOptions = PersonalOptions.getInstance();
personalOptions.hasSetupCompleted = event.value;
if (personalOptions.hasSetupCompleted)
chrome.send('getSyncStatus');
personalOptions.updateControlsVisibility_();
});
$('showpasswords').onclick = function(event) {
PasswordsExceptions.load();
OptionsPage.showPageByName('passwordsExceptions');
OptionsPage.showTab($('passwords-nav-tab'));
chrome.send('coreOptionsUserMetricsAction',
['Options_ShowPasswordsExceptions']);
};
$('autofill_options').onclick = function(event) {
OptionsPage.showPageByName('autoFillOptions');
chrome.send('coreOptionsUserMetricsAction',
['Options_ShowAutoFillSettings']);
};
if (!cr.isChromeOS) {
$('stop-sync').onclick = function(event) {
AlertOverlay.show(localStrings.getString('stop_syncing_title'),
localStrings.getString('stop_syncing_explanation'),
localStrings.getString('stop_syncing_confirm_button_label'),
undefined,
function() { chrome.send('stopSyncing'); });
};
$('import_data').onclick = function(event) {
OptionsPage.showOverlay('importDataOverlay');
chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
};
}
if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
$('themes_GTK_button').onclick = function(event) {
chrome.send('themesSetGTK');
};
$('themes_set_classic').onclick = function(event) {
chrome.send('themesReset');
};
$('themes-gallery').onclick = function(event) {
chrome.send('themesGallery');
}
}
if (cr.isMac || cr.isWindows || cr.isChromeOS) {
$('themes_reset').onclick = function(event) {
chrome.send('themesReset');
};
$('themes-gallery').onclick = function(event) {
chrome.send('themesGallery');
}
}
if (cr.isChromeOS) {
chrome.send('loadAccountPicture');
}
},
syncStatusCallback_: function(statusString) {
$('synced_to_user_with_time').textContent = statusString;
},
setGtkThemeButtonEnabled_: function(enabled) {
if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
$('themes_GTK_button').disabled = !enabled;
}
},
setClassicThemeButtonEnabled_: function(enabled) {
$('themes_set_classic').disabled = !enabled;
},
updateControl_: function(control, visible) {
if (visible)
control.classList.remove('hidden');
else
control.classList.add('hidden');
},
updateControlsVisibility_: function() {
this.updateControl_($('synced-controls'),
this.syncEnabled && this.hasSetupCompleted);
this.updateControl_($('not-synced-controls'),
this.syncEnabled && !this.hasSetupCompleted);
this.updateControl_($('sync-disabled-controls'), !this.syncEnabled);
},
};
// Enables synchronization option.
// NOTE: by default synchronization option is disabled, so handler should
// explicitly enable it.
PersonalOptions.enableSync = function(enabled) {
var personalOptions = PersonalOptions.getInstance();
personalOptions.syncEnabled = enabled;
personalOptions.updateControlsVisibility_();
};
PersonalOptions.syncStatusCallback = function(statusString) {
PersonalOptions.getInstance().syncStatusCallback_(statusString);
};
PersonalOptions.setGtkThemeButtonEnabled = function(enabled) {
PersonalOptions.getInstance().setGtkThemeButtonEnabled_(enabled);
};
PersonalOptions.setClassicThemeButtonEnabled = function(enabled) {
PersonalOptions.getInstance().setClassicThemeButtonEnabled_(enabled);
};
PersonalOptions.setAccountPicture = function(image) {
$('account-picture').src = image;
}
// Export
return {
PersonalOptions: PersonalOptions
};
});
|
JavaScript
| 0.999999 |
@@ -3820,24 +3820,96 @@
(enabled) %7B%0A
+ if (!cr.isChromeOS && navigator.platform.match(/linux%7CBSD/i)) %7B%0A
$('the
@@ -3943,24 +3943,32 @@
= !enabled;%0A
+ %7D%0A
%7D,%0A%0A
@@ -5451,13 +5451,12 @@
s%0A %7D;%0A%0A%7D);%0A
-%0A
|
8964507088534cf1b292e73c9b2d2fcad85d8140
|
reformat indents and clue to error for console
|
app/js/rockpaperscissors.js
|
app/js/rockpaperscissors.js
|
////////////////////////////////////////////////
/* Provided Code - Please Don't Edit */
////////////////////////////////////////////////
'use strict';
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
} else if (randomNumber < 0.66) {
return "paper";
} else {
return "scissors";
}
}
////////////////////////////////////////////////
/* Write Your Code Below */
////////////////////////////////////////////////
function getplayerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `getInput()`.
return move || getInput();
}
function getComputerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
return move || randomPlay();
}
function getWinner(playerMove,computerMove) { //what given, what want?
var winner; // can be computer, player or tie.
// Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
// Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
// The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
if (playerMove === computerMove) {
winner = 'tie';
}
else {
if (playerMove == 'rock' && computerMove == 'scissors') {
winner = 'player';
}
else if (playerMove == 'rock' && computerMove == 'paper') {
winner = 'computer';
}
else if (playerMove == 'scissors' && computerMove == 'paper') {
winner = 'player';
}
else if (playerMove == 'scissors' && computerMove == 'rock') {
winner = 'computer';
}
else if (playerMove == 'paper' && computerMove == 'rock') {
winner = 'player';
}
else if (playerMove == 'paper' && computerMove == 'scissors') {
winner = 'computer';
}
else winner = 'something went wrong';
}
return winner;
}
function playToFive() {
console.log("Let's play Rock, Paper, Scissors");
var playerWins = 0;
var computerWins = 0;
// Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
/* YOUR CODE HERE */
return [playerWins, computerWins];
}
|
JavaScript
| 0 |
@@ -2450,17 +2450,28 @@
rong
+ with getWinner
';%0A%7D%0A
-
retu
|
557b53035b811d46d75b6b7ced6cf7600c4d256a
|
Update sanno.js
|
commands/sanno.js
|
commands/sanno.js
|
const Discord = require('discord.js');
exports.run = (client, message) => {
const modlog = client.channels.find('name', 'pie-log');
const anno2 = client.channels.find('name', 'announcements');
let say = message.content.split(" ").join(" ").slice(6)
if (say.length < 1) return message.reply('Please specify on what I have to say.').catch(console.error);
message.delete()
client.channels.get(anno2.id).send({embed: {
color: 0xff0000,
title: `Server Announcement`,
description: `**Announcer:** ${message.author}\n**Message:** ${say}`,
}
})
client.channels.get(modlog.id).send({embed: {
color: 0x0000FF,
title: "Command input",
description: `\n\n**Username:** \n${message.author.username} <${message.author}>\n**Command:** ;sanno${say}`,
timestamp: new Date(),
footer: {
icon_url: `${message.author.avatarURL}`,
text: `User: ${message.author.username}`
}
}
})
client.channels.get(modlog.id).send('@everyone')
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 2
};
exports.help = {
name: 'sanno',
description: 'Announces something under the channel #announcements',
usage: 'sanno message'
};
|
JavaScript
| 0.000001 |
@@ -933,38 +933,37 @@
nt.channels.get(
-modlog
+anno2
.id).send('@ever
|
4822a490951160a2e342e0127fbb55710b7408a1
|
fix agent response override on cache hit
|
lib/read-cache.js
|
lib/read-cache.js
|
import hydrate from './hydrate'
export default function (req) {
return function (value) {
return new Promise((resolve, reject) => {
if (!value) {
const error = new Error()
error.reason = 'cache-miss'
error.message = 'Value not found from cache'
return reject(error)
}
// override request end callback
req.end((err, res) => {
const callback = req.callback // main callback
if (err) {
return reject(callback(err, res))
}
resolve(callback(null, res))
})
// hydrate pseudo xhr from cached value
req.xhr = hydrate(value)
req.emit('end')
})
}
}
|
JavaScript
| 0.000004 |
@@ -367,12 +367,19 @@
req.
-end(
+callback =
(err
@@ -393,63 +393,8 @@
=%3E %7B
-%0A const callback = req.callback // main callback
%0A%0A
@@ -434,25 +434,16 @@
reject(
-callback(
err, res
@@ -439,25 +439,24 @@
ct(err, res)
-)
%0A %7D%0A%0A
@@ -475,36 +475,20 @@
lve(
-callback(null,
res)
-)
%0A %7D
)%0A%0A
@@ -483,17 +483,16 @@
%0A %7D
-)
%0A%0A
|
01cc5aefc1987cf6f1a6c7cc577e00f73d6b1837
|
make named null properties appear in inspector (fixes e.g. g-animation's published null valued properties)
|
lib/reflection.js
|
lib/reflection.js
|
/*
* Copyright 2013 The Toolkitchen Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function() {
function reflect(element, name) {
return {
obj: element,
name: name,
value: element[name],
meta: element.meta && element.meta.properties[name]
};
}
function reflectProperty(element, name) {
var v = element[name];
if (v !== null
&& v !== undefined
&& typeof v !== 'function'
&& typeof v !== 'object'
//&& element.propertyIsEnumerable(k)
&& !reflectProperty.blacklist[name]) {
var prop = reflect(element, name);
}
return prop;
}
reflectProperty.blacklist = {isToolkitElement: 1};
function reflectProperties(element) {
var props = [];
if (element) {
var found = {};
var p = element.__proto__;
while (p && p !== HTMLElement.prototype/*&& p.isToolkitElement*/) {
var k = Object.keys(p);
k.forEach(function(k) {
if (found[k]) {
return;
}
var prop = reflectProperty(element, k);
if (prop) {
props.push(prop);
found[k] = true;
}
});
p = p.__proto__;
}
//
var more = [];
if (!element.firstElementChild) {
more.push('textContent');
}
more.push('id');
more.forEach(function(k) {
var v = element[k];
if (typeof v !== 'function' && typeof v !== 'object') {
props.push(reflect(element, k));
}
});
}
return props;
}
window.Reflection = {
properties: reflectProperties
};
})();
|
JavaScript
| 0 |
@@ -430,28 +430,39 @@
if (
+(name &&
v
-!
+=
== null
+)
%0A
-&&
+%7C%7C (
v !=
@@ -622,16 +622,17 @@
t%5Bname%5D)
+)
%7B%0A v
|
1b400d9f1ace16499a0b8fa1c115ccaf2c2628aa
|
Make blocks draggable
|
src/block_manager/view/BlockView.js
|
src/block_manager/view/BlockView.js
|
import { on, off } from 'utils/mixins';
module.exports = Backbone.View.extend({
events: {
mousedown: 'startDrag'
},
initialize(o, config = {}) {
this.config = config;
this.endDrag = this.endDrag.bind(this);
this.ppfx = config.pStylePrefix || '';
this.listenTo(this.model, 'destroy remove', this.remove);
},
/**
* Start block dragging
* @private
*/
startDrag(e) {
//Right or middel click
if (e.button !== 0) {
return;
}
if (!this.config.getSorter) {
return;
}
this.config.em.refreshCanvas();
var sorter = this.config.getSorter();
sorter.setDragHelper(this.el, e);
sorter.setDropContent(this.model.get('content'));
sorter.startSort(this.el);
on(document, 'mouseup', this.endDrag);
},
/**
* Drop block
* @private
*/
endDrag(e) {
off(document, 'mouseup', this.endDrag);
const sorter = this.config.getSorter();
// After dropping the block in the canvas the mouseup event is not yet
// triggerd on 'this.doc' and so clicking outside, the sorter, tries to move
// things (throws false positives). As this method just need to drop away
// the block helper I use the trick of 'moved = 0' to void those errors.
sorter.moved = 0;
sorter.endMove();
},
render() {
const el = this.el;
const pfx = this.ppfx;
const className = `${pfx}block`;
el.className += ` ${className} ${pfx}one-bg ${pfx}four-color-h`;
el.innerHTML = `<div class="${className}-label">${this.model.get(
'label'
)}</div>`;
return this;
}
});
|
JavaScript
| 0.000002 |
@@ -112,16 +112,50 @@
artDrag'
+,%0A dragstart: 'handleDragStart'
%0A %7D,%0A%0A
@@ -430,24 +430,56 @@
rtDrag(e) %7B%0A
+ const config = this.config;%0A
//Right
@@ -520,72 +520,51 @@
== 0
-) %7B%0A return;%0A %7D%0A%0A if (!this.config.getSorter) %7B%0A
+ %7C%7C !config.getSorter %7C%7C this.el.draggable)
ret
@@ -576,20 +576,8 @@
-%7D%0A%0A this.
conf
@@ -607,11 +607,13 @@
-var
+const
sor
@@ -610,37 +610,32 @@
const sorter =
-this.
config.getSorter
@@ -802,32 +802,278 @@
endDrag);%0A %7D,%0A%0A
+ handleDragStart(ev) %7B%0A const content = this.model.get('content');%0A // Can't put the content in dataTransfer as it will not be available%0A // on %60dragenter%60 event for security reason%0A this.config.em.set('dragContent', content);%0A %7D,%0A%0A
/**%0A * Drop
@@ -1832,16 +1832,56 @@
/div%3E%60;%0A
+ el.setAttribute('draggable', true);%0A
retu
|
4b5932fdcdb30ebdc5c95d11d25be346f501666a
|
Add custom render for blocks
|
src/block_manager/view/BlockView.js
|
src/block_manager/view/BlockView.js
|
import Backbone from 'backbone';
import { isObject } from 'underscore';
import { on, off, hasDnd } from 'utils/mixins';
module.exports = Backbone.View.extend({
events: {
mousedown: 'startDrag',
dragstart: 'handleDragStart',
drag: 'handleDrag',
dragend: 'handleDragEnd'
},
initialize(o, config = {}) {
const { model } = this;
this.em = config.em;
this.config = config;
this.endDrag = this.endDrag.bind(this);
this.ppfx = config.pStylePrefix || '';
this.listenTo(model, 'destroy remove', this.remove);
this.listenTo(model, 'change', this.render);
},
/**
* Start block dragging
* @private
*/
startDrag(e) {
const config = this.config;
//Right or middel click
if (e.button !== 0 || !config.getSorter || this.el.draggable) return;
config.em.refreshCanvas();
const sorter = config.getSorter();
sorter.setDragHelper(this.el, e);
sorter.setDropContent(this.model.get('content'));
sorter.startSort(this.el);
on(document, 'mouseup', this.endDrag);
},
handleDragStart(ev) {
const { em, model } = this;
const content = model.get('content');
const isObj = isObject(content);
const type = isObj ? 'text/json' : 'text';
const data = isObj ? JSON.stringify(content) : content;
// Note: data are not available on dragenter for security reason,
// but will use dragContent as I need it for the Sorter context
// IE11 supports only 'text' data type
ev.dataTransfer.setData('text', data);
em.set('dragContent', content);
em.trigger('block:drag:start', model, ev);
},
handleDrag(ev) {
this.em.trigger('block:drag', this.model, ev);
},
handleDragEnd() {
const { em, model } = this;
const result = em.get('dragResult');
if (result) {
const oldKey = 'activeOnRender';
const oldActive = result.get && result.get(oldKey);
if (model.get('activate') || oldActive) {
result.trigger('active');
result.set(oldKey, 0);
}
if (model.get('select')) {
em.setSelected(result);
}
if (model.get('resetId')) {
result.onAll(model => model.resetId());
}
}
em.set({
dragResult: null,
dragContent: null
});
em.trigger('block:drag:stop', result, model);
},
/**
* Drop block
* @private
*/
endDrag(e) {
off(document, 'mouseup', this.endDrag);
const sorter = this.config.getSorter();
// After dropping the block in the canvas the mouseup event is not yet
// triggerd on 'this.doc' and so clicking outside, the sorter, tries to move
// things (throws false positives). As this method just need to drop away
// the block helper I use the trick of 'moved = 0' to void those errors.
sorter.moved = 0;
sorter.endMove();
},
render() {
const el = this.el;
const pfx = this.ppfx;
const className = `${pfx}block`;
const label = this.model.get('label');
el.className += ` ${className} ${pfx}one-bg ${pfx}four-color-h`;
el.innerHTML = `<div class="${className}-label">${label}</div>`;
el.title = el.textContent.trim();
hasDnd(this.em) && el.setAttribute('draggable', true);
return this;
}
});
|
JavaScript
| 0 |
@@ -2836,47 +2836,38 @@
nst
-el = this.el;%0A const pfx
+%7B em, el, ppfx, model %7D
= this
-.ppfx
;%0A
@@ -2889,16 +2889,17 @@
me = %60$%7B
+p
pfx%7Dbloc
@@ -2920,21 +2920,16 @@
label =
-this.
model.ge
@@ -2936,24 +2936,64 @@
t('label');%0A
+ const render = model.get('render');%0A
el.class
@@ -3017,16 +3017,17 @@
Name%7D $%7B
+p
pfx%7Done-
@@ -3031,16 +3031,17 @@
ne-bg $%7B
+p
pfx%7Dfour
@@ -3169,21 +3169,16 @@
hasDnd(
-this.
em) && e
@@ -3208,24 +3208,140 @@
le', true);%0A
+ const result = render && render(%7B el, model, className, prefix: ppfx %7D);%0A if (result) el.innerHTML = result;%0A
return t
|
35a3edcfeece85457abc14ecaa1076e6cda9ef04
|
Make readyState message a warning
|
src/Filters/HTML/ScriptsDeferring/rewrite.js
|
src/Filters/HTML/ScriptsDeferring/rewrite.js
|
/* global phast */
var Promise = phast.ES6Promise;
var go = phast.once(loadScripts);
phast.on(document, "DOMContentLoaded").then(function () {
if (phast.stylesLoading) {
phast.onStylesLoaded = go;
setTimeout(go, 4000);
} else {
Promise.resolve().then(go);
}
});
var loadFiltered = false;
window.addEventListener("load", function (e) {
if (!loadFiltered) {
e.stopImmediatePropagation();
}
loadFiltered = true;
});
document.addEventListener("readystatechange", function (e) {
if (document.readyState === "loading") {
e.stopImmediatePropagation();
}
});
var didSetTimeout = false;
var originalSetTimeout = window.setTimeout;
window.setTimeout = function (fn, delay) {
if (!delay || delay < 0) {
didSetTimeout = true;
}
return originalSetTimeout.apply(window, arguments);
};
function loadScripts() {
var scriptsFactory = new phast.ScriptsLoader.Scripts.Factory(
document,
fetchScript
);
var scripts = phast.ScriptsLoader.getScriptsInExecutionOrder(
document,
scriptsFactory
);
if (scripts.length === 0) {
return;
}
setReadyState("loading");
phast.ScriptsLoader.executeScripts(scripts).then(restoreReadyState);
}
function setReadyState(state) {
try {
Object.defineProperty(document, "readyState", {
configurable: true,
get: function () {
return state;
},
});
} catch (e) {
console.error(
"[Phast] Unable to override document.readyState on this browser: ",
e
);
}
}
function restoreReadyState() {
waitForTimeouts()
.then(function () {
setReadyState("interactive");
triggerEvent(document, "readystatechange");
return waitForTimeouts();
})
.then(function () {
triggerEvent(document, "DOMContentLoaded");
return waitForTimeouts();
})
.then(function () {
delete document["readyState"];
triggerEvent(document, "readystatechange");
if (loadFiltered) {
triggerEvent(window, "load");
}
loadFiltered = true;
});
function waitForTimeouts() {
return new Promise(function (resolve) {
(function retry(depth) {
if (didSetTimeout && depth < 10) {
didSetTimeout = false;
originalSetTimeout.call(window, function () {
retry(depth + 1);
});
} else {
requestAnimationFrame(resolve);
}
})(0);
});
}
}
function triggerEvent(on, name) {
var e = document.createEvent("Event");
e.initEvent(name, true, true);
on.dispatchEvent(e);
}
function fetchScript(element) {
return phast.ResourceLoader.instance.get(
phast.ResourceLoader.RequestParams.fromString(
element.getAttribute("data-phast-params")
)
);
}
|
JavaScript
| 0.000011 |
@@ -1409,13 +1409,12 @@
ole.
-error
+warn
(%0A
|
b1c2aca7874239baaa303f8a669bacb3159eab46
|
Add locale check to dob
|
src/common/res/features/days-of-buffering/main.js
|
src/common/res/features/days-of-buffering/main.js
|
// DoB means Days of Buffering
function ynabEnhancedDoB() {
var YNABheader = document.getElementsByClassName("budget-header-flexbox")[0];
var elementForAoM = document.getElementsByClassName("budget-header-days")[0];
var elementForDoB = elementForAoM.cloneNode(true);
elementForDoB.className = elementForDoB.className + " days-of-buffering";
elementForDoB.children[1].textContent = ynabToolKit.l10n && ynabToolKit.l10n.Data.Budget.Header.Metric.DoB || "Days of Buffering";
elementForDoB.children[1].title = "Don't like AoM? Try this out instead!";
var calculation = ynabEnhancedDoBCalculate();
if (!calculation){
elementForDoB.children[0].textContent = "???";
elementForDoB.children[0].title = "Your budget history is less than 15 days. Go on with YNAB a while.";
}
else {
// TODO Add locale check.
var dayText = ynabToolKit.shared.declension('ru', calculation["DoB"], {nom: 'день', gen: 'дня', plu: 'дней'});
// " day" + (calculation["DoB"] == 1 ? "" : "s");
elementForDoB.children[0].textContent = calculation["DoB"] + " " + dayText;
elementForDoB.children[0].title = "Total outflow: " + ynab.YNABSharedLib.currencyFormatter.format(calculation["totalOutflow"]) +
"\nTotal days of budgeting: " + calculation["totalDays"] +
"\nAverage daily outflow: ~" + ynab.YNABSharedLib.currencyFormatter.format(calculation["averageDailyOutflow"]) +
"\nAverage daily transactions: " + calculation["averageDailyTransactions"].toFixed(1);
}
YNABheader.appendChild(elementForDoB);
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
function ynabEnhancedCheckTransactionTypes(transactions) {
// Describe all handled transaction types and check that no other got.
var handeledTransactionTypes = ["subTransaction", "transaction", "scheduledTransaction", "scheduledSubTransaction"];
var uniqueTransactionTypes = Array.from(transactions, function(el) { return el.displayItemType }).filter(onlyUnique);
var allTypesHandeled = uniqueTransactionTypes.every(function(el) { return uniqueTransactionTypes.includes(el) });
if (!allTypesHandeled) {
throw "Found unhandeled transaction type. " + uniqueTransactionTypes;
}
}
function ynabEnhancedDoBCalculate() {
// Get outflow transactions.
var entityManager = ynab.YNABSharedLib.defaultInstance.entityManager;
var transactions = entityManager.getAllTransactions();
var outflowTransactions = transactions.filter(function(el) { return !el.isTombstone
&& el.transferAccountId == null
&& el.amount < 0
&& el.getAccount().onBudget });
// Filter outflow transactions by Date for history lookup option.
if (ynabToolKit.options.daysOfBufferingHistoryLookup > 0) {
dateNow = Date.now();
var outflowTransactions = outflowTransactions.filter(function (el) {
return (dateNow - el.getDate().getUTCTime()) / 3600/24/1000/(365/12) < ynabToolKit.options.daysOfBufferingHistoryLookup })
}
// Get outflow transactions period
outflowTransactionsDates = Array.from(outflowTransactions, function (el) { return el.getDate().getUTCTime() });
var firstTransactionDate = Math.min.apply(null, outflowTransactionsDates);
var lastTransactionDate = Math.max.apply(null, outflowTransactionsDates);
var totalDays = (lastTransactionDate - firstTransactionDate)/3600/24/1000;
if (totalDays < 15){
return false;
}
var totalOutflow = Array.from(outflowTransactions, function (i) { return -i.amount; }).reduce(function (a, b) { return a + b; }, 0);
var averageDailyOutflow = totalOutflow / totalDays;
var budgetAccountsTotal = ynab.YNABSharedLib.getBudgetViewModel_SidebarViewModel()._result.getOnBudgetAccountsBalance();
return {
DoB: Math.floor(budgetAccountsTotal/averageDailyOutflow),
totalOutflow: totalOutflow,
totalDays: totalDays,
averageDailyOutflow: averageDailyOutflow,
averageDailyTransactions: outflowTransactions.length/totalDays,
}
}
function ynabEnhancedDoBInit() {
var elementForAoM = document.getElementsByClassName("budget-header-days");
var elementForDoB = document.getElementsByClassName('days-of-buffering');
if (elementForAoM.length == 1 && elementForDoB.length == 0) {
ynabEnhancedDoB();
}
setTimeout(ynabEnhancedDoBInit, 250);
}
setTimeout(ynabEnhancedDoBInit, 250);
|
JavaScript
| 0 |
@@ -836,45 +836,121 @@
-// TODO Add locale check.%0A var
+var dayText = %22day%22 + (calculation%5B%22DoB%22%5D == 1 ? %22%22 : %22s%22);%0A if (ynabToolKit.options.l10n == 1)%7B%0A
day
@@ -1065,57 +1065,9 @@
-// %22 day%22 + (calculation%5B%22DoB%22%5D == 1 ? %22%22 : %22s%22);
+%7D
%0A
|
38efa3a2c6aae77fca707d5c7dd8737c6e346c96
|
Update messaging for contracts that cannot be resold
|
src/botPage/bot/TradeEngine/Sell.js
|
src/botPage/bot/TradeEngine/Sell.js
|
import { translate } from '../../../common/i18n';
import { recoverFromError, doUntilDone } from '../tools';
import { contractStatus, notify } from '../broadcast';
import { DURING_PURCHASE } from './state/constants';
let delayIndex = 0;
export default Engine =>
class Sell extends Engine {
isSellAtMarketAvailable() {
return this.contractId && !this.isSold && this.isSellAvailable && !this.isExpired;
}
sellAtMarket() {
// Prevent calling sell twice
if (this.store.getState().scope !== DURING_PURCHASE) {
return Promise.resolve();
}
if (!this.isSellAtMarketAvailable()) {
if (this.hasEntryTick) {
const error = new Error(translate('Sell is not available'));
error.name = 'SellNotAvailable';
throw error;
} else {
return Promise.resolve();
}
}
const onSuccess = ({ sell: { sold_for: soldFor } }) => {
delayIndex = 0;
contractStatus('purchase.sold');
notify('info', `${translate('Sold for')}: ${soldFor}`);
return this.waitForAfter();
};
const action = () => this.api.sellContract(this.contractId, 0);
if (!this.options.timeMachineEnabled) {
return doUntilDone(action).then(onSuccess);
}
return recoverFromError(
action,
(errorCode, makeDelay) => makeDelay().then(() => this.observer.emit('REVERT', 'during')),
['NoOpenPosition', 'InvalidSellContractProposal', 'UnrecognisedRequest'],
delayIndex++
).then(onSuccess);
}
sellExpired() {
if (this.isSellAvailable && this.isExpired) {
doUntilDone(() => this.api.sellExpiredContracts());
}
}
};
|
JavaScript
| 0 |
@@ -771,29 +771,47 @@
te('
-Sell is not available
+Resale of this contract is not offered.
'));
|
5712ea40b5a69104249088df4a371aaad92c1863
|
refactor render method in finalize auction component
|
src/components/FinalizeAuction/FinalizeAuction.js
|
src/components/FinalizeAuction/FinalizeAuction.js
|
// @flow weak
import React, {Component} from 'react';
import moment from 'moment'
import classNames from 'classnames/bind';
import {finalizeAuction} from '../../lib/ensService';
import {fromNow, getDuringReveal} from '../../lib/util';
import {FinalizeAuctionInfo} from './FinalizeAuctionInfo';
import './FinalizeAuction.css';
const FinalizeAuctionForm = (props) => {
const timelineState = classNames(props.duringReveal === 'during' ? 'hidden' : null);
return (
<div>
<h2>{props.searchResult.searchName}.eth</h2>
<div>
<p>Auction Closes On</p>
<div>{props.endsAt}</div>
{ props.duringReveal === 'expired' ? (
<div>Finalization</div>
) : (
<div>{fromNow(props.endsAt)}</div>
)
}
</div>
<div className={timelineState}>
<form onSubmit={props.handleFormSubmit}>
<div>
<label>
Email:
<input
name="email"
type="email"
placeholder="[email protected]"
value={props.email}
onChange={props.handleChange}
/>
</label>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</div>
</div>
);
}
export class FinalizeAuction extends Component {
constructor(props) {
super(props)
this.state = {
endsAt: '',
duringReveal: '',
email: '',
finalFormSent: ''
}
this.setFinalFormSent = this.setFinalFormSent.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
componentDidMount() {
// TODO
// request api to get startsAt and endsAt
const endsAt = '';
this.setState({endsAt});
const duringReveal = getDuringReveal(null, endsAt);
this.setState({duringReveal});
}
setFinalFormSent(state) {
this.setState({finalFormSent: state});
}
handleChange(event) {
this.setState({email: event.target.value});
}
// only success scenario and no async
handleFormSubmit(event) {
event.preventDefault();
const email = this.state.email;
const privateKey = this.props.privateKey;
finalizeAuction(email, privateKey);
this.setFinalFormSent('sent');
}
finalAuctionPage(){
return this.state.finalFormSent === 'sent' ? (
<FinalizeAuctionInfo
searchName={this.props.searchResult.searchName}
switchPage={this.props.switchPage}
/>
) : (
<FinalizeAuctionForm
{...this.props}
endsAt={this.state.endsAt}
setFinalFormSent={this.setFinalFormSent}
handleChange={this.handleChange}
handleFormSubmit={this.handleFormSubmit}
/>
)
}
render() {
return this.finalAuctionPage();
}
}
|
JavaScript
| 0.000001 |
@@ -2358,80 +2358,37 @@
inal
+ize
Auction
-Page()%7B%0A return this.state.finalFormSent === 'sent' ?
+Info = () =%3E
(%0A
-
-
%3CFin
@@ -2404,18 +2404,16 @@
ionInfo%0A
-
se
@@ -2464,18 +2464,16 @@
%7D%0A
-
switchPa
@@ -2507,25 +2507,49 @@
-
-
/%3E%0A
- ) : (%0A
+);%0A%0A finalizeAuctionForm = () =%3E (%0A
@@ -2575,18 +2575,16 @@
m%0A
-
%7B...this
@@ -2591,18 +2591,16 @@
.props%7D%0A
-
en
@@ -2630,18 +2630,16 @@
%7D%0A
-
setFinal
@@ -2671,18 +2671,16 @@
rmSent%7D%0A
-
ha
@@ -2712,26 +2712,24 @@
ange%7D%0A
-
handleFormSu
@@ -2765,22 +2765,14 @@
-
-
/%3E%0A
-
)
-%0A %7D
%0A%0A
@@ -2781,23 +2781,85 @@
nder
-() %7B%0A return
+ = () =%3E this.state.finalFormSent === 'sent' ?%0A this.finalizeAuctionInfo() :
thi
@@ -2869,25 +2869,24 @@
inal
+ize
Auction
-Page();%0A %7D
+Form();
%0A%7D%0A
|
e5374eca0b7f8eb61de6fc0ce27085a6be01c519
|
Allow to set link target (_self to change current window's location)
|
assets/buttons.js
|
assets/buttons.js
|
require(['gitbook'], function(gitbook) {
gitbook.events.bind('start', function(e, config) {
var opts = config.toolbar;
if (!opts || !opts.buttons) return;
var buttons = opts.buttons.slice(0);
buttons.reverse();
buttons.forEach(function(button) {
gitbook.toolbar.createButton({
icon: button.icon || "fa fa-external-link",
label: button.label || "Link",
position: 'right',
onClick: function(e) {
e.preventDefault();
var mapping = {
"{{title}}": encodeURIComponent(document.title),
"{{url}}": encodeURIComponent(location.href)
};
var re = RegExp(Object.keys(mapping).join("|"), "g");
window.open(button.url.replace(re, function(matched) {
return mapping[matched];
}));
}
});
});
});
});
|
JavaScript
| 0 |
@@ -874,20 +874,18 @@
-window.open(
+var url =
butt
@@ -994,18 +994,236 @@
%7D)
-)
;
+%0A if (button.target == %22_self%22) %7B%0A window.location = url;%0A %7D else %7B%0A window.open(url, button.target %7C%7C %22_blank%22);%0A %7D
%0A
|
f65229875c39b09eab54526b11738c8cc6097247
|
Update PropTypes of ReadModeModal component
|
src/components/RecipeModal/ReadModeModal/index.js
|
src/components/RecipeModal/ReadModeModal/index.js
|
import React, { PropTypes } from 'react';
import { Modal } from 'react-bootstrap';
const ReadModeModal = props => (
<div>
<Modal.Header>
<Modal.Title>{props.recipe.name}</Modal.Title>
</Modal.Header>
<Modal.Body>
<div id='description'>
{props.recipe.description}
</div>
<ul>
{
props.recipe.ingredients.split(',').map((ingredient,index) => (
<li key={index}>{ingredient}</li>)
)
}
</ul>
</Modal.Body>
<Modal.Footer>
<button onClick={() => props.switchModal(props.recipeId,'update')}>
Edit
</button>
<button onClick={() => props.switchModal(props.recipeId,'delete')}>
Delete
</button>
<button onClick={props.onHide}>Close</button>
</Modal.Footer>
</div>
);
ReadModeModal.PropTypes = {
recipeId: PropTypes.number.isRequired,
recipe: PropTypes.object.isRequired,
onHide: PropTypes.func.isRequired,
switchModal: PropTypes.func.isRequired
}
export default ReadModeModal;
|
JavaScript
| 0 |
@@ -904,25 +904,150 @@
pes.
-object.isRequired
+shape(%7B%0A name: PropTypes.string.isRequired,%0A description: PropTypes.string.isRequired,%0A ingredients: PropTypes.string.isRequired%0A %7D)
,%0A
|
b82800fc66b5744a962217b7a0d529dd1c9b2dee
|
Add title and permanent flag to token model
|
src/models/Token.js
|
src/models/Token.js
|
'use strict'
const mongoose = require('mongoose')
const uuid = require('uuid').v4
const schema = new mongoose.Schema({
id: {
type: String,
required: true,
unique: true,
default: uuid
},
created: {
type: Date,
required: true,
default: Date.now
},
updated: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('Token', schema)
|
JavaScript
| 0 |
@@ -191,16 +191,97 @@
uid%0A%09%7D,%0A
+%09title: %7B%0A%09%09type: String%0A%09%7D,%0A%09permanent: %7B%0A%09%09type: Boolean,%0A%09%09default: false%0A%09%7D,%0A
%09created
|
c74c8d8a7ceacc8f81fc05a740c84566c0949231
|
add a couple urls
|
assets/js/beat.js
|
assets/js/beat.js
|
//Authors
//Nancy Wong <[email protected]>
//Janita Chalam <[email protected]>
//Shloka Kini <[email protected]>
var songs_yt_links = ["https://www.youtube.com/embed/jSXiNdTbTA4",
"https://www.youtube.com/embed/uYsq7fbRbvk",
"https://www.youtube.com/embed/2uVHNib1uzE",
"https://www.youtube.com/embed/KNmpIA_bLcE",
"https://www.youtube.com/embed/LlvUepMa31o",
"https://www.youtube.com/embed/sfTa_NLiXRU",
"https://www.youtube.com/embed/wZcNacuLSGQ",
"https://www.youtube.com/embed/2eq6l9P8Wf0",
"https://www.youtube.com/embed/nfQJRtf0kr4",
"https://www.youtube.com/embed/EZfDUdGWRhQ"];
var talks_poems_links = ["https://www.youtube.com/embed/LkK2fwZfVjA",
"https://www.youtube.com/embed/cWPx9UyEdYw",
"https://www.youtube.com/embed/B3wsSdPzAuQ",
"https://www.youtube.com/embed/H_8y0WLm78U",
"https://www.youtube.com/embed/hg3umXU_qWc",
"https://www.youtube.com/embed/6X9nRnKshCM",
"https://www.youtube.com/embed/0kKh1es5vBQ",
"https://www.youtube.com/embed/Ks-_Mh1QhMc",
"https://www.youtube.com/embed/V-bjOJzB7LY",
"https://www.youtube.com/embed/LBSUTPftN9E"];
console.log(songs_yt_links);
console.log(talks_poems_links);
function generateSong(){
var index = getRandomInt(0,10);
var index2 = getRandomInt(0,10);
var songURL = songs_yt_links[index];
var poemURL = talks_poems_links[index2];
var songiFrame = $('.song_iframe');
var poemiFrame = $('.poem_iframe');
$(".song_iframe").attr('src', songURL+'?autoplay=1');
$(".poem_iframe").attr('src', poemURL+'?autoplay=1');
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
|
JavaScript
| 0.00001 |
@@ -606,16 +606,110 @@
UdGWRhQ%22
+,%0A%09%09%22https://www.youtube.com/embed/S-Xm7s9eGxU%22,%0A%09%09%22https://www.youtube.com/embed/YP_fUo9a_mg%22
%5D;%0A%0A%0Avar
@@ -1307,34 +1307,53 @@
getRandomInt(0,
-10
+songs_yt_links.length
);%0A%09%09%09var index2
@@ -1374,10 +1374,32 @@
t(0,
-10
+talks_poems_links.length
);%0A%09
|
015fe0b3d260eb9916e55775f7a4073c31621b77
|
Check to see if the methods exist before unwrapping them.
|
src/main/webapp/resources/js/dev/directives/dropzone.js
|
src/main/webapp/resources/js/dev/directives/dropzone.js
|
import Dropzone from 'dropzone';
// Prevent Dropzone to auto-magically finding itself in before it is needed.
Dropzone.autoDiscover = false;
/**
* Link function for the dropzone directive.
* @param {object} scope - AngularJS dom scope
* @param {array} element - element directive is attached to
*/
const link = (scope, element) => {
// Unwraps the function and is needed to passed parameters later;
scope.onSuccess = scope.onSuccess();
scope.onComplete = scope.onComplete();
scope.onError = scope.onError();
// Initialize the dropzone.
const dz = new Dropzone(element[0], {
url: scope.url
});
// Update event handlers
dz.on('success', scope.onSuccess);
dz.on('complete', scope.onComplete);
dz.on('error', scope.onError);
};
/**
* Attributes expected on the dropzone tag
* @type {{url: string, onSuccess: function, onComplete: function, onError: function}}
*/
const scope = {
url: "@",
onSuccess: "&",
onComplete: "&",
onError: "&"
};
/**
* Angular directive for Dropzone.js allowing a drag and drop interface for uploading
* files to the server.
* Example:
* <dropzone th:url="@{url}"
* on-success="successCallback"
* on-complete="completionCallback" />
* @return {object} {{restrict: string, scope: {url: string}, link: (function(*, *, *))}}
*/
const dropzone = () => {
return {
scope,
link,
restrict: "E",
replace: true,
template: `<form class="dropzone"></form>`
};
};
export default dropzone;
|
JavaScript
| 0 |
@@ -336,192 +336,8 @@
%3E %7B%0A
- // Unwraps the function and is needed to passed parameters later;%0A scope.onSuccess = scope.onSuccess();%0A scope.onComplete = scope.onComplete();%0A scope.onError = scope.onError();%0A%0A
//
@@ -362,16 +362,16 @@
opzone.%0A
+
const
@@ -427,16 +427,17 @@
l%0A %7D);%0A
+%0A
// Upd
@@ -461,24 +461,141 @@
s%0A
-dz.on('success',
+// Unwraps the function as it is needed to be passed parameters later;%0A if (typeof scope.onSuccess === %22function%22) %7B%0A const sFn =
sco
@@ -606,19 +606,22 @@
nSuccess
+(
);%0A
+
dz.on(
@@ -625,18 +625,91 @@
on('
-complete',
+success', sFn);%0A %7D%0A if (typeof scope.onComplete === %22function%22) %7B%0A const cFn =
sco
@@ -721,19 +721,22 @@
Complete
+(
);%0A
+
dz.on(
@@ -740,15 +740,89 @@
on('
-error',
+complete', cFn);%0A %7D%0A if (typeof scope.onError === %22function%22) %7B%0A const eFn =
sco
@@ -831,19 +831,49 @@
.onError
+(
);%0A
+ dz.on('error', eFn);%0A %7D%0A
%7D;%0A%0A/**%0A
@@ -1233,18 +1233,20 @@
ropzone
-th
+data
:url=%22@%7B
|
6a2682cabb2537f81a8ec225cf0e1760bf67bdcb
|
Fix typo in PageTimeTracker that prevented timer from being cleared
|
src/desktop/analytics/main_layout.js
|
src/desktop/analytics/main_layout.js
|
//
// Analytics for the main layout. This includes buttons in the header, footer
// or any other actions that occur on each page.
//
import { data as sd } from "sharify"
import { reportLoadTimeToVolley } from "lib/volley"
// Track pageview
const pageType = window.sd.PAGE_TYPE || window.location.pathname.split("/")[1]
var properties = { path: location.pathname }
if (pageType == "artwork") {
properties["acquireable"] = sd.ARTWORK.is_acquireable
properties["availability"] = sd.ARTWORK.availability
properties["price_listed"] = sd.ARTWORK.price && sd.ARTWORK.price.length > 0
}
analytics.page(properties, { integrations: { Marketo: false } })
// Track pageload speed
if (
window.performance &&
window.performance.timing &&
sd.TRACK_PAGELOAD_PATHS
) {
window.addEventListener("load", function() {
if (sd.TRACK_PAGELOAD_PATHS.split("|").includes(pageType)) {
window.setTimeout(function() {
const {
requestStart,
loadEventEnd,
domComplete,
} = window.performance.timing
reportLoadTimeToVolley(
requestStart,
loadEventEnd,
domComplete,
pageType,
"desktop"
)
}, 0)
}
})
}
class PageTimeTracker {
constructor(path, delay, description) {
this.path = path
this.delay = delay
this.description = description
this.timer = null
this.track()
}
setPath(newPath) {
this.path = newPath
}
track() {
this.timer = setTimeout(() => {
window.analytics.track("Time on page", {
category: this.description,
message: this.path,
})
}, this.delay)
}
clear() {
if (this.timer) clearTimeout(this.delay)
}
reset(newPath = null) {
this.clear()
if (newPath) this.setPath(newPath)
this.track()
}
}
window.desktopPageTimeTrackers = [
new PageTimeTracker(sd.CURRENT_PATH, 15000, "15 seconds"),
new PageTimeTracker(sd.CURRENT_PATH, 30000, "30 seconds"),
new PageTimeTracker(sd.CURRENT_PATH, 60000, "1 minute"),
new PageTimeTracker(sd.CURRENT_PATH, 180000, "3 minutes"),
]
// debug tracking calls
if (sd.SHOW_ANALYTICS_CALLS) {
analytics.on("track", function() {
console.info("TRACKED: ", arguments[0], JSON.stringify(arguments[1]))
})
}
if (sd.SHOW_ANALYTICS_CALLS) {
analyticsHooks.on("all", function(name, data) {
console.info("ANALYTICS HOOK: ", name, data)
})
}
|
JavaScript
| 0.000001 |
@@ -1693,29 +1693,29 @@
imeout(this.
-delay
+timer
)%0A %7D%0A%0A res
|
a0c41e2d5767aa325ce4a6e0b23feb43808329d2
|
Fix password resetting
|
src/components/structures/login/ForgotPassword.js
|
src/components/structures/login/ForgotPassword.js
|
/*
Copyright 2015, 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
var React = require('react');
var sdk = require('../../../index');
var Modal = require("../../../Modal");
var MatrixClientPeg = require('../../../MatrixClientPeg');
var PasswordReset = require("../../../PasswordReset");
module.exports = React.createClass({
displayName: 'ForgotPassword',
propTypes: {
defaultHsUrl: React.PropTypes.string,
defaultIsUrl: React.PropTypes.string,
customHsUrl: React.PropTypes.string,
customIsUrl: React.PropTypes.string,
onLoginClick: React.PropTypes.func,
onRegisterClick: React.PropTypes.func,
onComplete: React.PropTypes.func.isRequired
},
getInitialState: function() {
return {
enteredHomeserverUrl: this.props.homeserverUrl,
enteredIdentityServerUrl: this.props.identityServerUrl,
progress: null
};
},
submitPasswordReset: function(hsUrl, identityUrl, email, password) {
this.setState({
progress: "sending_email"
});
this.reset = new PasswordReset(hsUrl, identityUrl);
this.reset.resetPassword(email, password).done(() => {
this.setState({
progress: "sent_email"
});
}, (err) => {
this.showErrorDialog("Failed to send email: " + err.message);
this.setState({
progress: null
});
})
},
onVerify: function(ev) {
ev.preventDefault();
if (!this.reset) {
console.error("onVerify called before submitPasswordReset!");
return;
}
this.reset.checkEmailLinkClicked().done((res) => {
this.setState({ progress: "complete" });
}, (err) => {
this.showErrorDialog(err.message);
})
},
onSubmitForm: function(ev) {
ev.preventDefault();
if (!this.state.email) {
this.showErrorDialog("The email address linked to your account must be entered.");
}
else if (!this.state.password || !this.state.password2) {
this.showErrorDialog("A new password must be entered.");
}
else if (this.state.password !== this.state.password2) {
this.showErrorDialog("New passwords must match each other.");
}
else {
this.submitPasswordReset(
this.state.enteredHomeserverUrl, this.state.enteredIdentityServerUrl,
this.state.email, this.state.password
);
}
},
onInputChanged: function(stateKey, ev) {
this.setState({
[stateKey]: ev.target.value
});
},
onHsUrlChanged: function(newHsUrl) {
this.setState({
enteredHomeserverUrl: newHsUrl
});
},
onIsUrlChanged: function(newIsUrl) {
this.setState({
enteredIdentityServerUrl: newIsUrl
});
},
showErrorDialog: function(body, title) {
var ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
Modal.createDialog(ErrorDialog, {
title: title,
description: body
});
},
render: function() {
var LoginHeader = sdk.getComponent("login.LoginHeader");
var LoginFooter = sdk.getComponent("login.LoginFooter");
var ServerConfig = sdk.getComponent("login.ServerConfig");
var Spinner = sdk.getComponent("elements.Spinner");
var resetPasswordJsx;
if (this.state.progress === "sending_email") {
resetPasswordJsx = <Spinner />
}
else if (this.state.progress === "sent_email") {
resetPasswordJsx = (
<div>
An email has been sent to {this.state.email}. Once you've followed
the link it contains, click below.
<br />
<input className="mx_Login_submit" type="button" onClick={this.onVerify}
value="I have verified my email address" />
</div>
);
}
else if (this.state.progress === "complete") {
resetPasswordJsx = (
<div>
<p>Your password has been reset.</p>
<p>You have been logged out of all devices and will no longer receive push notifications.
To re-enable notifications, re-log in on each device.</p>
<input className="mx_Login_submit" type="button" onClick={this.props.onComplete}
value="Return to login screen" />
</div>
);
}
else {
resetPasswordJsx = (
<div>
<div className="mx_Login_prompt">
To reset your password, enter the email address linked to your account:
</div>
<div>
<form onSubmit={this.onSubmitForm}>
<input className="mx_Login_field" ref="user" type="text"
value={this.state.email}
onChange={this.onInputChanged.bind(this, "email")}
placeholder="Email address" autoFocus />
<br />
<input className="mx_Login_field" ref="pass" type="password"
value={this.state.password}
onChange={this.onInputChanged.bind(this, "password")}
placeholder="New password" />
<br />
<input className="mx_Login_field" ref="pass" type="password"
value={this.state.password2}
onChange={this.onInputChanged.bind(this, "password2")}
placeholder="Confirm your new password" />
<br />
<input className="mx_Login_submit" type="submit" value="Send Reset Email" />
</form>
<ServerConfig ref="serverConfig"
withToggleButton={true}
defaultHsUrl={this.props.defaultHsUrl}
defaultIsUrl={this.props.defaultIsUrl}
customHsUrl={this.props.customHsUrl}
customIsUrl={this.props.customIsUrl}
onHsUrlChanged={this.onHsUrlChanged}
onIsUrlChanged={this.onIsUrlChanged}
delayTimeMs={0}/>
<div className="mx_Login_error">
</div>
<a className="mx_Login_create" onClick={this.props.onLoginClick} href="#">
Return to login
</a>
<a className="mx_Login_create" onClick={this.props.onRegisterClick} href="#">
Create a new account
</a>
<LoginFooter />
</div>
</div>
);
}
return (
<div className="mx_Login">
<div className="mx_Login_box">
<LoginHeader />
{resetPasswordJsx}
</div>
</div>
);
}
});
|
JavaScript
| 0.000007 |
@@ -1321,18 +1321,43 @@
ops.
-homeserver
+customHsUrl %7C%7C this.props.defaultHs
Url,
@@ -1410,22 +1410,43 @@
ops.
-identityServer
+customIsUrl %7C%7C this.props.defaultIs
Url,
|
b139c8d01c6d7f8196f085cb69e95e6de196e70d
|
Generate unique IDs for SettingsCheckbox
|
src/components/views/elements/SettingsCheckbox.js
|
src/components/views/elements/SettingsCheckbox.js
|
/*
Copyright 2017 Travis Ralston
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import SettingsStore from "../../../settings/SettingsStore";
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
displayName: 'SettingsCheckbox',
propTypes: {
name: React.PropTypes.string.isRequired,
level: React.PropTypes.string.isRequired,
roomId: React.PropTypes.string, // for per-room settings
label: React.PropTypes.string, // untranslated
onChange: React.PropTypes.func,
// If group is supplied, then this will create a radio button instead.
group: React.PropTypes.string,
value: React.PropTypes.any, // the value for the radio button
},
onChange: function(e) {
if (this.props.group && !e.target.checked) return;
const newState = this.props.group ? this.props.value : e.target.checked;
SettingsStore.setValue(this.props.name, this.props.roomId, this.props.level, newState);
if (this.props.onChange) this.props.onChange(newState);
},
render: function() {
let val = SettingsStore.getValueAt(this.props.level, this.props.name, this.props.roomId);
let label = this.props.label;
if (!label) label = SettingsStore.getDisplayName(this.props.name, this.props.level);
else label = _t(label);
let id = this.props.name;
let checkbox = (
<input id={this.props.name}
type="checkbox"
defaultChecked={val}
onChange={this.onChange}
/>
);
if (this.props.group) {
id = this.props.group + '_' + this.props.name;
checkbox = (
<input id={id}
type="radio"
name={this.props.group}
value={this.props.value}
checked={val === this.props.value}
onChange={this.onChange}
/>
);
}
return (
<div className="mx_SettingCheckbox">
{ checkbox }
<label htmlFor={id}>
{ label }
</label>
</div>
);
},
});
|
JavaScript
| 0.999999 |
@@ -1875,32 +1875,175 @@
-let id = this.props.name
+// We generate a relatively complex ID to avoid conflicts%0A const id = this.props.name + %22_%22 + this.props.group + %22_%22 + this.props.value + %22_%22 + this.props.level
;%0A
@@ -2088,31 +2088,18 @@
put id=%7B
-this.props.name
+id
%7D%0A
@@ -2273,67 +2273,8 @@
) %7B%0A
- id = this.props.group + '_' + this.props.name;%0A
|
c056f4faa65b286ff68dc025dd54789d656544eb
|
Make URL preview checkboxes pretty again
|
src/components/views/elements/SettingsCheckbox.js
|
src/components/views/elements/SettingsCheckbox.js
|
/*
Copyright 2017 Travis Ralston
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from "react";
import SettingsStore from "../../../settings/SettingsStore";
import { _t } from '../../../languageHandler';
module.exports = React.createClass({
displayName: 'SettingsCheckbox',
propTypes: {
name: React.PropTypes.string.isRequired,
level: React.PropTypes.string.isRequired,
roomId: React.PropTypes.string, // for per-room settings
label: React.PropTypes.string, // untranslated
onChange: React.PropTypes.func,
// If group is supplied, then this will create a radio button instead.
group: React.PropTypes.string,
value: React.PropTypes.any, // the value for the radio button
},
onChange: function(e) {
if (this.props.group && !e.target.checked) return;
const newState = this.props.group ? this.props.value : e.target.checked;
SettingsStore.setValue(this.props.name, this.props.roomId, this.props.level, newState);
if (this.props.onChange) this.props.onChange(newState);
},
render: function() {
let val = SettingsStore.getValueAt(this.props.level, this.props.name, this.props.roomId);
let label = this.props.label;
if (!label) label = SettingsStore.getDisplayName(this.props.name, this.props.level);
else label = _t(label);
// We generate a relatively complex ID to avoid conflicts
const id = this.props.name + "_" + this.props.group + "_" + this.props.value + "_" + this.props.level;
let checkbox = (
<input id={id}
type="checkbox"
defaultChecked={val}
onChange={this.onChange}
/>
);
if (this.props.group) {
checkbox = (
<input id={id}
type="radio"
name={this.props.group}
value={this.props.value}
checked={val === this.props.value}
onChange={this.onChange}
/>
);
}
return (
<div className="mx_SettingCheckbox">
{ checkbox }
<label htmlFor={id}>
{ label }
</label>
</div>
);
},
});
|
JavaScript
| 0 |
@@ -2648,42 +2648,13 @@
%3C
-div className=%22mx_SettingCheckbox%22
+label
%3E%0A
@@ -2684,49 +2684,8 @@
x %7D%0A
- %3Clabel htmlFor=%7Bid%7D%3E%0A
@@ -2718,20 +2718,16 @@
-
%3C/label%3E
@@ -2731,27 +2731,8 @@
el%3E%0A
- %3C/div%3E%0A
|
879c3aff60efbf493c0c65a5274fec15048fc42b
|
Send fetch_bundle api release_channel and version
|
normandy/selfrepair/static/js/self_repair_runner.js
|
normandy/selfrepair/static/js/self_repair_runner.js
|
// Trigger heartbeat callbacks when the UITour tells us that Heartbeat
// happened.
Mozilla.UITour.observe((eventName, data) => {
if (eventName.startsWith('Heartbeat')) {
let flowId = data.flowId;
if (flowId in Normandy.heartbeatCallbacks) {
Normandy.heartbeatCallbacks[flowId](data);
}
}
});
let registeredActions = {};
window.registerAction = function(name, ActionClass) {
registeredActions[name] = ActionClass;
};
/**
* Download the implementation of the given action from the server.
*
* @param {Recipe} recipe Recipe object from the server.
* @promise {Function} The action class for the given recipe's action.
* @rejects {Error} Rejects if the action could not be loaded or did not
* register itself.
*/
function loadAction(recipe) {
return new Promise((resolve, reject) => {
let action = recipe.action;
if (!registeredActions[action.name]) {
let script = document.createElement('script');
script.src = action.implementation_url;
script.onload = () => {
if (!registeredActions[action.name]) {
reject(new Error(`Could not find action with name ${action.name}.`));
} else {
resolve(registeredActions[action.name]);
}
};
document.head.appendChild(script);
} else {
resolve(registeredActions[action.name]);
}
});
}
/**
* Get a user_id. If one doesn't exist yet, make one up and store it in local storage.
* @return {String} A stored or generated UUID
*/
function get_user_id() {
let user_id = localStorage.getItem('user_id');
if (user_id === null) {
user_id = uuid.v4();
localStorage.setItem('user_id', user_id);
}
return user_id;
}
/**
* Fetch recipes from the Recipe server.
*
* @promise {Array<Recipe>} List of recipes.
*/
function fetchRecipes() {
let {recipeUrl, locale} = document.documentElement.dataset;
return xhr.post(recipeUrl, {
data: {
locale: locale,
user_id: get_user_id(),
},
headers: {Accept: 'application/json'}
}).then(request => {
return JSON.parse(request.responseText).recipes;
});
}
/**
* Fetch and execute the actions for the given recipe.
*
* @param {Recipe} recipe - Recipe retrieved from the server.
* @promise Resolves once the action has executed.
*/
function runRecipe(recipe) {
return loadAction(recipe).then(function(Action) {
return new Action(Normandy, recipe).execute();
});
}
// Actually fetch and run the recipes.
fetchRecipes().then((recipes) => {
let chain = Promise.resolve();
for (let recipe of recipes) {
chain.then(runRecipe.bind(null, recipe));
}
return chain;
}).catch((err) => {
console.error(err);
});
|
JavaScript
| 0 |
@@ -1470,24 +1470,761 @@
%0A %7D);%0A%7D%0A%0A
+/**%0A * @promise %7BObject%7D The data to send to fetch_bundle to identify this client.%0A */%0Afunction get_fetch_recipe_payload() %7B%0A let data = %7B%0A locale: document.documentElement.dataset.locale,%0A user_id: get_user_id(),%0A release_channel: null,%0A version: null,%0A %7D;%0A%0A return get_uitour_appinfo()%0A .then(uitour_data =%3E %7B%0A data%5B'release_channel'%5D = uitour.defaultUpdateChannel;%0A data%5B'version'%5D = uitour.version;%0A return data;%0A %7D);%0A%7D%0A%0A/**%0A * @promise %7BObject%7D The appinfo from UITour%0A */%0Afunction get_uitour_appinfo() %7B%0A return new Promise((resolve, reject) =%3E %7B%0A Mozilla.UITour.getConfiguration('appinfo', appinfo =%3E %7B%0A resolve(appinfo);%0A %7D);%0A %7D);%0A%7D%0A%0A
/**%0A * Get a
@@ -2710,16 +2710,8 @@
eUrl
-, locale
%7D =
@@ -2748,185 +2748,148 @@
et;%0A
-%0A
-return xhr.post(recipeUrl, %7B%0A data: %7B%0A locale: locale,%0A user_id: get_user_i
+let headers = %7BAccept: 'application/json'%7D;%0A%0A get_fetch_recipe_payloa
d()
-,
%0A
- %7D,%0A headers: %7BAccept: 'application/json'%7D
+.then(data =%3E xhr.post(recipeUrl, %7Bdata, headers%7D))
%0A
-%7D)
.the
@@ -2900,33 +2900,16 @@
quest =%3E
- %7B%0A return
JSON.pa
@@ -2941,23 +2941,16 @@
.recipes
-;%0A %7D
);%0A%7D%0A%0A%0A/
|
40dc43a24a31f16a1e586d734171f5d3963031d9
|
Fix bug on firefox
|
themes/custom/gamers_assembly/components/streams/streams.js
|
themes/custom/gamers_assembly/components/streams/streams.js
|
(function ($) {
'use strict';
$(".stream-video-list .stream-video-list-item").each(function () {
var key = $(this).attr("x-key");
$.ajax({
url: "https://api.twitch.tv/kraken/streams/" + key+"?client_id=3e1bo4w4sfblm61c8baoacmcxab9dq",
}).done(function (data) {
if (data && data.stream) {
$("#stream-video-list-item-" + key).addClass('online');
if (data.stream.viewers) {
$("#stream-video-list-item-" + key + " .stream-video-list-count").text(data.stream.viewers.toString());
}
} else {
$("#stream-video-list-item-" + key).addClass('offline');
}
});
});
$(".stream-video-list .stream-video-list-item").click(function () {
var key = $(this).attr("x-key");
$(".stream-video iframe").attr('src', "https://player.twitch.tv/?channel=" + key);
$(".stream-chat iframe").attr('src', "https://www.twitch.tv/"+key+"/chat?darkpopout");
$(".stream-video-list-item").removeClass('active');
$("#stream-video-list-item-" + key).addClass('active');
});
$(".stream-tab-video-list").click(function () {
$(".stream-video-list, .stream-video-more").show();
$(".stream-chat").hide();
$(".stream-tab-video-list").addClass("active");
$(".stream-tab-chat").removeClass("active");
});
$(".stream-tab-chat").click(function () {
$(".stream-video-list, .stream-video-more").hide();
$(".stream-chat").show();
$(".stream-tab-video-list").removeClass("active");
$(".stream-tab-chat").addClass("active");
});
$('.stream-video-more').click(function() {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$('.stream-video-list').height('200px');
} else {
$(this).addClass('active');
$('.stream-video-list').height('auto');
}
});
})(jQuery);
|
JavaScript
| 0.000021 |
@@ -979,36 +979,43 @@
at iframe%22).
-attr('src',
+html(' %3Ciframe src=
%22https://www
@@ -1029,15 +1029,15 @@
.tv/
-%22
+'
+key+
-%22
+'
/cha
@@ -1049,16 +1049,84 @@
kpopout%22
+ height=%22378%22 width=%22100%25%22 frameborder=%220%22 scrolling=%22no%22%3E%3C/iframe%3E'
);%0D%0A
|
765444e800cd10f7a6347c82f1b272d64875e835
|
Optimize and classify only res.locals.scripts as not found
|
middleware/ensure-found.js
|
middleware/ensure-found.js
|
/*
* Ensures something has been found during the request. Returns 404 if
* res.template is unset, res.locals is empty and statusCode has not been set
* to 204.
*
* Should be placed at the very end of the middleware pipeline,
* after all project specific routes but before the error handler & responder.
*
* @module midwest/middleware/ensure-found
*/
'use strict';
const _ = require('lodash');
module.exports = function ensureFound(req, res, next) {
// it seems most reasonable to check if res.locals is empty before res.statusCode
// because the former is much more common
if (res.template || res.master || !_.isEmpty(res.locals) || res.statusCode === 204) {
next();
} else {
// generates Not Found error if there is no page to render and no truthy
// values in data
const err = new Error(`Not found: ${req.method.toUpperCase()} ${req.path}`);
err.status = 404;
next(err);
}
};
|
JavaScript
| 0.000002 |
@@ -373,37 +373,165 @@
';%0A%0A
-const _ = require('lodash')
+function isEmpty(obj) %7B%0A for (const prop in obj) %7B%0A if (prop !== 'scripts' && obj.hasOwnProperty(prop)) %7B%0A return false;%0A %7D%0A %7D%0A%0A return true
;%0A
+%7D
%0Amod
@@ -752,10 +752,8 @@
%7C%7C !
-_.
isEm
|
26264f6daeadb11d3f21676aeacd483425400c3b
|
Move document filters to top of fields list
|
packages/@sanity/core/src/actions/graphql/v2/generateTypeFilters.js
|
packages/@sanity/core/src/actions/graphql/v2/generateTypeFilters.js
|
const createIdFilters = require('./filters/idFilters')
const createStringFilters = require('./filters/stringFilters')
const createFloatFilters = require('./filters/floatFilters')
const createIntegerFilters = require('./filters/integerFilters')
const createBooleanFilters = require('./filters/booleanFilters')
const createDatetimeFilters = require('./filters/datetimeFilters')
const createDateFilters = require('./filters/dateFilters')
const createDocumentFilters = require('./filters/documentFilters')
const typeAliases = {
Url: 'String',
Text: 'String',
Email: 'String'
}
const filterCreators = {
ID: createIdFilters,
String: createStringFilters,
Float: createFloatFilters,
Integer: createIntegerFilters,
Boolean: createBooleanFilters,
Datetime: createDatetimeFilters,
Date: createDateFilters,
Document: createDocumentFilters
}
function generateTypeFilters(types) {
const builtInTypeKeys = Object.keys(filterCreators)
const builtinTypeValues = Object.values(filterCreators)
const objectTypes = types.filter(
type =>
type.type === 'Object' &&
!['Block', 'Span'].includes(type.name) && // TODO: What do we do with blocks?
!type.interfaces &&
!builtInTypeKeys.includes(type.type)
)
const documentTypes = types.filter(
type => type.type === 'Object' && type.interfaces && type.interfaces.includes('Document')
)
const builtinTypeFilters = createBuiltinTypeFilters(builtinTypeValues)
const objectTypeFilters = createObjectTypeFilters(objectTypes)
const documentTypeFilters = createDocumentTypeFilters(documentTypes)
return builtinTypeFilters.concat(objectTypeFilters).concat(documentTypeFilters)
}
function createBuiltinTypeFilters(builtinTypeValues) {
return builtinTypeValues.map(filterCreator => filterCreator())
}
function createObjectTypeFilters(objectTypes) {
return objectTypes.map(objectType => {
return {
name: `${objectType.name}Filter`,
kind: 'InputObject',
fields: createFieldFilters(objectType)
}
})
}
function createDocumentTypeFilters(documentTypes) {
return documentTypes.map(documentType => {
const fields = createFieldFilters(documentType).concat(getDocumentFilters())
return {
name: `${documentType.name}Filter`,
kind: 'InputObject',
fields
}
})
}
function createFieldFilters(objectType) {
return objectType.fields
.filter(field => field.type !== 'JSON' && field.kind !== 'List')
.map(field => ({
fieldName: field.fieldName,
type: `${typeAliases[field.type] || field.type}Filter`,
isReference: field.isReference
}))
}
function getDocumentFilters() {
return [
{
fieldName: '_',
type: 'DocumentFilter',
description: 'Apply filters on document level'
}
]
}
module.exports = generateTypeFilters
|
JavaScript
| 0 |
@@ -2129,24 +2129,52 @@
st fields =
+getDocumentFilters().concat(
createFieldF
@@ -2197,36 +2197,8 @@
ype)
-.concat(getDocumentFilters()
)%0A
|
085bee98731268235ba290ad34de7a485a0dd66c
|
Integrate new Expression API
|
src/document/nodes/cell/CellMixin.js
|
src/document/nodes/cell/CellMixin.js
|
import { isArray, isNil, map } from 'substance'
import { parse } from 'substance-mini'
import { type } from '../../../value'
export default {
hasValue() {
return !isNil(this.value)
},
hasErrors() {
return this.hasRuntimeErrors() || this.hasSyntaxError()
},
hasRuntimeErrors() {
return this.runtimeErrors
},
getRuntimeErrors() {
return map(this.runtimeErrors)
},
addRuntimeError(key, error) {
if (!this.runtimeErrors) this.runtimeErrors = {}
if (isArray(error)) {
error = error.map(_normalize)
} else {
error = _normalize(error)
}
this.runtimeErrors[key] = error
function _normalize(error) {
const line = error.hasOwnProperty('line') ? error.line : -1
const column = error.hasOwnProperty('column') ? error.column : -1
const message = error.message || error.toString()
return {line, column, message}
}
},
clearRuntimeError(key) {
if (this.runtimeErrors) {
delete this.runtimeErrors[key]
}
},
hasSyntaxError() {
return this._expr && Boolean(this._expr.syntaxError)
},
getSyntaxError() {
return this._expr.syntaxError
},
recompute() {
// we can only propagate if the expression has been parsed
// and the engine has been attached
if (this._expr) {
this._expr.propagate()
}
},
_isInRealDocument() {
// NOTE: for now all cells are active which are part of a 'real' document
return (this.document && !this.document._isTransactionDocument)
},
_setExpression(exprStr) {
// dispose first
if (this._expr) {
this._expr.off(this)
}
// then renew
this._exprStr = exprStr
this._expr = null
if (this._isInRealDocument()) {
this._parse()
this.emit('expression:updated', this)
}
},
_parse() {
const exprStr = this._exprStr
if (exprStr) {
let expr = parse(exprStr)
this._validateExpression(expr)
expr.id = this.id
expr._cell = this
this._expr = expr
expr.on('evaluation:started', this._onEvaluationStarted, this)
expr.on('evaluation:finished', this._onEvaluationFinished, this)
if (this._deriveStateFromExpression) {
this._deriveStateFromExpression()
}
}
},
_onEvaluationStarted() {
// console.log('Started evaluation on', this)
this.pending = true
this.runtimeErrors = null
this.emit('evaluation:started')
},
_onEvaluationFinished() {
// console.log('Finished evaluation on', this)
this.pending = false
const newValue = this._expr.getValue()
// console.log('setting value', newValue)
this._setValue(newValue)
this.emit('evaluation:finished')
},
_setValue(val) {
// console.log('Setting value', this.id, val)
if (this._value !== val) {
// always keep the last computed value
// so that UI can still render it even if
if (!isNil(this._value)) {
this._lastValidValue = this._value
this._lastValidValueType = this.valueType
}
this._value = val
this.valueType = type(val)
}
},
_setSourceCode(val) {
// console.log('Setting sourceCode', this.id, val)
this._sourceCode = val
this.recompute()
},
// TODO: also make sure that call()/run() only have arguments with name (var, or named arg)
_validateExpression(expr) {
// check that if 'call()' or 'run()' is used
// that there is only one of them.
const nodes = expr.nodes
let callCount = 0
for (let i = 0; i < nodes.length; i++) {
const node = expr.nodes[i]
if (node.type === 'call' && (node.name === 'call' || node.name === 'run')) {
callCount++
}
}
if (callCount > 1) {
throw new Error("Only one 'call()' or 'run()' allowed per expression.")
}
}
}
|
JavaScript
| 0.000001 |
@@ -137,16 +137,184 @@
ault %7B%0A%0A
+ isPending() %7B%0A if (this._expr) %7B%0A return this._expr.isPending()%0A %7D%0A %7D,%0A%0A isReady() %7B%0A if (this._expr) %7B%0A return this._expr.isReady()%0A %7D%0A %7D,%0A%0A
hasVal
@@ -2238,24 +2238,95 @@
rted, this)%0A
+ expr.on('evaluation:deferred', this._onEvaluationDeferred, this)%0A
expr.o
@@ -2572,32 +2572,8 @@
is)%0A
- this.pending = true%0A
@@ -2636,24 +2636,227 @@
ted')%0A %7D,%0A%0A
+ _onEvaluationDeferred() %7B%0A // This means that there is an evaluation coming up soon%0A // it could not be done right away because a dependency is pending%0A this.emit('evaluation:awaiting')%0A %7D,%0A%0A
_onEvaluat
@@ -2926,33 +2926,8 @@
is)%0A
- this.pending = false%0A
|
98e63ad42486ff4ba483eec0af8e7a683542ad69
|
Fix message events already declared
|
lib/modules/console/index.js
|
lib/modules/console/index.js
|
let utils = require('../../utils/utils');
const EmbarkJS = require('embarkjs');
const IpfsApi = require('ipfs-api');
const Web3 = require('web3');
class Console {
constructor(_embark, options) {
this.events = options.events;
this.plugins = options.plugins;
this.version = options.version;
this.logger = options.logger;
this.ipc = options.ipc;
this.config = options.config;
if (this.ipc.isServer()) {
this.ipc.on('console:executeCmd', this.executeCmd.bind(this));
}
this.events.setCommandHandler("console:executeCmd", this.executeCmd.bind(this));
this.registerEmbarkJs();
}
processEmbarkCmd (cmd) {
if (cmd === 'help' || cmd === __('help')) {
let helpText = [
__('Welcome to Embark') + ' ' + this.version,
'',
__('possible commands are:'),
'versions - ' + __('display versions in use for libraries and tools like web3 and solc'),
// TODO: only if the blockchain is actually active!
// will need to pass te current embark state here
'ipfs - ' + __('instantiated js-ipfs object configured to the current environment (available if ipfs is enabled)'),
'web3 - ' + __('instantiated web3.js object configured to the current environment'),
'quit - ' + __('to immediatly exit (alias: exit)'),
'',
__('The web3 object and the interfaces for the deployed contracts and their methods are also available')
];
return helpText.join('\n');
} else if (['quit', 'exit', 'sair', 'sortir', __('quit')].indexOf(cmd) >= 0) {
utils.exit();
}
return false;
}
executeCmd(cmd, callback) {
var pluginCmds = this.plugins.getPluginsProperty('console', 'console');
for (let pluginCmd of pluginCmds) {
let pluginResult = pluginCmd.call(this, cmd, {});
if(typeof pluginResult !== 'object'){
if (pluginResult !== false && pluginResult !== 'false' && pluginResult !== undefined) {
this.logger.warn("[DEPRECATED] In future versions of embark, we expect the console command to return an object " +
"having 2 functions: match and process. The documentation with example can be found here: https://embark.status.im/docs/plugin_reference.html#embark-registerConsoleCommand-callback-options");
return callback(null, pluginResult);
}
} else if (pluginResult.match()) {
return pluginResult.process(callback);
}
}
let output = this.processEmbarkCmd(cmd);
if (output) {
return callback(null, output);
}
try {
this.events.request('runcode:eval', cmd, callback);
}
catch (e) {
if (this.ipc.connected && this.ipc.isClient()) {
return this.ipc.request('console:executeCmd', cmd, callback);
}
callback(e);
}
}
registerEmbarkJs() {
this.events.emit('runcode:register', 'IpfsApi', IpfsApi, false);
this.events.emit('runcode:register', 'Web3', Web3, false);
this.events.emit('runcode:register', 'EmbarkJS', EmbarkJS, false);
this.events.on('code-generator-ready', () => {
if (this.ipc.connected) {
return;
}
this.events.request('code-generator:embarkjs:provider-code', (code) => {
const func = () => {};
this.events.request('runcode:eval', code, func, true);
this.events.request('runcode:eval', this.getInitProviderCode(), func, true);
});
});
}
getInitProviderCode() {
const codeTypes = {
'communication': this.config.communicationConfig || {},
'names': this.config.namesystemConfig || {},
'storage': this.config.storageConfig || {}
};
return this.plugins.getPluginsFor('initConsoleCode').reduce((acc, plugin) => {
Object.keys(codeTypes).forEach(codeTypeName => {
(plugin.embarkjs_init_console_code[codeTypeName] || []).forEach(initCode => {
let [block, shouldInit] = initCode;
if (shouldInit.call(plugin, codeTypes[codeTypeName])) {
acc += block;
}
});
});
return acc;
}, '');
}
}
module.exports = Console;
|
JavaScript
| 0.000001 |
@@ -3050,16 +3050,18 @@
vents.on
+ce
('code-g
|
f4357653b1969a35bd2ae4f9068039c645cb9bbd
|
revert integration test fix, is working again (#416)
|
packages/google-cloud-phishingprotection/samples/test/quickstart.js
|
packages/google-cloud-phishingprotection/samples/test/quickstart.js
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 path = require('path');
const {assert} = require('chai');
const {describe, it} = require('mocha');
const cp = require('child_process');
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
const cwd = path.join(__dirname, '..');
const PROJECT_ID = '1046198160504';
const URI = 'http://testsafebrowsing.appspot.com/s/phishing.html';
describe('Quickstart', () => {
it('should run quickstart', async () => {
try {
execSync(`node ./quickstart.js ${URI} ${PROJECT_ID}`, {
cwd,
});
assert('unreachable');
} catch (err) {
assert.match(err.message, /ALREADY_EXISTS/);
}
});
});
|
JavaScript
| 0 |
@@ -1032,19 +1032,22 @@
-try %7B%0A
+const stdout =
exe
@@ -1102,34 +1102,15 @@
%60, %7B
-%0A cwd,%0A
+cwd
%7D);%0A
-
@@ -1119,101 +1119,37 @@
sert
-('unreachable');%0A %7D catch (err) %7B%0A assert.match(err.message, /ALREADY_EXISTS/);%0A %7D
+.include(stdout, 'reported');
%0A %7D
|
8b2a7b1f1752012cddff9fce1db831fd0ba33669
|
Add function to detect TypedArrays
|
lib/sql-string.js
|
lib/sql-string.js
|
var moment = require("moment")
, SqlString = exports;
SqlString.escapeId = function (val, forbidQualified) {
if (forbidQualified) {
return '`' + val.replace(/`/g, '``') + '`';
}
return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`';
};
SqlString.escape = function(val, stringifyObjects, timeZone, dialect, field) {
if (arguments.length === 1 && typeof arguments[0] === "object") {
val = val.val || val.value || null
stringifyObjects = val.stringifyObjects || val.objects || undefined
timeZone = val.timeZone || val.zone || null
dialect = val.dialect || null
field = val.field || null
}
else if (arguments.length < 3 && typeof arguments[1] === "object") {
timeZone = stringifyObjects.timeZone || stringifyObjects.zone || null
dialect = stringifyObjects.dialect || null
field = stringifyObjects.field || null
}
if (val === undefined || val === null) {
return 'NULL';
}
switch (typeof val) {
case 'boolean':
// SQLite doesn't have true/false support. MySQL aliases true/false to 1/0
// for us. Postgres actually has a boolean type with true/false literals,
// but sequelize doesn't use it yet.
return dialect === 'sqlite' ? +!!val : ('' + !!val);
case 'number':
return val+'';
}
if (val instanceof Date) {
val = SqlString.dateToString(val, timeZone || "Z", dialect);
}
if (Buffer.isBuffer(val)) {
return SqlString.bufferToString(val, dialect);
}
if (Array.isArray(val)) {
return SqlString.arrayToList(val, timeZone, dialect, field);
}
if (typeof val === 'object') {
if (stringifyObjects) {
val = val.toString();
} else {
return SqlString.objectToValues(val, timeZone);
}
}
if (dialect === 'postgres' || dialect === 'sqlite') {
// http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
// http://stackoverflow.com/q/603572/130598
val = val.replace(/'/g, "''");
} else {
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch(s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\"+s;
}
});
}
return "'"+val+"'";
};
SqlString.arrayToList = function(array, timeZone, dialect, field) {
if (dialect === 'postgres') {
var ret = 'ARRAY[' + array.map(function(v) {
return SqlString.escape(v, true, timeZone, dialect, field);
}).join(',') + ']';
if (!!field && !!field.type) {
ret += '::' + field.type.replace(/\(\d+\)/g, '');
}
return ret;
} else {
return array.map(function(v) {
if (Array.isArray(v))
return '(' + SqlString.arrayToList(v, timeZone, dialect) + ')';
return SqlString.escape(v, true, timeZone, dialect);
}).join(', ');
}
};
SqlString.format = function(sql, values, timeZone, dialect) {
values = [].concat(values);
return sql.replace(/\?/g, function(match) {
if (!values.length) {
return match;
}
return SqlString.escape(values.shift(), false, timeZone, dialect);
});
};
SqlString.formatNamedParameters = function(sql, values, timeZone, dialect) {
return sql.replace(/\:(\w+)/g, function (value, key) {
if (values.hasOwnProperty(key)) {
return SqlString.escape(values[key], false, timeZone, dialect);
}
else {
throw new Error('Named parameter "' + value + '" has no value in the given object.');
}
});
};
SqlString.dateToString = function(date, timeZone, dialect) {
var dt = new Date(date);
// TODO: Ideally all dialects would work a bit more like this
if (dialect === "postgres") {
return moment(dt).zone('+00:00').format("YYYY-MM-DD HH:mm:ss.SSS Z");
}
if (timeZone !== 'local') {
var tz = convertTimezone(timeZone);
dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000));
if (tz !== false) {
dt.setTime(dt.getTime() + (tz * 60000));
}
}
return moment(dt).format("YYYY-MM-DD HH:mm:ss");
};
SqlString.bufferToString = function(buffer, dialect) {
var hex = '';
try {
hex = buffer.toString('hex');
} catch (err) {
// node v0.4.x does not support hex / throws unknown encoding error
for (var i = 0; i < buffer.length; i++) {
var byte = buffer[i];
hex += zeroPad(byte.toString(16));
}
}
if (dialect === 'postgres') {
// bytea hex format http://www.postgresql.org/docs/current/static/datatype-binary.html
return "E'\\\\x" + hex+ "'";
}
return "X'" + hex+ "'";
};
SqlString.objectToValues = function(object, timeZone) {
var values = [];
for (var key in object) {
var value = object[key];
if(typeof value === 'function') {
continue;
}
values.push(this.escapeId(key) + ' = ' + SqlString.escape(value, true, timeZone));
}
return values.join(', ');
};
function zeroPad(number) {
return (number < 10) ? '0' + number : number;
}
function convertTimezone(tz) {
if (tz == "Z") return 0;
var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/);
if (m) {
return (m[1] == '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60;
}
return false;
}
|
JavaScript
| 0.000001 |
@@ -32,28 +32,522 @@
,
-SqlString = exports;
+isArrayBufferView%0A , SqlString = exports;%0A%0Aif(typeof(ArrayBufferView) === 'function') %7B%0A isArrayBufferView = function(object) %7B return object && (object instanceof ArrayBufferView); %7D;%0A%7D else %7B%0A var arrayBufferViews = %5B%0A Int8Array, Uint8Array, Int16Array, Uint16Array,%0A Int32Array, Uint32Array, Float32Array, Float64Array%0A %5D;%0A isArrayBufferView = function(object) %7B%0A for(var i=0;i%3C8;i++) %7B%0A if(object instanceof arrayBufferViews%5Bi%5D) %7B%0A return true;%0A %7D%0A %7D%0A return false;%0A %7D;%0A%7D%0A
%0A%0ASq
|
30aba6ad711d93f7207ccf3b900cc26dd07c8c12
|
Move status to Record
|
packages/node_modules/@ciscospark/redux-module-users/src/reducer.js
|
packages/node_modules/@ciscospark/redux-module-users/src/reducer.js
|
import {fromJS, Record} from 'immutable';
import {
STORE_USER,
STORE_USERS,
FETCH_USER_REQUEST,
STORE_CURRENT_USER,
FETCH_CURRENT_USER_REQUEST,
PENDING_STATUS
} from './actions';
const User = new Record({
id: undefined,
displayName: '',
nickName: '',
email: '',
orgId: '',
status: {
isFetching: false
}
});
export const initialState = fromJS({
currentUserId: null,
byId: {},
byEmail: {}
});
export default function reducer(state = initialState, action) {
switch (action.type) {
case STORE_USER: {
const {user} = action.payload;
return state
.setIn(['byId', user.id], new User(user))
.setIn(['byEmail', user.email], user.id);
}
case STORE_USERS: {
const users = {};
const emails = {};
action.payload.users.forEach((u) => {
users[u.id] = new User(u);
emails[u.email] = u.id;
});
return state
.mergeIn(['byId'], users)
.mergeIn(['byEmail'], emails);
}
case STORE_CURRENT_USER: {
const {user} = action.payload;
return state.set('currentUserId', user.id)
.setIn(['byId', user.id], new User(user))
.setIn(['byEmail', user.email], user.id);
}
case FETCH_USER_REQUEST: {
const {email, id} = action.payload;
let newState = state;
if (id) {
newState = newState.setIn(['byId', id], new User({status: {isFetching: true}}));
}
else if (email) {
newState = newState.setIn(['byEmail', email], id || PENDING_STATUS);
}
return newState;
}
case FETCH_CURRENT_USER_REQUEST: {
const {id} = action.payload;
return state.set('currentUserId', id)
.setIn(['byId', id], new User({status: {isFetching: true}}));
}
default:
return state;
}
}
|
JavaScript
| 0.000004 |
@@ -186,16 +186,67 @@
ions';%0A%0A
+const Status = new Record(%7B%0A isFetching: false%0A%7D);
%0Aconst U
@@ -356,35 +356,20 @@
us:
-%7B%0A isFetching: false%0A %7D
+new Status()
%0A%7D);
|
de63299abc051e250d31d7414cb6d1e5ccc4fdf2
|
Remove unneeded import
|
client/app/pods/components/main-sidebar/component.js
|
client/app/pods/components/main-sidebar/component.js
|
//
// Copyright 2009-2015 Ilkka Oksanen <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
import Mobx from 'mobx';
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import Component from '@ember/component';
import settingStore from '../../../stores/SettingStore';
import friendStore from '../../../stores/FriendStore';
import { dispatch } from '../../../utils/dispatcher';
const { autorun } = Mobx;
export default Component.extend({
init(...args) {
this._super(...args);
this.disposer = autorun(() => {
this.set('canUseIRC', settingStore.settings.canUseIRC);
this.set('darkTheme', settingStore.settings.theme === 'dark');
this.set('friends', Array.from(friendStore.friends.values()));
});
},
didDestroyElement() {
this.disposer();
},
classNames: ['sidebar', 'flex-grow-column'],
draggedWindow: false,
actions: {
openModal(modal) {
dispatch('OPEN_MODAL', { name: modal });
},
logout() {
dispatch('LOGOUT');
},
logoutAll() {
dispatch('LOGOUT', { allSessions: true });
},
toggleDarkTheme() {
dispatch('TOGGLE_THEME');
}
},
friendsOnline: computed('[email protected]', function() {
return this.friends.filterBy('online', true).length;
})
});
|
JavaScript
| 0.000002 |
@@ -698,56 +698,8 @@
t';%0A
-import %7B alias %7D from '@ember/object/computed';%0A
impo
|
381e2fc39e71a0453baaf49a85114add6971f0d9
|
Update unpackaged/gated/healthCheck/lwc/healthCheck/healthCheck.js
|
unpackaged/gated/healthCheck/lwc/healthCheck/healthCheck.js
|
unpackaged/gated/healthCheck/lwc/healthCheck/healthCheck.js
|
import { LightningElement, track, wire } from 'lwc';
import stgHealthCheckErrorLastRunDate from '@salesforce/label/c.stgHealthCheckErrorLastRunDate';
import getHealthCheckViewModel from '@salesforce/apex/HealthCheckController.getHealthCheckViewModel';
import updateHealthCheckLastRunDate from '@salesforce/apex/HealthCheckController.updateHealthCheckLastRunDate';
export default class HealthCheck extends LightningElement {
@track expanded = true;
@track totalChecks = 0;
@track passedChecks = 0;
@track lastRunDate = '';
@track isDisplayHealthCheckGroup = false;
@track healthCheckDefinitionsToDisplayList = [];
LabelReference = {
stgHealthCheckErrorLastRunDate
}
handleHealthCheckRun(){
updateHealthCheckLastRunDate()
.then(result => {
this.lastRunDate = result;
this.isDisplayHealthCheckGroup = true;
})
.catch(error => {
// console.log('error updating last run date: ', error);
this.lastRunDate = this.LabelReference.stgHealthCheckErrorLastRunDate;
});
}
@wire(getHealthCheckViewModel)
healthCheckViewModel({error, data}){
if (data){
this.lastRunDate = data.lastRunDate;
this.healthCheckDefinitionsToDisplayList = data.healthCheckDefinitionList;
} else if (error){
console.log('error retrieving health check view model: ', error);
}
}
get displayHealthCheck(){
return !(!this.isDisplayHealthCheckGroup || !this.healthCheckDefinitionsToDisplayList);
}
}
|
JavaScript
| 0 |
@@ -1415,16 +1415,18 @@
+//
console.
@@ -1634,8 +1634,9 @@
%7D%0A%0A%7D
+%0A
|
aafd17d8db6d9a8a4248813e3f47d9ad83e771aa
|
fix typo
|
site/kitchen/src/en-US.js
|
site/kitchen/src/en-US.js
|
const appLocaleData = require('react-intl/locale-data/en');
module.exports = {
locale: 'en-US',
data: appLocaleData,
messages: {
'app.site.title': 'Ant Design Mobile',
'app.site.subTitle': 'Mobile Componets By Ant UED',
},
};
|
JavaScript
| 0.000203 |
@@ -212,16 +212,17 @@
Compone
+n
ts By An
|
3467d509f75380c78c5362e2044b12543668a482
|
save old extension handlers so we can put them back if the extensions are hooked again
|
lib/6to5/register.js
|
lib/6to5/register.js
|
require("./polyfill");
var sourceMapSupport = require("source-map-support");
var to5 = require("./index");
var _ = require("lodash");
sourceMapSupport.install({
retrieveSourceMap: function (source) {
var map = maps[source];
if (map) {
return {
url: null,
map: map
};
} else {
return null;
}
}
});
//
var ignoreRegex = /node_modules/;
var exts = [];
var maps = {};
var old = require.extensions[".js"];
var loader = function (m, filename) {
if (ignoreRegex && ignoreRegex.test(filename)) {
return old.apply(this, arguments);
}
var result = to5.transformFileSync(filename, {
sourceMap: true
});
maps[filename] = result.map;
m._compile(result.code, filename);
};
var hookExtensions = function (_exts) {
_.each(exts, function (ext) {
delete require.extensions[ext];
});
exts = _exts;
_.each(exts, function (ext) {
require.extensions[ext] = loader;
});
};
hookExtensions([".es6", ".js"]);
module.exports = function (opts) {
opts = opts || {};
if (_.isRegExp(opts)) opts = { ignoreRegex: opts };
if (opts.ignoreRegex != null) {
ignoreRegex = opts.ignoreRegex;
}
if (opts.extensions) hookExtensions(opts.extensions);
};
|
JavaScript
| 0 |
@@ -435,10 +435,10 @@
=
-%5B%5D
+%7B%7D
;%0Ava
@@ -842,32 +842,37 @@
exts, function (
+old,
ext) %7B%0A delet
@@ -870,15 +870,8 @@
-delete
requ
@@ -889,16 +889,22 @@
ons%5Bext%5D
+ = old
;%0A %7D);%0A
@@ -913,21 +913,18 @@
exts =
-_exts
+%7B%7D
;%0A%0A _.e
@@ -919,32 +919,33 @@
= %7B%7D;%0A%0A _.each(
+_
exts, function (
@@ -947,24 +947,65 @@
ion (ext) %7B%0A
+ exts%5Bext%5D = require.extensions%5Bext%5D;%0A
require.
|
420505ca40f94bd2765d79174cdf5db0cd5ec039
|
remove console.log debug
|
lib/6to5/register.js
|
lib/6to5/register.js
|
"use strict";
require("./polyfill");
var sourceMapSupport = require("source-map-support");
var registerCache = require("./register-cache");
var util = require("./util");
var to5 = require("./index");
var fs = require("fs");
var extend = require("lodash/object/extend");
var each = require("lodash/collection/each");
sourceMapSupport.install({
retrieveSourceMap: function (source) {
var map = maps && maps[source];
if (map) {
return {
url: null,
map: map
};
} else {
return null;
}
}
});
//
registerCache.load();
var cache = registerCache.get();
//
var transformOpts = {};
var ignoreRegex = /node_modules/;
var onlyRegex;
var exts = {};
var maps = {};
var old = require.extensions[".js"];
var mtime = function (filename) {
return +fs.statSync(filename).mtime;
};
var compile = function (filename) {
var result;
if (cache) {
var cached = cache[filename];
if (cached && cached.mtime === mtime(filename)) {
result = cached;
}
}
if (!result) {
result = to5.transformFileSync(filename, extend({
sourceMap: true,
ast: false
}, transformOpts));
}
if (cache) {
result.mtime = mtime(filename);
cache[filename] = result;
}
maps[filename] = result.map;
return result.code;
};
var shouldIgnore = function (filename) {
console.log(filename);
return (ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename));
};
var istanbulLoader = function (m, filename, old) {
// we need to monkey patch fs.readFileSync so we can hook into
// what istanbul gets, it's extremely dirty but it's the only way
var _readFileSync = fs.readFileSync;
fs.readFileSync = function () {
fs.readFileSync = _readFileSync;
return compile(filename);
};
old(m, filename);
};
var normalLoader = function (m, filename) {
m._compile(compile(filename), filename);
};
var registerExtension = function (ext) {
var old = require.extensions[ext];
var loader = normalLoader;
if (process.env.running_under_istanbul) loader = istanbulLoader;
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
old(m, filename);
} else {
loader(m, filename, old);
}
};
};
var hookExtensions = function (_exts) {
each(exts, function (old, ext) {
require.extensions[ext] = old;
});
exts = {};
each(_exts, function (ext) {
exts[ext] = require.extensions[ext];
registerExtension(ext);
});
};
hookExtensions(util.canCompile.EXTENSIONS);
module.exports = function (opts) {
// normalise options
opts = opts || {};
if (opts.only != null) onlyRegex = util.regexify(opts.only);
if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);
if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));
if (opts.cache === false) cache = null;
delete opts.extensions;
delete opts.ignore;
delete opts.cache;
delete opts.only;
extend(transformOpts, opts);
};
|
JavaScript
| 0.000012 |
@@ -1437,33 +1437,8 @@
) %7B%0A
- console.log(filename);%0A
re
|
651a9dd782dd08745a9924078dd1844b9cde234a
|
remove console logs
|
lib/treehugger.js
|
lib/treehugger.js
|
/*
* treehugger
* https://github.com/goliatone/treehugger
*
* Copyright (c) 2015 goliatone
* Licensed under the MIT license.
*/
var extend = require('gextend');
var _inherit = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var assert = require('assert-is');
var DEFAULTS = {
autoinitialize: true,
glue: '_',
markAsLoaded: true,
deleteAfterLoad: false,
namespace: 'NODE',
loadedFlag: 'TREEHUGHER',
getEnvironment: function(){
return process.env;
}
};
function TreeHugger(config){
EventEmitter.call(this);
config = extend({}, this.constructor.DEFAULTS, config);
if(config.autoinitialize ) this.init(config);
}
_inherit(TreeHugger, EventEmitter);
TreeHugger.DEFAULTS = DEFAULTS;
TreeHugger.config = function(config){
TreeHugger.config = config;
return TreeHugger;
};
TreeHugger.write = function(data){
var options = extend({}, TreeHugger.config);
TreeHugger.config = {};
return new TreeHugger(options).write(data);
};
TreeHugger.read = function(data){
var options = extend({}, TreeHugger.config);
TreeHugger.config = {};
return new TreeHugger(options).read(data);
};
TreeHugger.prototype.init = function(config){
if(this.initialized) return;
this.initialized = true;
extend(this, this.constructor.DEFAULTS, config);
this.ENV = this.getEnvironment();
};
TreeHugger.prototype.write = function(data){
assert.isObject(data, 'You need to pass in a data object');
var env = this._loadedFlag(this.namespace);
if(this.ENV[env]) {
console.log(this.ENV)
process.nextTick(function(){
this.emit('write', this.ENV);
}.bind(this));
return this;
}
this.ENV[env] = Date.now();
var name, namespace = this.namespace;
Object.keys(data).map(function(key){
name = this._environmentKey(key, namespace);
this.ENV[name] = data[key];
}, this);
/*
* Let's make the process async, so we
* can register listeners on constructor
*/
process.nextTick(function(){
this.emit('write', this.ENV);
}.bind(this));
return this;
};
TreeHugger.prototype.read = function(output){
output = output || {};
var env = {}, name;
var rx = new RegExp('^' + this.namespace + this.glue);
Object.keys(this.ENV).map(function(key){
console.log(rx.test(key))
if(!rx.test(key)) return;
name = this._variableName(key, this.namespace);
output[name] = this.ENV[key];
}, this);
//TODO: Should we enable filtering or post process?
process.nextTick(function(){
this.emit('read', output);
}.bind(this));
return this;
};
TreeHugger.prototype._loadedFlag = function(appname){
var namespace = this.namespace + this.glue + this.loadedFlag;
return this._environmentKey(appname, namespace);
};
TreeHugger.prototype._environmentKey = function(str, namespace){
str = str || '', namespace = namespace || this.namespace;
str = namespace + this.glue + str;
str = str.replace(/\W+/g, this.glue)
.replace(/([a-z\d])([A-Z])/g, '$1' + this.glue + '$2');
str = str.toUpperCase();
return str;
};
TreeHugger.prototype._variableName = function(str, namespace){
function _capitalize(s){
return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
}
function _downcase(s){
return s.charAt(0).toLowerCase() + s.slice(1);
}
str = str.replace(new RegExp('^' + namespace + this.glue), '');
return _downcase(str.split(this.glue).reduce(function(out, key){
return out + _capitalize(key);
}, ''));
};
TreeHugger.prototype.logger = console;
module.exports = TreeHugger;
|
JavaScript
| 0.000001 |
@@ -1577,38 +1577,8 @@
) %7B%0A
- console.log(this.ENV)%0A
@@ -2344,42 +2344,8 @@
y)%7B%0A
- console.log(rx.test(key))%0A
|
d967a0cb94cbd4a33931d475a6a5147fc0efee56
|
put back the workaround for Safari
|
lib/AttrAssembler.js
|
lib/AttrAssembler.js
|
import { NodeAssembler } from './NodeAssembler'
const { prototype : { map } } = Array
const { Attr, Node : { ELEMENT_NODE }, document } = window
const EMPTY_STRING = ''
const NAMESPACE_SEPARATOR = ':'
const VALUE_PROPERTY_NAME = 'value'
/**
* @see https://www.w3.org/TR/dom/#interface-attr
*/
export class AttrAssembler extends NodeAssembler {
/**
* Remove the attribute from it's owner element
*/
remove() {
const ownerElement = this.node.ownerElement
if(ownerElement) {
ownerElement.removeAttribute(this.name)
}
}
/**
* @return {string}
*/
get name() {
return this.node.name
}
/**
* @param {ElementAssembler|Element|*} ownerElement
*/
set ownerElement(ownerElement) {
const node = this.node
if(ownerElement) {
if(ownerElement instanceof NodeAssembler.ElementAssembler) {
ownerElement.setAttr(node)
}
else if(ownerElement.nodeType === ELEMENT_NODE) {
ownerElement.attributes.setNamedItem(node)
}
else {
const element = new this.constructor.elementAssembler(ownerElement)
element.setAttr(node)
}
}
}
/**
* @returns {ElementAssembler|null}
*/
get ownerElement() {
return this.getInstanceOf(this.node.ownerElement)
}
/**
* @param {ParentNodeAssembler|*|null} parentNode
*/
set parentNode(parentNode) {
const ownerElement = this.ownerElement
if(ownerElement) {
ownerElement.parentNode = parentNode
}
else throw Error(`Failed to set 'parentNode' on '${ this.constructor.name }': the 'ownerElement' is null.`)
}
/**
* @returns {ParentNodeAssembler|*|null}
*/
get parentNode() {
const ownerElement = this.ownerElement
return ownerElement && ownerElement.parentNode
}
/**
* @param {string|*} value
*/
set value(value) {
if(this.constructor.removeOnValue(value)) {
this.remove()
}
else this.node.value = value
}
/**
* @returns {string|*}
*/
get value() {
return this.node.value
}
/**
* @returns {Attr|*}
* @override
*/
static create() {
return document.createAttributeNS(this.namespace, this.qualifiedName)
}
/**
* @param {ElementAssembler|Element|*} element
* @returns {AttrAssembler|*}
*/
static getAttrOf(element) {
const node = this.getNodeOf(element)
const attr = node.attributes.getNamedItem(this.qualifiedName)
return attr && this.getInstanceOf(attr)
}
/**
* @param {string|Element|Document|DocumentFragment} [selectorOrContext=this.selector]
* @param {Element|Document|DocumentFragment} [context=window.document]
* @returns {AttrAssembler[]} array of initialized instances
*/
static init(selectorOrContext = this.selector, context = document) {
const localName = this.localName
if(selectorOrContext.nodeType) {
context = selectorOrContext
selectorOrContext = this.selector
}
return map.call(context.querySelectorAll(selectorOrContext), ownerElement => {
const node = ownerElement.attributes[localName]
return node?
new this({ node }) :
new this({ ownerElement })
})
}
/**
* @param {*} value
* @returns {boolean}
*/
static removeOnValue(value) {
return value === null
}
/**
* @returns {string}
* @override
*/
static get defaultPropertyName() {
return VALUE_PROPERTY_NAME
}
/**
* @returns {null|*}
*/
static get defaultValue() {
return null
}
/**
* @returns {interface} Attr
* @override
*/
static get interface() {
return Attr
}
/**
* @returns {string}
*/
static get localName() {
return this === AttrAssembler?
EMPTY_STRING :
this.name.toLowerCase()
}
/**
* @returns {string}
*/
static get namespace() {
return EMPTY_STRING
}
/**
* @returns {string}
*/
static get prefix() {
return EMPTY_STRING
}
/**
* @returns {string}
*/
static get qualifiedName() {
const { prefix, localName } = this
return prefix?
prefix + NAMESPACE_SEPARATOR + localName :
localName
}
/**
* @returns {string}
*/
static get selector() {
return `[${ this.localName }]`
}
}
NodeAssembler.AttrAssembler = AttrAssembler
|
JavaScript
| 0 |
@@ -4779,8 +4779,589 @@
sembler%0A
+%0A/*%0A * !!! Workaround !!!%0A * The garbage collector in Safari removes instances of AttrAssembler%0A * that are not referenced from the static memory structure.%0A */%0Aconst %7B userAgent %7D = window.navigator%0Aif(/Safari/.test(userAgent) && !/Chrome/.test(userAgent)) %7B%0A AttrAssembler.__instances__ = %5B%5D%0A Object.defineProperty(AttrAssembler, 'setTargetOf', %7B%0A configurable : true,%0A writable : true,%0A value : function(instance, target) %7B%0A NodeAssembler.setTargetOf(target, instance)%0A AttrAssembler.__instances__.push(this)%0A %7D%0A %7D)%0A%7D%0A
|
8c2bac40171bbd1963471061fe7b6dcd94a32a7b
|
Handle startDate for new reviewer
|
src/commands/setup.js
|
src/commands/setup.js
|
// npm modules
import chalk from 'chalk';
import inquirer from 'inquirer';
import moment from 'moment';
import ora from 'ora';
import PushBullet from 'pushbullet';
import Table from 'cli-table2';
// our modules
import {api, config} from '../utils';
async function getUserInfoFromApi() {
const startDateSpinner = ora('Getting startDate...').start();
const completedReviews = await api({
task: 'completed',
body: {
start_date: moment('2014-01-01').format('YYYY-MM-DDTHH:mm:ss.SSS'),
end_date: moment().format('YYYY-MM-DDTHH:mm:ss.SSS'),
},
});
const startDate = completedReviews.body
.map(review => moment(review.assigned_at)) // returns date of review
.map(date => date.valueOf()) // returns date in Unix Time (milliseconds from 1970)
.reduce((acc, val) => { // returns the smallest number
if (acc < val) {
return acc;
}
return val;
});
config.startDate = moment(startDate).format('YYYY-MM-DD');
startDateSpinner.succeed(`Startdate is ${config.startDate}`);
const certSpinner = ora('Getting certifications...').start();
const certifications = await api({
task: 'certifications',
});
config.certs = certifications.body
.filter(cert => cert.status === 'certified')
.reduce((acc, cert) => {
/* eslint-disable no-param-reassign */
acc[cert.project.id] = {
name: cert.project.name,
price: cert.project.price,
};
return acc;
}, {});
// Create a new table for certifications
const certsDetails = new Table({
head: [
{hAlign: 'center', content: 'id'},
{hAlign: 'left', content: 'project name'},
{hAlign: 'center', content: 'price'}],
colWidths: [5, 40, 7],
});
Object.keys(config.certs)
.sort((a, b) => a - b)
.forEach((id) => {
const {name, price} = config.certs[id];
certsDetails.push([
{hAlign: 'center', content: id},
{hAlign: 'left', content: name},
{hAlign: 'center', content: price},
]);
});
certSpinner.succeed(`Your certifications:\n${certsDetails.toString()}`);
const configSpinner = ora('Saving configs...').start();
config.save();
configSpinner.succeed('Configs successfully save.');
process.exit(0);
}
const pushbulletTokenInput = () => {
inquirer.prompt([{
type: 'input',
name: 'pushbulletToken',
message: 'Input your PushBullet access token:',
validate(pushbulletToken) {
const pusher = new PushBullet(pushbulletToken);
return new Promise((resolve, reject) => {
pusher.devices((err) => {
if (err) reject(err);
resolve(true);
});
});
},
}]).then((pushbulletToken) => {
Object.assign(config, pushbulletToken);
getUserInfoFromApi();
});
};
const pushbulletChoice = () => {
inquirer.prompt([{
type: 'confirm',
name: 'pushbullet',
message: 'Do you wish to use PushBullet?',
default: false,
}]).then((confirm) => {
if (confirm.pushbullet) {
pushbulletTokenInput();
} else {
getUserInfoFromApi();
}
});
};
const languages = () => {
inquirer.prompt([{
type: 'checkbox',
message: 'Select Language(s) that you are certified for:\n',
name: 'languages',
choices: ['en-us', 'pt-br', 'zh-cn'],
validate: (langs) => {
if (langs.length < 1) {
return 'You must choose at least one language.';
}
return true;
},
}]).then((langs) => {
Object.assign(config, langs);
pushbulletChoice();
});
};
const tokenInput = () => {
inquirer.prompt([{
type: 'input',
name: 'token',
message: 'Input your token:',
validate(token) {
config.token = token;
return api({task: 'count'})
.then((res) => {
/* eslint-disable eqeqeq */
if (res.statusCode == '200') {
return true;
}
return 'The token was invalid, try again.';
})
.catch((err) => {
console.log('There was an error validating the token.');
console.log('Make sure you entered the token correctly and that you are not having connectivity issues.');
console.log(`
${chalk.red('The API request returned with the following error:')}\n\n${JSON.stringify(err, null, 4)}`);
process.exit(1);
});
},
}]).then((token) => {
Object.assign(config, token);
config.tokenAge = moment().add(28, 'd');
languages();
});
};
export const setupCmd = () => {
tokenInput();
};
|
JavaScript
| 0.000002 |
@@ -568,21 +568,60 @@
%7D);%0A
-const
+let startDate;%0A if (completedReviews) %7B%0A
startDa
@@ -643,24 +643,26 @@
eviews.body%0A
+
.map(rev
@@ -722,24 +722,26 @@
review%0A
+
+
.map(date =%3E
@@ -811,24 +811,26 @@
m 1970)%0A
+
.reduce((acc
@@ -874,24 +874,26 @@
umber%0A
+
if (acc %3C va
@@ -901,24 +901,26 @@
) %7B%0A
+
+
return acc;%0A
@@ -921,32 +921,34 @@
acc;%0A
+
%7D%0A
return val;%0A
@@ -931,24 +931,26 @@
%7D%0A
+
+
return val;%0A
@@ -949,24 +949,26 @@
rn val;%0A
+
%7D);%0A
config
@@ -955,24 +955,69 @@
;%0A %7D);%0A
+ %7D else %7B%0A startDate = moment.utc();%0A %7D%0A
config.sta
|
a59d7b55484ec52b30fe149ec9c064df09b3bb2f
|
fix error with geth genesis file parser
|
lib/util/parse.js
|
lib/util/parse.js
|
'use strict'
const Account = require('ethereumjs-account')
const Block = require('ethereumjs-block')
const Trie = require('merkle-patricia-tree/secure')
const BN = require('ethereumjs-util').BN
const url = require('url')
const path = require('path')
function parseBootnodes (string) {
if (!string) {
return
}
try {
return string.split(',').map(s => {
const match = s.match(/^(\d+\.\d+\.\d+\.\d+):([0-9]+)$/)
if (match) {
return { ip: match[1], port: match[2] }
}
const { auth: id, hostname: ip, port } = url.parse(s)
return { id, ip, port }
})
} catch (e) {
throw new Error(`Invalid bootnode URLs: ${e.message}`)
}
}
function parseTransports (transports) {
return transports.map(t => {
const options = {}
const [ name, ...pairs ] = t.split(':')
if (pairs) {
pairs.join(':').split(',').forEach(p => {
const [ key, value ] = p.split('=')
options[key] = value
})
}
return { name, options }
})
}
async function parseGethState (alloc) {
const trie = new Trie()
const promises = []
for (let [key, value] of Object.entries(alloc)) {
const address = Buffer.from(key, 'hex')
const account = new Account()
account.balance = new BN(value.balance.slice(2), 16)
promises.push(new Promise((resolve, reject) => {
trie.put(address, account.serialize(), (err) => {
if (err) return reject(err)
resolve()
})
}))
}
await Promise.all(promises)
return trie
}
async function parseGethHeader (json) {
const header = new Block.Header()
header.gasLimit = json.gasLimit
header.difficulty = json.difficulty
header.extraData = json.extraData
header.number = Buffer.from([])
header.nonce = json.nonce
header.timestamp = json.timestamp
header.mixHash = json.mixHash
header.stateRoot = (await parseGethState(json.alloc)).root
return header
}
async function parseGethParams (json) {
const header = await parseGethHeader(json)
const params = {
name: json.name,
chainId: json.config.chainId,
networkId: json.config.chainId,
genesis: {
hash: header.hash(),
timestamp: json.timestamp,
gasLimit: json.gasLimit,
difficulty: json.difficulty,
nonce: json.nonce,
extraData: json.extraData,
mixHash: json.mixHash,
coinbase: json.coinbase,
stateRoot: header.stateRoot
},
bootstrapNodes: []
}
const hardforks = [
'chainstart',
'homestead',
'dao',
'tangerineWhistle',
'spuriousDragon',
'byzantium',
'constantinople',
'hybridCasper'
]
const forkMap = {
homestead: 'homesteadBlock',
dao: 'daoForkBlock',
tangerineWhistle: 'eip150Block',
spuriousDragon: 'eip155Block',
byzantium: 'byzantiumBlock'
}
params.hardforks = hardforks.map(name => ({
name: name,
block: name === 'chainstart' ? 0 : json.config[forkMap[name]] || null,
consensus: json.config.clique ? 'poa' : 'pow',
finality: name === 'hybridCasper' ? 'pos' : null
}))
return params
}
async function parseParams (jsonFilePath) {
try {
const json = require(jsonFilePath)
if (json.config && json.difficulty && json.gasLimit && json.alloc) {
json.name = json.name || path.parse(jsonFilePath).base
if (json.nonce === undefined || json.nonce === '0x0') {
json.nonce = '0x0000000000000000'
}
return parseGethParams(json)
} else {
throw new Error('Invalid format')
}
} catch (e) {
throw new Error(`Error parsing parameters file: ${e.message}`)
}
}
exports.bootnodes = parseBootnodes
exports.transports = parseTransports
exports.params = parseParams
|
JavaScript
| 0 |
@@ -151,49 +151,8 @@
e')%0A
-const BN = require('ethereumjs-util').BN%0A
cons
@@ -1100,24 +1100,87 @@
s(alloc)) %7B%0A
+ if (key.startsWith('0x')) %7B%0A key = key.slice(2)%0A %7D%0A
const ad
@@ -1271,15 +1271,8 @@
e =
-new BN(
valu
@@ -1284,22 +1284,8 @@
ance
-.slice(2), 16)
%0A
|
018e6ae2676e89361ac1a373c41ca95b2023938a
|
Remove uneeded method
|
lib/util/shell.js
|
lib/util/shell.js
|
/**
* Module to loosely coupled shell execution.
* @name shell
*/
'use strict';
// Node modules
var spawn = require('child_process').spawn;
var path = require('path');
// npm modules
var _ = require('lodash');
var _shell = require('shelljs');
var esc = require('shell-escape');
var VError = require('verror');
// Kalabox modules
var core = require('../core.js');
var Promise = require('../promise.js');
/**
* Get an env object to inject into child process.
*/
function getEnvironment(opts) {
if (opts.app) {
// Merge app env over the process env and return.
var processEnv = _.cloneDeep(process.env);
var appEnv = opts.app.env.getEnv();
return _.merge(processEnv, appEnv);
} else {
// Just use process env.
return process.env;
}
}
/**
* Executes a shell command.
* @memberof shell
* @arg {string|Array} cmd - The shell command to run or an array of commands.
* @arg {Object} opts - Options
* @example
* return kbox.util.shell.exec(cmd, opts)
* .then(function(output) {
* // things
* });
*/
exports.exec = function(cmd, opts) {
// Merge in our options
var defaults = {silent: true};
var options = (opts) ? _.extend(defaults, opts) : defaults;
// Set environment for spawned process.
options.env = getEnvironment(opts);
// Logging functions.
var execLog = core.log.make('UTIL EXEC');
execLog.debug([cmd, opts]);
// Promisify the exec
return new Promise(function(resolve, reject) {
_shell.exec(esc(cmd), options, function(code, output) {
if (code !== 0) {
reject(new VError('code: ' + code + 'err:' + output));
}
else {
resolve(output);
}
});
});
};
/**
* Executes a shell command.
* @memberof shell
* @arg {string} cmd - The shell command to run.
* @example
* var child = kbox.util.shell.execAsync(cmd);
* child.stdout.on('data', function(data) {
* console.log(data);
* });
* child.stdout.on('end', function() {
* callback();
* });
*/
exports.execAsync = function(cmd, opts) {
// Promisify exec
return new Promise(function(resolve, reject) {
// Merge in our options
var defaults = {
async: true,
silent: true
};
var options = (opts) ? _.extend(defaults, opts) : defaults;
// Set environment for spawned process.
options.env = getEnvironment(opts);
// Logging functions.
var execLog = core.log.make('UTIL EXEC ADMIN');
execLog.debug([cmd, options]);
// Use stdio options and then create the child
var child = _shell.exec(cmd, options);
// Collector for buffer
var stdOut = '';
var stdErr = '';
// Log our stuff
child.stdout.on('data', function(buffer) {
execLog.info(_.trim(String(buffer)));
stdOut = stdOut + String(buffer);
});
// Reject if we get an error
child.stderr.on('data', function(buffer) {
execLog.debug(_.trim(String(buffer)));
stdErr = stdErr + String(buffer);
});
// Callback when done
child.on('close', function(code) {
if (code !== 0) {
reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
}
else {
resolve(stdOut);
}
});
});
};
/**
* Spawns a shell command. And optionally collects things
* @arg {Array} cmd - An array of commands. Split by spaces.
* @arg {Object} opts - Options on what to do
* @example
* return kbox.util.shell.execAdminAsync(cmd, opts)
* .then(function(output) {
* // things
* });
*/
exports.spawn = function(cmd, opts) {
// Promisify the spawn
return new Promise(function(resolve, reject) {
// Merge provided options with defaults
var defaults = {stdio: ['pipe', 'pipe', 'pipe']};
var options = (opts) ? _.extend(defaults, opts) : defaults;
// Set environment for spawned process.
options.env = getEnvironment(opts);
// Use stdio options and then create the child
var entrypoint = cmd.shift();
// Run the spawn
var run = spawn(entrypoint, cmd, options);
// Set of logging functions.
var spawnLog = core.log.make(path.basename(entrypoint).toUpperCase());
spawnLog.debug([entrypoint, cmd, options]);
// Collector for buffer
var stdOut = '';
var stdErr = '';
// Collect data if stdout is being piped
if (options.stdio === 'pipe' || options.stdio[1] === 'pipe') {
run.stdout.on('data', function(buffer) {
spawnLog.info(_.trim(String(buffer)));
stdOut = stdOut + String(buffer);
});
}
// Reject if we get an error
run.on('error', function(buffer) {
spawnLog.info(_.trim(String(buffer)));
stdErr = stdErr + String(buffer);
});
// Callback when done
run.on('close', function(code) {
spawnLog.info('Run exited with code: ' + code);
if (code !== 0) {
reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));
}
else {
resolve(stdOut);
}
});
});
};
/**
* Escapes the spaces in an array or string into a string to make it more CLI friendly
* @arg {string|Array} command - The command to run.
*/
exports.escSpaces = function(s, platform) {
var p = platform || process.platform;
if (_.isArray(s)) {
s = s.join(' ');
}
if (p === 'win32') {
return s.replace(/ /g, '^ ');
}
else {
return s.replace(/ /g, '\ ');
}
};
/**
* Escapes an array or string into a string to make it more CLI friendly
* @arg {string|Array} command - The command to run.
*/
exports.esc = esc;
/**
* Do a which
*/
exports.which = _shell.which;
|
JavaScript
| 0.000001 |
@@ -1673,1525 +1673,8 @@
%7D;%0A%0A
-/**%0A * Executes a shell command.%0A * @memberof shell%0A * @arg %7Bstring%7D cmd - The shell command to run.%0A * @example%0A * var child = kbox.util.shell.execAsync(cmd);%0A * child.stdout.on('data', function(data) %7B%0A * console.log(data);%0A * %7D);%0A * child.stdout.on('end', function() %7B%0A * callback();%0A * %7D);%0A */%0Aexports.execAsync = function(cmd, opts) %7B%0A%0A // Promisify exec%0A return new Promise(function(resolve, reject) %7B%0A%0A // Merge in our options%0A var defaults = %7B%0A async: true,%0A silent: true%0A %7D;%0A var options = (opts) ? _.extend(defaults, opts) : defaults;%0A%0A // Set environment for spawned process.%0A options.env = getEnvironment(opts);%0A%0A // Logging functions.%0A var execLog = core.log.make('UTIL EXEC ADMIN');%0A execLog.debug(%5Bcmd, options%5D);%0A%0A // Use stdio options and then create the child%0A var child = _shell.exec(cmd, options);%0A%0A // Collector for buffer%0A var stdOut = '';%0A var stdErr = '';%0A%0A // Log our stuff%0A child.stdout.on('data', function(buffer) %7B%0A execLog.info(_.trim(String(buffer)));%0A stdOut = stdOut + String(buffer);%0A %7D);%0A%0A // Reject if we get an error%0A child.stderr.on('data', function(buffer) %7B%0A execLog.debug(_.trim(String(buffer)));%0A stdErr = stdErr + String(buffer);%0A %7D);%0A%0A // Callback when done%0A child.on('close', function(code) %7B%0A if (code !== 0) %7B%0A reject(new VError('code' + code + 'err:' + stdErr + 'more:' + stdOut));%0A %7D%0A else %7B%0A resolve(stdOut);%0A %7D%0A %7D);%0A%0A %7D);%0A%0A%7D;%0A%0A
/**%0A
|
c451ae3e163743377d1a1cdd149cffa3fd5f793c
|
fix imports
|
src/components/App.js
|
src/components/App.js
|
import React, { Component } from 'react';
import Header from './Header';
import Body from './Body';
import Contact from './Contact';
import Footer from './Footer';
import styles from './styles/App.scss';
export default class App extends Component {
render() {
return (
<div className={styles.App}>
<Header />
<Body />
<Contact />
<Footer />
</div>
);
}
}
|
JavaScript
| 0.000002 |
@@ -57,17 +57,17 @@
from './
-H
+h
eader';%0A
@@ -86,17 +86,17 @@
from './
-B
+b
ody';%0Aim
@@ -116,17 +116,17 @@
from './
-C
+c
ontact';
@@ -148,17 +148,17 @@
from './
-F
+f
ooter';%0A
@@ -460,8 +460,9 @@
%0A %7D%0A%7D
+%0A
|
a25be6ea0adafe44af145d1a277343fc27a03d45
|
improve the functionality of embedded form
|
src/comments/CommentFormEmbedded.js
|
src/comments/CommentFormEmbedded.js
|
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { FormattedMessage } from 'react-intl';
import { isSmall } from 'react-responsive-utils';
import _ from 'lodash';
import classNames from 'classnames';
import Textarea from 'react-textarea-autosize';
import Icon from '../widgets/Icon';
import * as commentActions from './commentsActions';
import './CommentForm.scss';
@withRouter
@connect(
state => ({
comments: state.comments,
posts: state.posts,
auth: state.auth,
}),
dispatch => bindActionCreators({
sendComment: (depth, parentId) => commentActions.sendComment(depth, parentId),
updateCommentingDraft: commentActions.updateCommentingDraft,
}, dispatch)
)
export default class CommentFormEmbedded extends Component {
constructor(props) {
super(props);
this.state = {
draftValue: '',
};
}
static PropTypes = {
parentId: React.PropTypes.string.isRequired,
isReplyToComment: React.PropTypes.bool,
};
static defaultProps = {
isReplyToComment: false,
};
componentDidMount() {
const { parentId, posts, comments, isReplyToComment, isEditing } = this.props;
const content = isReplyToComment ? comments.comments[parentId] : posts[parentId];
let payload;
if (isEditing) {
payload = {
id: parentId,
parentAuthor: content.parent_author,
category: content.category,
permlink: content.permlink,
parentPermlink: content.parent_permlink,
isReplyToComment: true,
isEditing: true,
body: content.body,
};
} else {
payload = {
id: parentId,
body: '',
parentAuthor: content.author,
parentPermlink: content.permlink,
category: content.category,
isReplyToComment,
};
}
this.props.updateCommentingDraft(payload);
this.loadDraft();
}
componentWillReceiveProps(nextProps) {
const { parentId, comments } = nextProps;
const draftValue =
(comments.commentingDraft[parentId] && comments.commentingDraft[parentId].body);
this.setState({ draftValue });
}
updateDraft = _.debounce(() => {
this.props.updateCommentingDraft({
id: this.props.parentId,
body: this.state.draftValue,
});
}, 1000);
loadDraft() {
const { parentId, comments } = this.props;
const draftValue =
(comments.commentingDraft[parentId] && comments.commentingDraft[parentId].body);
this.setState({ draftValue });
}
handleSubmit(e, commentDepth) {
e.stopPropagation();
this.updateDraft();
this.props.sendComment(commentDepth, this.props.parentId).then(() => {
this.setState({ draftValue: '' });
if (_.isFunction(this.props.onSubmit)) this.props.onSubmit();
});
}
handleTextChange = (e) => {
this.setState({ draftValue: e.target.value });
this.updateDraft();
};
render() {
const { comments, posts, isReplyToComment, parentId } = this.props;
const commentsClass = classNames({
CommentForm: true,
'CommentForm--embedded': true,
'py-1': true,
mobile: isSmall(),
});
let parentTitle = '';
// will need depth in optimistic payload since it's used to style nested comments
let commentDepth;
const commentsData = comments.comments;
if (isReplyToComment) {
const replyingComment = commentsData[parentId];
parentTitle = `${replyingComment.author} in ${replyingComment.root_title}`;
commentDepth = commentsData[parentId].depth + 1;
} else {
parentTitle = posts[parentId].title;
commentDepth = 1;
}
return (
<div className={commentsClass}>
<div className="container">
<div className="my-2">
<i className="icon icon-sm material-icons">reply</i>
{' '}<FormattedMessage id="reply_to" />{' '}
<b>{parentTitle}</b>
</div>
<Textarea
className="CommentForm__input my-2 p-2"
placeholder={'Write a comment...'}
value={this.state.draftValue}
onChange={this.handleTextChange}
/>
<button
onClick={e => this.handleSubmit(e, commentDepth)}
className="btn btn-success CommentForm__submit"
>
<Icon name="send" />
</button>
</div>
</div>
);
}
}
|
JavaScript
| 0.000001 |
@@ -463,24 +463,66 @@
tsActions';%0A
+import Loading from '../widgets/Loading';%0A
import './Co
@@ -710,23 +710,16 @@
mment: (
-depth,
parentId
@@ -754,15 +754,8 @@
ent(
-depth,
pare
@@ -982,24 +982,46 @@
tValue: '',%0A
+ loading: false,%0A
%7D;%0A %7D%0A%0A
@@ -2667,30 +2667,16 @@
Submit(e
-, commentDepth
) %7B%0A
@@ -2701,36 +2701,66 @@
);%0A this.
-updateDraft(
+setState(%7B draftValue: '', loading: true %7D
);%0A this.
@@ -2781,22 +2781,8 @@
ent(
-commentDepth,
this
@@ -2847,16 +2847,134 @@
alue: ''
+, loading: false %7D);%0A this.props.updateCommentingDraft(%7B%0A id: this.props.parentId,%0A body: '',%0A
%7D);%0A
@@ -3244,24 +3244,87 @@
his.props;%0A%0A
+ if (this.state.loading) %7B%0A return %3CLoading /%3E;%0A %7D%0A%0A
const co
@@ -3496,116 +3496,8 @@
'';%0A
- // will need depth in optimistic payload since it's used to style nested comments%0A let commentDepth;%0A
@@ -3705,63 +3705,8 @@
%7D%60;%0A
- commentDepth = commentsData%5BparentId%5D.depth + 1;%0A
@@ -3761,32 +3761,8 @@
le;%0A
- commentDepth = 1;%0A
@@ -4344,22 +4344,8 @@
it(e
-, commentDepth
)%7D%0A
|
adab9a4a572cef1cab670bdc65b6d740f2cf0230
|
Remove zero values from pie chart
|
src/common/directives/d3PieChart.js
|
src/common/directives/d3PieChart.js
|
angular.module('ngQuestionnaires.directives')
.directive('d3PieChart', function (d3) {
return {
restrict: 'A',
scope: {
data: '=',
label: '@',
value: '@',
height: '@'
},
link: function (scope, element, attrs) {
var chart = d3.select(element[0])
.append('svg')
.attr('class', 'pie-chart'),
height = scope.height || 500,
colour = d3.scale.category20(),
value = function (d) {
return d[scope.value];
};
scope.$watch('data', function (data) {
scope.render(data);
}, true);
scope.render = function (data) {
var width = chart[0][0].offsetWidth,
radius = Math.min(height, width) / 2,
margin = 30,
arc = d3.svg.arc()
.startAngle(function (d) {
return d.startAngle;
})
.endAngle(function (d) {
return d.endAngle;
})
.outerRadius(radius - margin)
.innerRadius(45),
pie = d3.layout.pie().value(value),
arcs,
total = 0,
pieData,
label = function (d) {
var percentage = (d.data[scope.value] / total) * 100;
return percentage.toFixed(1) + "%";
};
chart.selectAll('*').remove();
if (!data || !angular.isArray(data)) {
return;
}
// Remove any zero values from data
/*
data = data.filter(function (d) {
return +d[scope.value] !== 0;
});
*/
data.forEach(function (d) {
total += d[scope.value];
});
pieData = pie(data);
arcs = chart.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
.selectAll('.arc')
.data(pieData)
.enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('d', arc)
.attr('fill', function (d, i) {
return colour(i);
});
chart.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
.selectAll('line')
.data(pieData)
.enter()
.append('line')
.attr('x1', 0)
.attr('x2', 0)
.attr('y1', -radius + margin - 1)
.attr('y2', -radius + margin - 10)
.attr('transform', function (d) {
return 'rotate(' + (d.startAngle + d.endAngle) / 2 * (180 / Math.PI) + ')';
});
chart.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
.selectAll('text')
.data(pieData)
.enter()
.append('text')
.attr("dy", function (d) {
if ((d.startAngle + d.endAngle) / 2 > Math.PI / 2 && (d.startAngle + d.endAngle) / 2 < Math.PI * 1.5) {
return 5;
} else {
return -7;
}
})
.attr("transform", function (d) {
return "translate(" + Math.cos(((d.startAngle + d.endAngle - Math.PI) / 2)) * (radius - margin + 12) + "," +
Math.sin((d.startAngle + d.endAngle - Math.PI) / 2) * (radius - margin + 12) + ")";
})
.attr("text-anchor", function (d) {
if ((d.startAngle + d.endAngle) / 2 < Math.PI) {
return "beginning";
} else {
return "end";
}
})
.attr('fill', function (d, i) {
return colour(i);
})
.text(function (d) {
return d.data[scope.label];
});
arcs.append('text')
.attr('transform', function (d) {
return 'translate(' + arc.centroid(d) + ')';
})
.attr('dy', '0.33em')
.attr('text-anchor', 'middle')
.text(label);
chart.append('text')
.attr('class', 'label')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
.attr('dy', -5)
.attr('text-anchor', 'middle')
.text('TOTAL');
chart.append('text')
.attr('class', 'total')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
.attr('dy', 20)
.attr('text-anchor', 'middle')
.text(total);
};
}
};
});
|
JavaScript
| 0.000116 |
@@ -1548,22 +1548,8 @@
ata%0A
- /*%0A
@@ -1580,32 +1580,33 @@
(function (d) %7B%0A
+
retur
@@ -1644,26 +1644,11 @@
-
%7D);
-%0A */
%0A%0A
|
81cdf0d1694bd6d30fb07dc3cc412e59be22d3f3
|
Fix typo
|
src/foam/u2/detail/AbstractSectionedDetailView.js
|
src/foam/u2/detail/AbstractSectionedDetailView.js
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.detail',
name: 'AbstractSectionedDetailView',
extends: 'foam.u2.View',
documentation: `
The abstract for property-sheet style Views with sections for editing an FObject.
`,
requires: [
'foam.core.Action',
'foam.core.Property',
'foam.layout.Section',
'foam.layout.SectionAxiom'
],
properties: [
{
class: 'FObjectProperty',
name: 'data',
factory: function() {
return this.hasOwnProperty('of') ? this.of.create(null, this) : null;
},
postSet: function(oldValue, newValue) {
this.of = newValue ? newValue.cls_ : undefined;
}
},
{
class: 'Class',
name: 'of',
expression: function(data) {
return data && data.cls_;
}
},
{
class: 'FObjectArray',
of: 'foam.core.Property',
name: 'propertyWhiteList',
documentation: `
If this array is not empty, only the properties listed in it will be
included in the detail view.
`,
preSet: function(_, ps) {
foam.assert(ps, 'Properties required.');
for ( var i = 0; i < ps.length; i++ ) {
foam.assert(
foam.core.Property.isInstance(ps[i]),
`Non-Property in 'properties' list:`,
ps);
}
return ps;
}
},
{
class: 'FObjectArray',
of: 'foam.layout.Section',
name: 'sections',
factory: null,
expression: function(of) {
if ( ! of ) return [];
sections = of.getAxiomsByClass(this.SectionAxiom)
.sort((a, b) => a.order - b.order)
.map((a) => this.Section.create().fromSectionAxiom(a, of));
var usedAxioms = sections
.map((s) => s.properties.concat(s.actions))
.flat()
.reduce((map, a) => {
map[a.name] = true;
return map;
}, {});
var unusedProperties = of.getAxiomsByClass(this.Property)
.filter((p) => ! usedAxioms[p.name])
.filter((p) => ! p.hidden);
var unusedActions = of.getAxiomsByClass(this.Action)
.filter((a) => ! usedAxioms[a.name]);
if ( unusedProperties.length || unusedActions.length ) {
sections.push(this.Section.create({
properties: unusedProperties,
actions: unusedActions
}));
}
if ( this.propertyWhitelist ) {
sections = sections
.map((s) => {
s.properties = s.properties.filter((p) => this.propertyWhitelist.includes(p));
return s;
})
.filter((s) => {
return s.properties.length > 0 || s.actions.length > 0;
});
}
return sections;
}
}
]
});
|
JavaScript
| 0.999999 |
@@ -994,17 +994,17 @@
rtyWhite
-L
+l
ist',%0A
@@ -1147,16 +1147,37 @@
%60,%0A
+ factory: null,%0A
pr
|
786a0b30020935381212d7bdd75c5d931ca1d472
|
fix typo
|
download.js
|
download.js
|
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
var promise = require('promise');
var fs = require('fs');
var htmlEscape = require("html-escape");
var getOpt = require('node-getopt');
var opt = getOpt.create([
['', 'page[=PAGE]' , 'Rnages of pages to fetch (start:end)'],
['', 'output[=DIR]' , 'Output'],
['', 'overwrite' , 'Whether to overwrite existing chapters'],
['h', 'help' , 'Display help']
]).bindHelp().parseSystem();
function getOnePage(url) {
return new Promise(function(resolve, reject) {
console.log('Downloading', url);
request(url, function(err, response, html) {
if (err) {
var errMsg = 'Error downloading' + url + err;
console.log(errMsg);
reject(errMsg);
}
console.log('Downloaded', url);
resolve(html);
});
});
}
function getSections(url) {
return getOnePage(url).then(function(content) {
$ = cheerio.load(content);
return $('td[id^=postmessage]').toArray();
});
}
function writeFile(fileName, text) {
fs.exists(fileName, function(exists) {
if (exists) {
if (opt.options['overwrite']) {
console.log('Overwrite', fileName);
} else {
console.log('Skip', fileName);
return;
}
} else {
console.log('New file', fileName);
}
fs.writeFile(fileName, text);
});
}
function processSections(index, sections) {
for (i = 0; i < sections.length; ++i) {
// Sanitize.
var node = $(sections[i]);
node.find('.pstatus').remove();
node.find('ignore_js_op').remove();
node.find('a').remove();
node.find('br').replaceWith('\n\n');
// Normalize line break and space.
// Remove bad char which causes problems when translating to epub (0x0c).
var text = node.text()
.replace(/\r\n/g, '').replace(/\u3000|\xa0/g, ' ')
.replace(/\x0c/g, '');
// epub creator often treats text as html so needs to escape.
text = htmlEscape(text);
// Try best to guess redundant line break used to control layout on forum.
text = text.replace(/([^。,?!」])\n\n([^\s])/g, '$1$2');
console.log('Writing chapter', index);
writeFile(String(index++) + '.part', text);
}
return index;
}
var URL_TEMPLATE = 'http://ck101.com/thread-1586268-%s-1.html';
function download(startPage, endPage) {
// Use promise to chain parallel responses in order.
var all = Promise.resolve(1);
for (var i = startPage; i <= endPage; ++i) {
var url = util.format(URL_TEMPLATE, i);
// Create a closure so the "page" is copied. Otherwise the same
// object is referenced when page is done in each iteration.
all = (function(page){
return all.then(function(index) {
return page.then(processSections.bind(undefined, index));
}, function(err) {
console.log(err);
});
})(getSections(url));
}
all.then(function() {
console.log('All Done.');
}, function(err) {
console.log(err);
});
}
function getPageNum() {
console.log('Getting num of pages');
var firstPage = util.format(URL_TEMPLATE, 1);
return getOnePage(firstPage).then(function(content) {
$ = cheerio.load(content);
return parseInt($('.pgt .pg a.last').text().match(/\d+/)[0], 10);
});
}
function main() {
if ('output' in opt.options) {
try {
process.chdir(opt.options['output']);
} catch (e) {
console.log('Couldn not change directory', d);
return;
};
}
var startPage = 1;
var endPage = null;
if ('page' in opt.options) {
pageRange = opt.options['page'].split(':');
startPage = parseInt(pageRange[0], 10) || startPage;
endPage = parseInt(pageRange[1], 10) || endPage;
}
var last = endPage ? Promise.resolve(endPage) : getPageNum();
last.then(function(endPage) {
console.log('start page', startPage, 'end page', endPage);
download(startPage, endPage);
});
}
main();
|
JavaScript
| 0.999991 |
@@ -3463,17 +3463,17 @@
ctory',
-d
+e
);%0A
|
e22f0e267809e1fc65d9b41ee45853110db02fcc
|
Remove trailing whitespace
|
jquery.cookie.js
|
jquery.cookie.js
|
/*!
* jQuery Cookie Plugin v1.3.0
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function ($, document, undefined) {
var pluses = /\+/g;
function raw(s) {
return s;
}
function decoded(s) {
return unRfc2068(decodeURIComponent(s.replace(pluses, ' ')));
}
function unRfc2068(value) {
if (value.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape
value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
return value;
}
var config = $.cookie = function (key, value, options) {
// write
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// read
var decode = config.raw ? raw : decoded;
var cookies = document.cookie.split('; ');
var result = key ? null : {};
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = decode(parts.join('='));
if (config.json) {
cookie = JSON.parse(cookie);
}
if (key && key === name) {
result = cookie;
break;
}
if (!key) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== null) {
$.cookie(key, null, options);
return true;
}
return false;
};
})(jQuery, document);
|
JavaScript
| 0.999999 |
@@ -329,17 +329,16 @@
)));%0A%09%7D%0A
-%09
%0A%09functi
@@ -1694,20 +1694,17 @@
('='));%0A
-%09%09%09
%0A
+
%09%09%09if (c
@@ -1751,28 +1751,25 @@
okie);%0A%09%09%09%7D%0A
-%09%09%09
%0A
+
%09%09%09if (key &
@@ -1823,19 +1823,16 @@
k;%0A%09%09%09%7D%0A
-%09%09%09
%0A%09%09%09if (
|
02f7394b83303ca19b8981ada3d031abe032efad
|
use bootstrap default classes
|
jquery.tabify.js
|
jquery.tabify.js
|
(function($) {
function Tab($tab, $pane) {
var self = this;
this.$tab = $tab;
this.$pane = $pane;
this.$tab.on('click', function() {
self.select();
});
this.$tab.on('select-tab',function() {
var name;
if (name = self.name()) {
window.location.hash = '#' + name;
if ($('.js-current-tab').length) {
$('.js-current-tab').val(name);
}
}
});
}
Tab.prototype = {
name: function() {
return this._name || this.$tab.data('name') || this.$pane.data('name');
},
select: function() {
this.$pane.siblings().each(function() {
$(this).removeClass('current');
});
this.$tab.siblings().each(function() {
var $it = $(this);
$it.removeClass('selected');
$it.trigger('deselect-tab');
});
this.$pane.addClass('current');
this.$tab
.addClass('selected')
.trigger('select-tab');
}
};
$.fn.tabify = function() {
var $elem = this;
if ($elem.length > 1) {
$elem.each(function() {
$(this).tabify();
});
return;
}
var $tabs = $('<ul />');
$tabs.addClass('tabs');
$elem.find('.js-tab').not($elem.find('.js-tabs .js-tab')).each(function(i) {
var $self = $(this);
var $title = $self.find('.js-title').eq(0);
if (! $title.length) {
$title = $self.find(':header').eq(0);
}
var $tab = $('<li />');
$tab.html($title.html());
$title.remove();
$tabs.append($tab);
var tab = new Tab($tab, $self);
$tab.data('tab', tab);
$self.data('tab', tab);
if (i==0) {
$tab.addClass('selected');
$self.addClass('current');
};
});
$elem.prepend($tabs);
$(function() {
var uri_tab = window.location.hash.substr(1);
function wanted() {
return $(this).data('tab').name() == uri_tab;
}
if (uri_tab) {
// TODO: A refactor would make this cleaner.
var $t = $tabs.children().filter(wanted).eq(0);
if (! $t.length) {
return;
}
var parent;
if (parent = $t.closest('.js-tab').data('tab')) {
parent.select();
}
$t.data('tab').select();
}
});
};
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -884,24 +884,31 @@
= function(
+options
) %7B%0A
@@ -967,32 +967,39 @@
m.each(function(
+options
) %7B%0A%09%09%09%09$(this).
@@ -1032,16 +1032,139 @@
n;%0A%09%09%7D%0A%0A
+%09%09options = $.extend(%7B%0A%09%09%09'tab_container_class' =%3E 'nav nav-tabs',%0A%09%09%09'tab_content_class' =%3E 'tab-content',%0A%09%09%7D, options);%0A
@@ -1189,24 +1189,18 @@
/%3E');%0A%0A
-
+%09%09
$tabs.ad
@@ -1210,14 +1210,35 @@
ass(
-'tabs'
+options.tab_container_class
);%0A%0A
@@ -2316,24 +2316,68 @@
).select();%0A
+%09%09%09%09$t.addClass(options.tab_content_class);%0A
%09%09%09%7D%0A%09%09%7D);%0A
|
2a74980be9df4948be3bfe5667b165ae0e1fe266
|
add @ts-nocheck before renaming to .ts
|
js/ArrowShape.js
|
js/ArrowShape.js
|
// Copyright 2013-2022, University of Colorado Boulder
/**
* An arrow shape, either single or double headed.
* ArrowShape has an optimization that allows you to reuse an array of Vector2.
* The array will have 0 points if the tail and tip are the same point.
*
* @author John Blanco
* @author Chris Malley (PixelZoom, Inc.)
* @author Aaron Davis
* @author Sam Reid (PhET Interactive Simulations)
*/
import Vector2 from '../../dot/js/Vector2.js';
import { Shape } from '../../kite/js/imports.js';
import merge from '../../phet-core/js/merge.js';
import sceneryPhet from './sceneryPhet.js';
class ArrowShape extends Shape {
/**
* @param {number} tailX
* @param {number} tailY
* @param {number} tipX
* @param {number} tipY
* @param {Object} [options]
*/
constructor( tailX, tailY, tipX, tipY, options ) {
options = merge( {
tailWidth: 5,
headWidth: 10,
headHeight: 10,
doubleHead: false, // determines whether the arrow has a head at both ends of the tail
isHeadDynamic: false, // determines whether to scale down the arrow head height for fractionalHeadHeight constraint
scaleTailToo: false, // determines whether to also scale arrow head width and tail width when scaling head height
fractionalHeadHeight: 0.5 // head will be scaled when headHeight is greater than fractionalHeadHeight * arrow length
}, options );
super();
if ( tipX !== tailX || tipY !== tailY ) {
const points = ArrowShape.getArrowShapePoints( tailX, tailY, tipX, tipY, [], options );
// Describe the shape
this.moveTo( points[ 0 ].x, points[ 0 ].y );
const tail = _.tail( points );
_.each( tail, element => this.lineTo( element.x, element.y ) );
this.close();
}
}
/**
* This method is static so it can be used in ArrowShape as well as in ArrowNode. If the tail and tip are at the
* same position, there are no points and the arrow will not be shown.
* @param {number} tailX
* @param {number} tailY
* @param {number} tipX
* @param {number} tipY
* @param {Vector2[]} shapePoints - if provided, values will be overwritten. This is to achieve
* high performance and is used by ArrowNode to avoid re-creating shapes.
* Tested this implementation vs the old one by creating hundreds of arrows and
* saw significant performance gains.
* @param {Object} [options]
* @returns {Vector2[]}
* @public
*/
static getArrowShapePoints( tailX, tailY, tipX, tipY, shapePoints, options ) {
// default shapePoints to empty array if it isn't passed in
if ( !shapePoints ) {
shapePoints = [];
}
if ( tipX === tailX && tipY === tailY ) {
// if arrow has no length, it should have no points so that we don't attempt to draw anything
shapePoints.length = 0;
}
else {
// create a vector representation of the arrow
const vector = new Vector2( tipX - tailX, tipY - tailY );
const length = vector.magnitude;
// start with the dimensions specified in options
let headWidth = options.headWidth;
let headHeight = options.headHeight;
let tailWidth = options.tailWidth;
// handle scaling of the head and tail
if ( options.isHeadDynamic ) {
const maxHeadHeight = options.fractionalHeadHeight * length;
// scale down the head height if it exceeds the max
if ( options.headHeight > maxHeadHeight ) {
headHeight = maxHeadHeight;
// optionally scale down the head width and tail width
if ( options.scaleTailToo ) {
headWidth = options.headWidth * headHeight / options.headHeight;
tailWidth = options.tailWidth * headHeight / options.headHeight;
}
}
}
else {
// otherwise, just make sure that head height is less than arrow length
headHeight = Math.min( options.headHeight, options.doubleHead ? 0.35 * length : 0.99 * length );
}
// Index into shapePoints, incremented each time addPoint is called.
let index = 0;
// Set up a coordinate frame that goes from the tail of the arrow to the tip.
const xHatUnit = vector.normalized();
const yHatUnit = xHatUnit.rotated( Math.PI / 2 );
// Function to add a point to shapePoints
const addPoint = function( xHat, yHat ) {
const x = xHatUnit.x * xHat + yHatUnit.x * yHat + tailX;
const y = xHatUnit.y * xHat + yHatUnit.y * yHat + tailY;
if ( shapePoints[ index ] ) {
shapePoints[ index ].x = x;
shapePoints[ index ].y = y;
}
else {
shapePoints.push( new Vector2( x, y ) );
}
index++;
};
// Compute points for single- or double-headed arrow
if ( options.doubleHead ) {
addPoint( 0, 0 );
addPoint( headHeight, headWidth / 2 );
addPoint( headHeight, tailWidth / 2 );
}
else {
addPoint( 0, tailWidth / 2 );
}
addPoint( length - headHeight, tailWidth / 2 );
addPoint( length - headHeight, headWidth / 2 );
addPoint( length, 0 );
addPoint( length - headHeight, -headWidth / 2 );
addPoint( length - headHeight, -tailWidth / 2 );
if ( options.doubleHead ) {
addPoint( headHeight, -tailWidth / 2 );
addPoint( headHeight, -headWidth / 2 );
}
else {
addPoint( 0, -tailWidth / 2 );
}
if ( index < shapePoints.length ) {
shapePoints.length = index;
}
}
return shapePoints;
}
}
sceneryPhet.register( 'ArrowShape', ArrowShape );
export default ArrowShape;
|
JavaScript
| 0.000001 |
@@ -49,16 +49,31 @@
oulder%0A%0A
+// @ts-nocheck%0A
/**%0A * A
|
ac5e8ece582cf17b8c359a32ba194e7a17758900
|
fix widget loader middleware
|
lib/view/index.js
|
lib/view/index.js
|
/**
* wejs view feature
*/
var hbs = require('hbs');
var fs = require('fs');
var _ = require('lodash');
var env = require('../env.js');
var Theme = require('../class/Theme.js');
var async = require('async');
var log = require('../log')();
var view = {
assets: require('./assets'),
layoutCache: {},
templateCache: {},
layouts: {},
templates: {},
helpers: {},
widgets: {},
configuration: {
layouts: {},
templates: {},
helpers: {},
widgets: {}
},
themes: {},
initialize: function initialize(we) {
view.getWe = function getWe(){ return we };
we.hbs = hbs;
we.events.on('router:before:set:controller:middleware', function(data) {
data.middlewares.push(view.middleware.bind(data.config));
});
var themesConfig = require('./loadThemeConfig')();
// load all themes
for (var i = 0; i < themesConfig.enabled.length; i++) {
view.themes[themesConfig.enabled[i]] = new Theme(
themesConfig.enabled[i], we.projectPath
);
view.themes[themesConfig.enabled[i]].projectThemeName = themesConfig.enabled[i];
}
view.appTheme = themesConfig.app;
view.adminTheme = themesConfig.admin;
// log themes loaded
if (env != 'prod') {
var themesLoaded = Object.keys(view.themes);
console.log( themesLoaded.length + ' themes loaded: ' + themesLoaded.join(', ') );
}
},
setExpressConfig: function setExpressConfig(express) {
express.use(function viewConfigMiddleware(req, res, next){
res.renderPage = view.renderPage.bind({req: req, res: res});
// default theme, is changed if are in admin area
res.locals.theme = view.appTheme;
// theme object getter
res.getTheme = view.geTheme;
// set default htmlTemplate file
res.locals.htmlTemplate = 'html';
if (req.query.skipHTML) res.locals.skipHTML = true;
next();
})
},
geTheme: function geTheme() {
return view.themes[this.locals.theme];
},
middleware: function middleware(req, res, next) {
// only work with html requests
if (res.locals.responseType != 'html') return next();
if (!res.locals.layoutName) res.locals.layoutName = 'default';
var we = req.getWe();
if (!res.locals.regions) res.locals.regions = {};
// preload all widgets for this response
// TODO add a widgets cache in memory
we.db.models.widget.findAll({
where: {
theme: res.locals.theme,
layout: res.locals.layoutName,
context: (res.locals.widgetContext || null),
controller: {
$or: [res.locals.controller , null]
},
action: {
$or: [res.locals.action , null]
}
},
order: 'weight ASC'
}).then(function (widgets) {
async.each(widgets, function (widget, nextW) {
// set region if not exits
if (!res.locals.regions[widget.regionName])
res.locals.regions[widget.regionName] = {widgets: []};
// set widget
res.locals.regions[widget.regionName].widgets.push(widget);
// run view middleware for load widget view data
widget.viewMiddleware(req, res, nextW);
}, next);
});
},
registerAll: function registerAll() {
var we = view.getWe();
this.registerHelpers(we);
},
registerHelpers: function registerHelpers(we) {
for (var helperName in view.configuration.helpers) {
hbs.registerHelper( helperName, require( view.configuration.helpers[helperName] )(we, view) );
}
},
renderLayout: function renderLayout(req, res, data) {
var template, theme = res.getTheme();
if (!res.locals.layoutName) {
if (req.model && theme.layouts[req.model+'/layout']) {
res.locals.layoutName = req.model+'/layout';
} else {
res.locals.layoutName = 'default';
}
}
res.locals.body = view.renderTemplate(res.locals.template, res.locals.theme, res.locals);
// unique name for current theme layout
var layoutThemeName = res.locals.theme + '/' + res.locals.layoutName;
if (env === 'prod' && view.layoutCache[layoutThemeName]) {
template = view.layoutCache[layoutThemeName];
} else {
if (theme.layouts[res.locals.layoutName]) {
template = hbs.compile(fs.readFileSync(theme.layouts[res.locals.layoutName].template, 'utf8'));
} else {
template = hbs.compile(fs.readFileSync(view.configuration.layouts[res.locals.layoutName].template, 'utf8'));
}
if (env === 'prod') {
// cache it if are prod env
view.layoutCache[layoutThemeName] = template;
}
}
if (data) _.merge(res.locals, data);
if (res.locals.skipHTML) {
return template(res.locals);
} else {
res.locals.layoutHtml = '<layout id="we-layout">' + template(res.locals) + '</layout>';
return view.renderTemplate(res.locals.htmlTemplate, res.locals.theme, res.locals);
}
},
/**
* render one template, first check if the template exists in theme if now fallback to plugin tempalte
* @param {String} name template name
* @param {String} themeName current theme name
* @param {Object} data Data to send to template
* @return {String} compiled template html
*/
renderTemplate: function renderTemplate(name, themeName, data) {
var theme = view.themes[themeName];
var template;
// unique name for current theme template
var templateThemeName = themeName + '/' + name;
// first check in cache
if (env === 'prod' && view.templateCache[templateThemeName])
return view.templateCache[templateThemeName](data);
// resolve template
if (theme.templates[name]) {
// theme template
template = hbs.compile(fs.readFileSync(theme.templates[name], 'utf8'));
} else if (view.configuration.templates[name]) {
// plugin template
template = hbs.compile(fs.readFileSync(view.configuration.templates[name], 'utf8'));
} else if (data && data.fallbackTemplate) {
// fallback template
template = hbs.compile(fs.readFileSync(data.fallbackTemplate, 'utf8'));
} else {
log.error('Template not found: ' + name + ' themeName: ' + themeName);
return '';
}
if (env === 'prod') {
// cache it if are prod env
view.templateCache[templateThemeName] = template;
}
try {
return template(data);
} catch(e) {
log.error('Error on render template: ',name, template, e);
return '';
}
},
renderPage: function renderPage(req, res, data) {
res.send(view.renderLayout(req, res, data));
},
themeScriptTag: function themeScriptTag(src) {
return '<script type="text/javascript" src="'+ src +'"></script>';
},
themeStylesheetTag: function themeStylesheetTag(href) {
return '<link href="'+ href +'" rel="stylesheet" type="text/css">'
},
// --forms feature
forms: {}
};
module.exports = view;
|
JavaScript
| 0.000001 |
@@ -2532,17 +2532,16 @@
null),%0A
-%0A
@@ -2553,26 +2553,16 @@
oller: %7B
-%0A
$or: %5Br
@@ -2588,25 +2588,21 @@
r , null
-%5D%0A
+, ''%5D
%7D,%0A
@@ -2614,26 +2614,16 @@
ction: %7B
-%0A
$or: %5Br
@@ -2649,17 +2649,13 @@
null
-%5D%0A
+, ''%5D
%7D%0A
|
71563991b339f58a5142dcb8086cb5d4400a1a83
|
use mipmap for logos in PhetButton, phetsims/joist#258
|
js/PhetButton.js
|
js/PhetButton.js
|
// Copyright 2002-2013, University of Colorado Boulder
/**
* The button that pops up the PhET menu, which appears in the bottom right of the home screen and on the right side
* of the navbar.
*
* @author Sam Reid
*/
define( function( require ) {
'use strict';
// modules
var AdaptedFromText = require( 'JOIST/AdaptedFromText' );
var Brand = require( 'BRAND/Brand' );
var Node = require( 'SCENERY/nodes/Node' );
var Image = require( 'SCENERY/nodes/Image' );
var FontAwesomeNode = require( 'SUN/FontAwesomeNode' );
var inherit = require( 'PHET_CORE/inherit' );
var PhetMenu = require( 'JOIST/PhetMenu' );
var Property = require( 'AXON/Property' );
var JoistButton = require( 'JOIST/JoistButton' );
var UpdateCheck = require( 'JOIST/UpdateCheck' );
// images
var phetLogo = require( 'image!BRAND/logo.png' ); // on a black navbar
var phetLogoDarker = require( 'image!BRAND/logo-on-white.png' ); // on a white navbar
/**
* @param {Sim} sim
* @param {Property.<Color|string>} backgroundFillProperty
* @param {Property.<Color|string>} textFillProperty
* @param {Object} [options] Unused in client code.
* @constructor
*/
function PhetButton( sim, backgroundFillProperty, textFillProperty, options ) {
options = _.extend( {
textDescription: 'PhET Menu Button',
phetLogoScale: 0.28, // {number}
highlightExtensionWidth: 6,
highlightExtensionHeight: 5,
highlightCenterOffsetY: 4,
tandem: null,
listener: function() {
var phetMenu = new PhetMenu( sim, {
showSaveAndLoad: sim.options.showSaveAndLoad,
tandem: options.tandem && options.tandem.createTandem( 'phetMenu' ),
closeCallback: function() {
// hides the popup and barrier background
sim.hidePopup( phetMenu, true );
phetMenu.dispose();
}
} );
/**
* Sim.js handles scaling the popup menu. This code sets the position of the popup menu.
* @param {Bounds2} bounds - the size of the window.innerWidth and window.innerHeight, which depends on the scale
* @param {Bounds2} screenBounds - subtracts off the size of the navbar from the height
* @param {number} scale - the overall scaling factor for elements in the view
*/
function onResize( bounds, screenBounds, scale ) {
phetMenu.right = bounds.right / scale - 2 / scale;
var navBarHeight = bounds.height - screenBounds.height;
phetMenu.bottom = screenBounds.bottom / scale + navBarHeight / 2 / scale;
}
sim.on( 'resized', onResize );
onResize( sim.bounds, sim.screenBounds, sim.scale );
phetMenu.show();
}
}, options );
// The PhET Label, which is the PhET logo
var phetLabel = new Image( phetLogo, {
scale: options.phetLogoScale,
pickable: false
} );
var optionsButton = new FontAwesomeNode( 'reorder', {
scale: 0.6,
left: phetLabel.width + 10,
bottom: phetLabel.bottom - 1.5,
pickable: false
} );
// The icon combines the PhET label and the thre horizontal bars in the right relative positions
var icon = new Node( { children: [ phetLabel, optionsButton ] } );
JoistButton.call( this, icon, backgroundFillProperty, options );
// If this is an "adapted from PhET" brand, decorate the PhET button with "adapted from" text.
if ( Brand.id === 'adapted-from-phet' ) {
this.addChild( new AdaptedFromText( textFillProperty, {
pickable: false,
right: icon.left - 10,
centerY: icon.centerY
} ) );
}
Property.multilink( [ backgroundFillProperty, sim.showHomeScreenProperty, UpdateCheck.stateProperty ],
function( backgroundFill, showHomeScreen, updateState ) {
var backgroundIsWhite = backgroundFill !== 'black' && !showHomeScreen;
var outOfDate = updateState === 'out-of-date';
optionsButton.fill = backgroundIsWhite ? ( outOfDate ? '#0a0' : '#222' ) : ( outOfDate ? '#3F3' : 'white' );
phetLabel.image = backgroundIsWhite ? phetLogoDarker : phetLogo;
} );
}
return inherit( JoistButton, PhetButton, {},
//statics
{
//How much space between the PhetButton and the right side of the screen.
HORIZONTAL_INSET: 5,
//How much space between the PhetButton and the bottom of the screen
VERTICAL_INSET: 0
} );
} );
|
JavaScript
| 0 |
@@ -802,37 +802,38 @@
ogo = require( '
-image
+mipmap
!BRAND/logo.png'
@@ -890,21 +890,22 @@
quire( '
-image
+mipmap
!BRAND/l
|
9330476515586258e785eb69b8fdcfdd1d9e210d
|
Add files as soft links. Closes #1334 (#1335)
|
src/common/plugin/GeneratedFiles.js
|
src/common/plugin/GeneratedFiles.js
|
/*globals define*/
define([
'common/util/assert',
'deepforge/storage/index',
], function(
assert,
Storage,
) {
const GeneratedFiles = function(blobClient) {
this.blobClient = blobClient;
this._files = {};
this._data = {};
};
GeneratedFiles.prototype.addUserAsset = function (path, dataInfo) {
assert(!!dataInfo, `Adding undefined user asset: ${path}`);
dataInfo = typeof dataInfo === 'object' ? dataInfo : JSON.parse(dataInfo);
this._data[path] = dataInfo;
};
GeneratedFiles.prototype.getUserAssetPaths = function () {
return Object.keys(this._data);
};
GeneratedFiles.prototype.getUserAsset = function (path) {
return this._data[path];
};
GeneratedFiles.prototype.getUserAssets = function () {
return Object.entries(this._data);
};
GeneratedFiles.prototype.addFile = function (path, contents) {
assert(typeof contents === 'string', `Cannot add non-string file ${path}.`);
this._files[path] = contents;
};
GeneratedFiles.prototype.appendToFile = function (path, contents) {
this._files[path] = (this._files[path] || '') + contents;
};
GeneratedFiles.prototype.getFile = function (path) {
return this._files[path];
};
GeneratedFiles.prototype.getFilePaths = function () {
return Object.keys(this._files);
};
GeneratedFiles.prototype.remove = function (path) {
delete this._files[path];
delete this._data[path];
};
GeneratedFiles.prototype.save = async function (artifactName) {
const artifact = this.blobClient.createArtifact(artifactName);
// Transfer the data files to the blob and create an artifact
const userAssets = this.getUserAssets();
if (userAssets.length) {
const objectHashes = {};
for (let i = userAssets.length; i--;) {
const [filepath, dataInfo] = userAssets[i];
const contents = await Storage.getFile(dataInfo);
const filename = filepath.split('/').pop();
const hash = await this.blobClient.putFile(filename, contents);
objectHashes[filepath] = hash;
}
await artifact.addObjectHashes(objectHashes);
}
await artifact.addFiles(this._files);
return await artifact.save();
};
return GeneratedFiles;
});
|
JavaScript
| 0 |
@@ -2348,16 +2348,27 @@
addFiles
+AsSoftLinks
(this._f
|
4ceeacb98813c38ad50f9a77948026bffa5426f3
|
load more filtered posts
|
src/component/homePage/component.js
|
src/component/homePage/component.js
|
import React from 'react'
import style from './style.css'
import { HorizontalPostList } from '../horizontalPostList'
import { VerticalPostList } from '../verticalPostList'
import type { Post as Post_type } from '../../../type'
import { primaryTags } from '../../reducer/selectedTag'
import { memoize } from '../../util/memoize'
export type Props = {
selectedTag: string,
posts: Array<Post_type>,
goToPost: () => *,
selectTag: (tag: string) => *,
loadMorePosts: (tag: string) => *,
device: 'palm' | 'desktop',
}
const createSelectTagHandler = memoize((selectTag, tag) => () =>
selectTag && selectTag(tag))
const createLoadMorePostsHandler = memoize((loadMorePosts, tag) => () =>
loadMorePosts && loadMorePosts(tag))
export const HomePage = ({
posts,
loadMorePosts,
selectedTag,
goToPost,
selectTag,
device,
}: Props) => (
<div className={style.container}>
{!selectedTag &&
<div className={style.section}>
<div
className={style.sectionLabel}
onClick={createSelectTagHandler(selectTag, 'world')}
>
World
</div>
<HorizontalPostList
goToPost={goToPost}
loadMorePosts={createLoadMorePostsHandler(
loadMorePosts,
'world'
)}
posts={posts.filter(({ tags }) => tags.includes('world'))}
/>
</div>}
{!selectedTag &&
<div className={style.section}>
<div
className={style.sectionLabel}
onClick={createSelectTagHandler(selectTag, 'essential')}
>
Essentials
</div>
<HorizontalPostList
goToPost={goToPost}
loadMorePosts={createLoadMorePostsHandler(
loadMorePosts,
'essential'
)}
posts={posts.filter(({ tags }) =>
tags.includes('essential')
)}
/>
</div>}
<div className={style.section}>
<div
className={style.sectionLabel}
onClick={
!selectedTag && createSelectTagHandler(selectTag, 'update')
}
>
{selectedTag
? (primaryTags.includes(selectedTag) ? '' : '#') +
selectedTag
: 'updates'}
</div>
<VerticalPostList
goToPost={goToPost}
loadMorePosts={
primaryTags.includes(selectedTag || 'update') &&
createLoadMorePostsHandler(
loadMorePosts,
selectedTag || 'update'
)
}
posts={posts.filter(({ tags }) =>
tags.includes(selectedTag || 'update')
)}
/>
</div>
</div>
)
|
JavaScript
| 0 |
@@ -2776,77 +2776,35 @@
ts=%7B
-%0A primaryTags.includes(selectedTag %7C%7C 'update') &&
+createLoadMorePostsHandler(
%0A
@@ -2824,19 +2824,9 @@
- createL
+l
oadM
@@ -2829,32 +2829,25 @@
oadMorePosts
-Handler(
+,
%0A
@@ -2859,34 +2859,54 @@
- loadMorePosts,%0A
+primaryTags.includes(selectedTag %7C%7C 'update')%0A
@@ -2917,32 +2917,33 @@
+?
selectedTag %7C%7C
@@ -2975,17 +2975,23 @@
-)
+: 'all'
%0A
@@ -2991,32 +2991,33 @@
+)
%7D%0A
|
a267be1670f955b776a49e2ad8cca531f40fb53e
|
update navigationBar hover opacity
|
src/components/App/NavigationBar.js
|
src/components/App/NavigationBar.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Radium from 'radium';
import {getFontSize} from '../../styles/typography';
import {pageShape} from '../../CatalogPropTypes';
import Link from '../Link/Link';
// The vertical and horizontal padding inside the left/right nav
// link element.
const verticalPadding = 28;
const horizontalPadding = 21;
function getStyles(theme) {
return {
navbar: {
width: '100%',
backgroundColor: theme.navBarBackground
},
navlink: {
boxSizing: 'border-box',
display: 'inline-block',
verticalAlign: 'top',
width: '50%',
transition: '.2s opacity',
':hover': {
opacity: 0.9
}
},
leftNavLink: {
padding: `${verticalPadding}px 0 ${verticalPadding}px ${horizontalPadding}px`,
textAlign: 'left',
'@media (min-width: 1000px)': {
padding: `${verticalPadding}px 0 ${verticalPadding}px ${horizontalPadding * 2}px`
}
},
rightNavLink: {
padding: `${verticalPadding}px ${horizontalPadding}px ${verticalPadding}px 0`,
textAlign: 'right',
borderLeft: `1px solid ${theme.background}`,
'@media (min-width: 1000px)': {
padding: `${verticalPadding}px ${horizontalPadding * 2}px ${verticalPadding}px 0`
}
},
link: {
color: theme.navBarTextColor,
display: 'block',
fontFamily: theme.fontFamily,
textDecoration: 'none'
},
leftLinkIcon: {
display: 'none',
margin: '0 24px 0 0',
verticalAlign: 'middle',
'@media (min-width: 1000px)': {
display: 'inline'
}
},
rightLinkIcon: {
display: 'none',
margin: '0 0 0 24px',
verticalAlign: 'middle',
'@media (min-width: 1000px)': {
display: 'inline'
}
},
linkIconPath: {
stroke: 'none',
fill: theme.navBarTextColor
},
linklabels: {
display: 'block',
verticalAlign: 'middle',
'@media (min-width: 1000px)': {
display: 'inline-block'
}
},
linkSuperTitle: {
fontSize: getFontSize(theme, 0),
margin: 0,
fontWeight: 400
},
linkTitle: {
fontSize: getFontSize(theme, 1),
margin: 0,
fontWeight: 400
}
};
}
class NavigationBar extends React.Component {
render() {
const {nextPage, previousPage, theme} = this.props;
const styles = getStyles(theme);
const leftIcon = (
<svg style={styles.leftLinkIcon} width='37px' height='26px' viewBox='0 0 37 26'>
<path style={styles.linkIconPath} d='M12.2925,0.2925 C12.6845,-0.0975 13.3165,-0.0975 13.7085,0.2925 C14.0985,0.6845 14.0985,1.3165 13.7085,1.7085 L3.4145,12.0005 L36.0005,12.0005 C36.5525,12.0005 37.0005,12.4485 37.0005,13.0005 C37.0005,13.5525 36.5525,14.0005 36.0005,14.0005 L3.4145,14.0005 L13.7085,24.2925 C14.0985,24.6845 14.0985,25.3165 13.7085,25.7085 C13.5125,25.9025 13.2565,26.0005 13.0005,26.0005 C12.7445,26.0005 12.4885,25.9025 12.2925,25.7085 L0.2925,13.7085 C-0.0975,13.3165 -0.0975,12.6845 0.2925,12.2925 L12.2925,0.2925 Z'></path>
</svg>
);
const rightIcon = (
<svg style={styles.rightLinkIcon} width='37px' height='26px' viewBox='0 0 37 26'>
<path style={styles.linkIconPath} d='M24.708,0.2925 C24.316,-0.0975 23.684,-0.0975 23.292,0.2925 C22.902,0.6845 22.902,1.3165 23.292,1.7085 L33.586,12.0005 L1,12.0005 C0.448,12.0005 0,12.4485 0,13.0005 C0,13.5525 0.448,14.0005 1,14.0005 L33.586,14.0005 L23.292,24.2925 C22.902,24.6845 22.902,25.3165 23.292,25.7085 C23.488,25.9025 23.744,26.0005 24,26.0005 C24.256,26.0005 24.512,25.9025 24.708,25.7085 L36.708,13.7085 C37.098,13.3165 37.098,12.6845 36.708,12.2925 L24.708,0.2925 Z'></path>
</svg>
);
return (
<div style={styles.navbar}>
<div style={styles.navlink} key='left'>{
previousPage &&
<Link to={previousPage.path} style={{...styles.link, ...styles.leftNavLink}}>
{ leftIcon }
<div style={styles.linklabels}>
<h4 style={styles.linkSuperTitle}>{ previousPage.superTitle }</h4>
<h3 style={styles.linkTitle}>{ previousPage.title }</h3>
</div>
</Link>
}</div>
<div style={styles.navlink} key='right'>{
nextPage &&
<Link to={nextPage.path} style={{...styles.link, ...styles.rightNavLink}}>
<div style={styles.linklabels}>
<h4 style={styles.linkSuperTitle}>{ nextPage.superTitle }</h4>
<h3 style={styles.linkTitle}>{ nextPage.title }</h3>
</div>
{ rightIcon }
</Link>
}</div>
</div>
);
}
}
NavigationBar.propTypes = {
theme: PropTypes.object.isRequired,
nextPage: pageShape,
previousPage: pageShape
};
export default Radium(NavigationBar);
|
JavaScript
| 0 |
@@ -686,17 +686,19 @@
city: 0.
-9
+65;
%0A %7D
|
4583144ae08f4ee78fc59b4ee2e9ce1c9db153ce
|
use once where possible.
|
lib/zip-stream.js
|
lib/zip-stream.js
|
/**
* node-zip-stream
*
* Copyright (c) 2014 Chris Talkington, contributors.
* Licensed under the MIT license.
* https://github.com/ctalkington/node-zip-stream/blob/master/LICENSE-MIT
*/
var inherits = require('util').inherits;
var Transform = require('stream').Transform || require('readable-stream').Transform;
var PassThrough = require('stream').PassThrough || require('readable-stream').PassThrough;
var ChecksumStream = require('./util/ChecksumStream');
var DeflateRawChecksum = require('./util/DeflateRawChecksum');
var headers = require('./headers');
var util = require('./util');
var ZipStream = module.exports = function(options) {
if (!(this instanceof ZipStream)) {
return new ZipStream(opts);
}
options = this.options = util.defaults(options, {
comment: '',
forceUTC: false
});
if (typeof options.zlib !== 'object') {
options.zlib = {};
}
if (typeof options.level === 'number' && options.level >= 0) {
options.zlib.level = options.level;
delete options.level;
} else if (typeof options.zlib.level !== 'number') {
options.zlib.level = 1;
}
Transform.call(this, options);
this.offset = 0;
this.files = [];
this._finalize = false;
this._finalized = false;
this._processing = false;
};
inherits(ZipStream, Transform);
ZipStream.prototype._afterAppend = function(file) {
this.files.push(file);
this._processing = false;
if (this._finalize) {
this.finalize();
}
};
ZipStream.prototype._appendBuffer = function(source, data, callback) {
var self = this;
var file = data;
file.offset = self.offset;
self.write(headers.encode('file', file));
function onend() {
self.write(headers.encode('fileDescriptor', file));
self._afterAppend(file);
callback(null);
}
if (file.store) {
file.uncompressedSize = source.length;
file.compressedSize = file.uncompressedSize;
file.crc32 = util.crc32(source).digest();
self.write(source);
onend();
} else {
var processStream = self._newProcessStream(file.store);
processStream.on('error', callback);
processStream.on('end', function() {
file.crc32 = processStream.digest;
file.uncompressedSize = processStream.rawSize;
file.compressedSize = processStream.compressedSize || processStream.rawSize;
onend();
});
processStream.pipe(self, { end: false });
processStream.end(source);
}
};
ZipStream.prototype._appendStream = function(source, data, callback) {
var self = this;
var file = data;
file.offset = self.offset;
self.write(headers.encode('file', file));
function onend() {
self.write(headers.encode('fileDescriptor', file));
self._afterAppend(file);
callback(null);
}
var processStream = self._newProcessStream(file.store);
processStream.on('error', callback);
processStream.on('end', function() {
file.crc32 = processStream.digest;
file.uncompressedSize = processStream.rawSize;
file.compressedSize = processStream.compressedSize || processStream.rawSize;
onend();
});
processStream.pipe(self, { end: false });
source.pipe(processStream);
};
ZipStream.prototype._emitErrorCallback = function(err, data) {
if (err) {
this.emit('error', err);
}
};
ZipStream.prototype._newProcessStream = function(store) {
var process;
if (store) {
process = new ChecksumStream();
} else {
process = new DeflateRawChecksum(this.options.zlib);
}
return process;
};
ZipStream.prototype._normalizeFileData = function(data) {
data = util.defaults(data, {
type: 'file',
name: '',
date: null,
store: false,
comment: ''
});
data.name = util.sanitizePath(data.name);
if (typeof data.lastModifiedDate !== 'number') {
data.lastModifiedDate = util.dosDateTime(data.date, this.options.forceUTC);
}
if (this.options.zlib && this.options.zlib.level === 0) {
data.store = true;
}
data.flags = (1 << 3);
data.compressionMethod = data.store ? 0 : 8;
data.uncompressedSize = 0;
data.compressedSize = 0;
return data;
};
ZipStream.prototype._normalizeSource = function(source) {
if (typeof source === 'string') {
return new Buffer(source);
} else if (util.isStream(source) && !source._readableState) {
var normalized = new PassThrough();
source.pipe(normalized);
return normalized;
}
return source;
};
ZipStream.prototype._transform = function(chunk, encoding, callback) {
callback(null, chunk);
};
ZipStream.prototype._writeCentralDirectory = function() {
var files = this.files;
var comment = this.options.comment;
var cdoffset = this.offset;
var cdsize = 0;
var centralDirectoryBuffer;
for (var i = 0; i < files.length; i++) {
var file = files[i];
centralDirectoryBuffer = headers.encode('centralDirectory', file);
this.write(centralDirectoryBuffer);
cdsize += centralDirectoryBuffer.length;
}
var centralDirectoryFooterData = {
directoryRecordsDisk: files.length,
directoryRecords: files.length,
centralDirectorySize: cdsize,
centralDirectoryOffset: cdoffset,
comment: comment
};
this.write(headers.encode('centralFooter', centralDirectoryFooterData));
};
ZipStream.prototype.entry = function(source, data, callback) {
if (typeof callback !== 'function') {
callback = this._emitErrorCallback.bind(this);
}
if (this._processing) {
callback(new Error('already processing an entry'));
return;
}
if (this._finalize || this._finalized) {
callback(new Error('entry after finalize()'));
return;
}
data = this._normalizeFileData(data);
if (data.type !== 'file') {
callback(new Error('only "file" entries are currently supported'));
return;
}
if (typeof data.name !== 'string' || data.name.length === 0) {
callback(new Error('filename must be a non-empty string value'));
return;
}
this._processing = true;
source = this._normalizeSource(source);
if (Buffer.isBuffer(source)) {
this._appendBuffer(source, data, callback);
} else if (util.isStream(source)) {
this._appendStream(source, data, callback);
} else {
this._processing = false;
callback(new Error('input source must be valid Stream or Buffer instance'));
return;
}
};
ZipStream.prototype.finalize = function() {
if (this._processing) {
this._finalize = true;
return;
}
this._writeCentralDirectory();
this._finalized = true;
this.end();
};
ZipStream.prototype.write = function(chunk, cb) {
if (chunk) {
this.offset += chunk.length;
}
return Transform.prototype.write.call(this, chunk, cb);
};
|
JavaScript
| 0 |
@@ -2049,32 +2049,34 @@
processStream.on
+ce
('error', callba
@@ -2093,32 +2093,34 @@
processStream.on
+ce
('end', function
@@ -2806,16 +2806,18 @@
tream.on
+ce
('error'
@@ -2848,16 +2848,18 @@
tream.on
+ce
('end',
|
fbb0af8d4b8683026a814a55a6c27522c8b416e5
|
Update telegram-parse-spec.js
|
spec/telegram/telegram-parse-spec.js
|
spec/telegram/telegram-parse-spec.js
|
/*global describe, it, expect, require */
'use strict';
var parse = require('../../lib/telegram/parse');
describe('Telegram parse', () => {
it('returns nothing if the format is invalid', () => {
expect(parse('string')).toBeUndefined();
expect(parse()).toBeUndefined();
expect(parse(false)).toBeUndefined();
expect(parse(123)).toBeUndefined();
expect(parse({})).toBeUndefined();
expect(parse([1, 2, 3])).toBeUndefined();
});
it('returns false the chat id are missing', () => {
expect(parse({message: {chat: 'some123ChatId', text: 'ello Telegram'}})).toBeUndefined();
expect(parse({message: {text: 'pete'}})).toBeUndefined();
});
it('returns a parsed object when chat id is present', () => {
var msg = {message: {chat: {id: 'some123ChatId'}, text: 'ello Telegram' }};
expect(parse(msg)).toEqual({ sender: 'some123ChatId', text: 'ello Telegram', originalRequest: msg, type: 'telegram'});
});
it('returns a parsed object when messageObject contains a callback_query', () => {
var msg = {callback_query: {message: {chat: {id: 'some123ChatId'}},data: 'someCallbackData'}};
expect(parse(msg)).toEqual({ sender: 'some123ChatId', text: 'someCallbackData', originalRequest: msg, type: 'telegram'});
});
it('sender field should be equal to actual user_id', () => {
var msg = {
update_id: 920742096,
inline_query: {
id: '512944664604439953',
from: {
id: 119429236,
first_name: 'Sergey',
last_name: 'Tverskikh',
username: 'tverskih'
},
query: 'share',
offset: ''
}
};
expect(parse(msg)).toEqual({
sender: 119429236,
text: 'share',
originalRequest: {
update_id: 920742096,
inline_query: {
id: '512944664604439953',
from: {
id: 119429236,
first_name: 'Sergey',
last_name: 'Tverskikh',
username: 'tverskih'
},
query: 'share',
offset: ''
}
},
type: 'telegram'
});
});
});
|
JavaScript
| 0.000001 |
@@ -1727,325 +1727,11 @@
st:
-%7B%0A update_id: 920742096,%0A inline_query: %7B%0A id: '512944664604439953',%0A from: %7B%0A id: 119429236,%0A first_name: 'Sergey',%0A last_name: 'Tverskikh',%0A username: 'tverskih'%0A %7D,%0A query: 'share',%0A offset: ''%0A %7D%0A %7D
+msg
,%0A
|
aeb2e601cf33965c745ccdc0dd75529929f455d1
|
fix style
|
src/components/Login/Signup.spec.js
|
src/components/Login/Signup.spec.js
|
import Signup from './Signup'
import { QCheckbox } from 'quasar'
import { mountWithDefaults, statusMocks } from '>/helpers'
const userData = {
displayName: 'my name',
email: '[email protected]',
password: 'secret',
}
describe('Signup', () => {
it('submits', () => {
let wrapper = mountWithDefaults(Signup, {
propsData: {
status: statusMocks.default(),
prefillEmail: () => '',
hasPlayground: true,
hasGroupToJoin: false,
},
})
Object.assign(wrapper.vm.user, userData)
const checkboxes = wrapper.findAll(QCheckbox)
expect(checkboxes.length).toBe(1)
expect(wrapper.vm.joinPlayground).toEqual(true)
wrapper.vm.submit()
expect(wrapper.emitted().submit).toBeTruthy()
expect(wrapper.emitted().submit[0][0]).toEqual({
joinPlayground: true,
userData,
})
})
it('submits without playground', () => {
let wrapper = mountWithDefaults(Signup, {
propsData: {
status: statusMocks.default(),
prefillEmail: () => '',
hasPlayground: false,
hasGroupToJoin: false,
},
})
Object.assign(wrapper.vm.user, userData)
const checkboxes = wrapper.findAll(QCheckbox)
expect(checkboxes.length).toBe(0)
wrapper.vm.submit()
expect(wrapper.emitted().submit).toBeTruthy()
expect(wrapper.emitted().submit[0][0]).toEqual({
joinPlayground: false,
userData,
})
})
it('submits with chosen group', () => {
let wrapper = mountWithDefaults(Signup, {
propsData: {
status: statusMocks.default(),
prefillEmail: () => '',
hasPlayground: false,
hasGroupToJoin: true,
},
})
Object.assign(wrapper.vm.user, userData)
const checkboxes = wrapper.findAll(QCheckbox)
expect(checkboxes.length).toBe(0)
wrapper.vm.submit()
expect(wrapper.emitted().submit).toBeTruthy()
expect(wrapper.emitted().submit[0][0]).toEqual({
joinPlayground: false,
userData,
})
})
it('deselects playground', () => {
let wrapper = mountWithDefaults(Signup, {
propsData: {
status: statusMocks.default(),
prefillEmail: () => '',
hasPlayground: true,
hasGroupToJoin: false,
},
})
Object.assign(wrapper.vm.user, userData)
const checkboxes = wrapper.findAll(QCheckbox)
expect(checkboxes.length).toBe(1)
expect(wrapper.vm.joinPlayground).toEqual(true)
checkboxes.at(0).trigger('click')
expect(wrapper.vm.joinPlayground).toEqual(false)
wrapper.vm.submit()
expect(wrapper.emitted().submit).toBeTruthy()
expect(wrapper.emitted().submit[0][0]).toEqual({
joinPlayground: false,
userData,
})
})
})
|
JavaScript
| 0.000001 |
@@ -2707,12 +2707,11 @@
%7D)%0A %7D)%0A
-%0A
%7D)%0A
|
b64aafcd9ba265f3c8a115feeadcdbbfa9c8a919
|
add trailing slash to link
|
webapps/ui/cockpit/src/components/Header/UserInformation.js
|
webapps/ui/cockpit/src/components/Header/UserInformation.js
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from "react";
import { withRouter } from "react-router-dom";
import { post } from "utils/request";
import translate from "utils/translation";
import pathUtil from "utils/paths";
import { Dropdown } from "components";
import "./UserInformation.scss";
import SmallScreenSwitch from "./SmallScreenSwitch";
function UserInformation({ user, history }) {
const profile = user.profile;
function logout() {
post("%ADMIN_API%/auth/user/%ENGINE%/logout").then(() => {
history.push("/login");
});
}
return (
<div className="UserInformation">
<Dropdown
title={
<button className="user">
<span className="glyphicon glyphicon-user" />
<SmallScreenSwitch>
<span className="userName">
{profile
? `${profile.firstName} ${profile.lastName}`
: user.userId}
</span>
</SmallScreenSwitch>
</button>
}
position="right"
>
<Dropdown.Option>
<a href={`../../welcome/${pathUtil("engine")}`}>
{translate("MY_PROFILE")}
</a>
</Dropdown.Option>
<Dropdown.Divider />
<Dropdown.Option onClick={logout}>
{translate("SIGN_OUT_ACTION")}
</Dropdown.Option>
</Dropdown>
</div>
);
}
export default withRouter(UserInformation);
|
JavaScript
| 0 |
@@ -1898,16 +1898,17 @@
ngine%22)%7D
+/
%60%7D%3E%0A
|
7f137795f774f8e86071ecdbd00a8bb51f128121
|
Make opacity an attribute
|
favcount.js
|
favcount.js
|
/*
* favcount.js v1.1.0
* http://chrishunt.co/favcount
* Dynamically updates the favicon with a number.
*
* Copyright 2013, Chris Hunt
* Released under the MIT license
*/
(function(){
function Favcount(icon) {
this.icon = icon;
this.canvas = document.createElement('canvas');
}
Favcount.prototype.set = function(count) {
var self = this,
img = document.createElement('img');
if (self.canvas.getContext) {
img.onload = function() {
drawCanvas(self.canvas, img, normalize(count));
};
img.src = this.icon;
}
}
function normalize(count) {
count = Math.round(count);
if (isNaN(count) || count < 1) {
return '';
} else if (count < 10) {
return ' ' + count;
} else if (count > 99) {
return '99';
} else {
return count;
}
}
function drawCanvas(canvas, img, count) {
var head = document.getElementsByTagName('head')[0],
favicon = document.createElement('link'),
multiplier, fontSize, context, xOffset, yOffset, border, shadow;
favicon.rel = 'icon';
// Scale canvas elements based on favicon size
multiplier = img.width / 16;
fontSize = multiplier * 11;
xOffset = multiplier;
yOffset = multiplier * 11;
border = multiplier;
shadow = multiplier * 2;
canvas.height = canvas.width = img.width;
context = canvas.getContext('2d');
context.font = 'bold ' + fontSize + 'px "helvetica", sans-serif';
// Draw faded favicon background
if (count) { context.globalAlpha = 0.4; }
context.drawImage(img, 0, 0);
context.globalAlpha = 1.0;
// Draw white drop shadow
context.shadowColor = '#FFF';
context.shadowBlur = shadow;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
// Draw white border
context.fillStyle = '#FFF';
context.fillText(count, xOffset, yOffset);
context.fillText(count, xOffset + border, yOffset);
context.fillText(count, xOffset, yOffset + border);
context.fillText(count, xOffset + border, yOffset + border);
// Draw black count
context.fillStyle = '#000';
context.fillText(count,
xOffset + (border / 2.0),
yOffset + (border / 2.0)
);
// Replace favicon with new favicon
favicon.href = canvas.toDataURL('image/png');
head.removeChild(document.querySelector('link[rel=icon]'));
head.appendChild(favicon);
}
this.Favcount = Favcount;
}).call(this);
(function(){
Favcount.VERSION = '1.1.0';
}).call(this);
|
JavaScript
| 0.000151 |
@@ -231,24 +231,48 @@
con = icon;%0A
+ this.opacity = 0.4;%0A
this.can
@@ -522,24 +522,38 @@
self.canvas,
+ self.opacity,
img, normal
@@ -905,16 +905,25 @@
(canvas,
+ opacity,
img, co
@@ -1613,19 +1613,23 @@
Alpha =
-0.4
+opacity
; %7D%0A
|
84ca138bbecfa677c2b86317451dad0d17de718e
|
Update contact_me.js
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
});
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "//formspree.io/[email protected]",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
dataType: "json",
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
ga('send','event','button', 'message_sent');
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0 |
@@ -1344,12 +1344,13 @@
.io/
-info
+mlake
@all
@@ -3333,12 +3333,13 @@
tml('');%0A%7D);
+%0A
|
8d007ab499f6b5dc327aeb96dc10c968037b1a3f
|
Add semi-colon
|
src/Modal/__tests__/Modal-test.js
|
src/Modal/__tests__/Modal-test.js
|
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
jest.dontMock('../Modal');
jest.dontMock('../../Util/Util');
var Modal = require('../Modal');
var DEFAULT_CLASSES = require('../DefaultModalClasses');
describe('Modal', function () {
describe('#addDefaultClasses', function () {
beforeEach(function () {
this.classProps = Object.keys(DEFAULT_CLASSES);
});
describe('no user added classes', function () {
it('should add default classes if user does not add any', function () {
var instance = TestUtils.renderIntoDocument(
<Modal open={true} />
);
var mergedClasses = instance.addDefaultClasses(instance.props);
this.classProps.forEach(function (classProp) {
expect(mergedClasses[classProp]).toEqual(DEFAULT_CLASSES[classProp]);
});
});
})
describe('user adds classes', function () {
it('should combine user added classes with the default', function () {
var props = {
open: true
};
// Simulate a user adding their own personal class onto the props.
this.classProps.forEach(function (classProp) {
props[classProp] = 'user-added-class';
});
var instance = TestUtils.renderIntoDocument(
<Modal {...props} />
);
var mergedClasses = instance.addDefaultClasses(instance.props);
// Test if default and user added classes combined.
this.classProps.forEach(function (classProp) {
var defaultClass = DEFAULT_CLASSES[classProp];
var userAdded = props[classProp];
expect(mergedClasses[classProp]).toEqual(defaultClass + ' ' + userAdded);
});
});
});
});
});
|
JavaScript
| 0.999999 |
@@ -858,16 +858,17 @@
;%0A %7D)
+;
%0A%0A de
|
2e0a5a1c197b3a0d45e38fc53646c9f90be211ac
|
Refactor TodoList into a function
|
src/components/TodoList/TodoList.js
|
src/components/TodoList/TodoList.js
|
import React from 'react'
import Todo from 'components/Todo/Todo'
const TodoList = ({todos, onCompleted, onDelete, onDeleteButtonVisibilityChanged, deleteButtonOnTodo}) => {
const todosComponents = this.props.todos.map(todo => (
<Todo todo={todo}
onCompleted={this.props.onCompleted}
onDelete={this.props.onDelete}
key={todo.id}
onDeleteButtonVisibilityChanged={this.props.onDeleteButtonVisibilityChanged}
deleteButtonVisible={todo.id === this.props.deleteButtonOnTodo}
/>
)
)
return (
<table className='todo-list todo-table'>
<tbody>
{ todosComponents }
</tbody>
</table>
)
}
export default TodoList
|
JavaScript
| 0.999007 |
@@ -171,47 +171,81 @@
=%3E
-%7B%0A const todosComponents = this.props.
+(%0A %3Ctable className='todo-list todo-table'%3E%0A %3Ctbody%3E%0A %7B%0A
todo
@@ -260,18 +260,16 @@
do =%3E (%0A
-
@@ -340,18 +340,16 @@
-
onComple
@@ -353,27 +353,16 @@
pleted=%7B
-this.props.
onComple
@@ -392,34 +392,32 @@
-
onDelete=%7Bthis.p
@@ -410,27 +410,16 @@
Delete=%7B
-this.props.
onDelete
@@ -420,18 +420,16 @@
Delete%7D%0A
-
@@ -494,34 +494,32 @@
-
onDeleteButtonVi
@@ -535,27 +535,16 @@
hanged=%7B
-this.props.
onDelete
@@ -564,26 +564,24 @@
ityChanged%7D%0A
-
@@ -639,19 +639,8 @@
===
-this.props.
dele
@@ -651,26 +651,24 @@
ttonOnTodo%7D%0A
-
@@ -714,120 +714,32 @@
-
)%0A
-)%0A return (%0A %3Ctable className='todo-list todo-table'%3E%0A %3Ctbody%3E%0A %7B todosComponents
+ )%0A
%7D%0A
-
%3C/tb
@@ -745,18 +745,16 @@
body%3E%0A
-
%3C/table%3E
@@ -758,13 +758,9 @@
le%3E%0A
- )%0A%7D
+)
%0A%0Aex
|
e57cd5218da551f420cc7c11236725828b8a70ce
|
Add user.displayName to missing manager message
|
src/force-directed-graph-renderer.js
|
src/force-directed-graph-renderer.js
|
import d3 from 'd3';
export default class ForceDirectedGraphRenderer {
renderSvg(containerElement, users) {
const width = 1200;
const height = 700;
const radius = 15;
const color = d3.scale.category20();
const vis = d3
.select(containerElement)
.append('svg')
.attr('width', width)
.attr('height', height);
const links = users
.filter(user => {
if (!user.manager) {
return false;
}
const manager = users.find(x => x.id === user.manager.id);
if (!manager) {
console.log(`Missing manager for ${user.id} in data.`); // eslint-disable-line no-console
}
return !!manager;
})
.map((user, index) => {
const managerIndex = users.find(x => x.id === user.manager.id);
if (!managerIndex && managerIndex !== 0) {
throw new Error(`managerIndex could be not found for user.manager.id: '${user.manager.id}'.`);
}
return {
source: index,
target: managerIndex,
value: 1
};
});
const link = vis.selectAll('line')
.data(links)
.enter().append('line');
const node = vis.selectAll('.node')
.data(users)
.enter().append('g')
.attr('class', 'node');
node.append('circle')
.attr('r', radius)
.style('fill', d => color(d.department));
node.append('text')
.attr('text-anchor', 'middle')
.text(x => this.getNameAbbreviation(x.displayName));
node.append('title')
.text(x => `${x.displayName} (${x.department})`);
const force = d3.layout.force()
.nodes(users)
.links(links)
.size([width, height])
.linkDistance(30)
.charge(-400)
.gravity(0.3)
.start();
node.call(force.drag);
force.on('tick', () => {
link.attr('x1', d => d.source.x)
.attr('y1', d => d.source.y)
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
d3.selectAll('circle')
.attr('cx', d => Math.max(radius, Math.min(width - radius, d.x)))
.attr('cy', d => Math.max(radius, Math.min(height - radius, d.y)));
d3.selectAll('text')
// TODO: Fix labels at svg edges
.attr('x', d => d.x)
.attr('y', d => d.y + 5);
});
}
getNameAbbreviation(displayName) {
const split = displayName.split(' ');
if (split.length > 0) {
const givenName = split[0];
const surName = split[1];
const firstLetter = givenName ? givenName[0] : '?';
const secondLetter = surName ? surName[0] : '';
return `${firstLetter}${secondLetter}`;
}
}
}
|
JavaScript
| 0.000002 |
@@ -597,16 +597,37 @@
ger for
+$%7Buser.displayName%7D (
$%7Buser.i
@@ -628,16 +628,17 @@
user.id%7D
+)
in data
|
82c6a74c4520697d0f86d3f3a5ea054f83590c97
|
Revert back to original working state
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
// url: "http://jparseghian-contact-form.herokuapp.com/send_email",
url: "https://www.google.com/recaptcha/api/siteverify",
type: "POST",
data: {
secret: "6LdemwkTAAAAAL-qNOBazx8zJrEYesUKSpKLNcaG",
response: window.grecaptcha.getResponse()
},
// data: {
// name: name,
// phone: phone,
// email: email,
// message: message
// },
// cache: false,
success: function(response) {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
console.log("success", response);
},
error: function(error) {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
console.log("error", error);
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0.000001 |
@@ -855,19 +855,16 @@
- //
url: %22h
@@ -941,316 +941,61 @@
-url: %22https://www.google.com/recaptcha/api/siteverify%22,%0A type: %22POST%22,%0A data: %7B%0A secret: %226LdemwkTAAAAAL-qNOBazx8zJrEYesUKSpKLNcaG%22,%0A response: window.grecaptcha.getResponse()%0A %7D,%0A // data: %7B%0A //
+type: %22POST%22,%0A data: %7B%0A
@@ -1018,27 +1018,24 @@
- //
phone:
@@ -1052,27 +1052,24 @@
- //
email:
@@ -1090,19 +1090,16 @@
- //
mes
@@ -1127,19 +1127,16 @@
- //
%7D,%0A
@@ -1146,19 +1146,16 @@
- //
cache:
@@ -1195,24 +1195,16 @@
unction(
-response
) %7B%0A
@@ -1831,62 +1831,8 @@
%22);%0A
- console.log(%22success%22, response);%0A
@@ -1878,21 +1878,16 @@
unction(
-error
) %7B%0A
@@ -2515,57 +2515,8 @@
%22);%0A
- console.log(%22error%22, error);%0A
|
2d7f2becd734418ad2b6a83b98ade0e3fa3146a7
|
Remove misleading comment. (#10190)
|
lib/rules/no-return-await.js
|
lib/rules/no-return-await.js
|
/**
* @fileoverview Disallows unnecessary `return await`
* @author Jordan Harband
*/
"use strict";
const astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const message = "Redundant use of `await` on a return value.";
module.exports = {
meta: {
docs: {
description: "disallow unnecessary `return await`",
category: "Best Practices",
// TODO: set to true
recommended: false,
url: "https://eslint.org/docs/rules/no-return-await"
},
fixable: null,
schema: [
]
},
create(context) {
/**
* Reports a found unnecessary `await` expression.
* @param {ASTNode} node The node representing the `await` expression to report
* @returns {void}
*/
function reportUnnecessaryAwait(node) {
context.report({
node: context.getSourceCode().getFirstToken(node),
loc: node.loc,
message
});
}
/**
* Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting
* this function. For example, a statement in a `try` block will always have an error handler. A statement in
* a `catch` block will only have an error handler if there is also a `finally` block.
* @param {ASTNode} node A node representing a location where an could be thrown
* @returns {boolean} `true` if a thrown error will be caught/handled in this function
*/
function hasErrorHandler(node) {
let ancestor = node;
while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") {
if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) {
return true;
}
ancestor = ancestor.parent;
}
return false;
}
/**
* Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression,
* an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position.
* @param {ASTNode} node A node representing the `await` expression to check
* @returns {boolean} The checking result
*/
function isInTailCallPosition(node) {
if (node.parent.type === "ArrowFunctionExpression") {
return true;
}
if (node.parent.type === "ReturnStatement") {
return !hasErrorHandler(node.parent);
}
if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) {
return isInTailCallPosition(node.parent);
}
if (node.parent.type === "LogicalExpression" && node === node.parent.right) {
return isInTailCallPosition(node.parent);
}
if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) {
return isInTailCallPosition(node.parent);
}
return false;
}
return {
AwaitExpression(node) {
if (isInTailCallPosition(node) && !hasErrorHandler(node)) {
reportUnnecessaryAwait(node);
}
}
};
}
};
|
JavaScript
| 0 |
@@ -541,41 +541,8 @@
%22,%0A%0A
- // TODO: set to true%0A
|
2927982500aac5e8b6c37479a6f6bef4fa4bdb97
|
Fix lights transforms.
|
src/framework/core/LightComponent.js
|
src/framework/core/LightComponent.js
|
import * as THREE from 'three';
import {$wrap, $define, $extend, $defaults} from '../utils/ComponentUtils';
import {loadMaterial, extend} from '../utils/index';
function LightComponent(targetComponent) {
const resultComponent = class LightComponentEnhance extends targetComponent {
static defaults = extend(targetComponent.defaults, {
light: {
color: 0xffffff,
skyColor: 0xffffff,
groundColor: 0xffffff,
intensity: 1,
distance: 100,
angle: Math.PI / 3,
exponent: 0,
decay: 1
},
helper: false,
shadowmap: {
cast: true,
bias: 0,
radius: 1,
width: 1024,
height: 1024,
near: true,
far: 400,
fov: 60,
top: 200,
bottom: -200,
left: -200,
right: 200
},
position: {x: 0, y: 0, z: 0},
rotation: {x: 0, y: 0, z: 0},
target: {x: 0, y: 0, z: 0}
});
wrapShadow() {
return new Promise(resolve => {
const _native = this.native,
_shadow = this.params.shadowmap;
_native.castShadow = _shadow.cast;
_native.shadow.mapSize.width = _shadow.width;
_native.shadow.mapSize.height = _shadow.height;
_native.shadow.bias = _shadow.bias;
_native.shadow.radius = _shadow.radius;
const _shadowCamera = _native.shadow.camera;
_shadowCamera.near = _shadow.near;
_shadowCamera.far = _shadow.far;
_shadowCamera.fov = _shadow.fov;
_shadowCamera.left = _shadow.left;
_shadowCamera.right = _shadow.right;
_shadowCamera.top = _shadow.top;
_shadowCamera.bottom = _shadow.bottom;
resolve(this);
});
}
wrapTransforms() {
const _params = this.params;
/*
this.position.set(
_params.position.x,
_params.position.y,
_params.position.z
);
this.rotation.set(
_params.rotation.x,
_params.rotation.y,
_params.rotation.z
);*/
if (this.target) this.target = _params.target;
}
copy(source) {
if (source.native) {
this.native = source.native.clone();
this.params = Object.assign({}, source.params);
if (source.helper) this.helper = source.helper.clone();
if (source.target) this.target = source.target.clone();
this.wrap();
this.position = source.position.clone();
this.rotation = source.rotation.clone();
} else this.params = source.params;
this.callCopy(this);
return this;
}
get position() {
return this.native.position;
}
set position(vector3) {
this.native.position.copy(vector3);
return this.native.position;
}
get quaternion() {
return this.native.quaternion;
}
set quaternion(quaternion) {
this.native.quaternion.copy(quaternion);
return this.native.quaternion;
}
get rotation() {
return this._native.rotation;
}
set rotation(euler) {
this.native.rotation.copy(euler);
return this.native.rotation;
}
get target() {
return this.native.target;
}
set target(vector3) {
if (vector3 instanceof THREE.Object3D)
this.native.target.copy(vector3); // THREE.Object3D in this case.
else this.native.target.position.copy(vector3);
}
clone() {
return new resultComponent({build: false}).copy(this);
}
};
$wrap(targetComponent).onCallConstructor(scope => {
scope.helper = null;
if (scope.native instanceof THREE.Object3D) scope.params = scope.defaults;
});
$wrap(targetComponent).onCallWrap((scope, ...tags) => {
if (tags.indexOf('no-shadows') < 0) scope.wrapShadow();
});
return resultComponent;
}
export {
LightComponent
};
|
JavaScript
| 0 |
@@ -1802,16 +1802,8 @@
ms;%0A
- /*
%0A
@@ -2037,10 +2037,8 @@
);
-*/
%0A%0A
|
e881175c7be723571016d9989855cba18ad71c4b
|
use linearRamping for volume changes to fix fadeOut bug
|
src/playlistAudioTrack.js
|
src/playlistAudioTrack.js
|
import {
random,
timestamp
} from './utils';
import { makeInitialTrackState } from './TrackStates';
import { TrackOptions } from './mixer/track_options';
const NEARLY_ZERO = 0.01; // webaudio spec says you can't use 0.0 as a value due to floating point math concerns
/*
@see https://github.com/loafofpiecrust/roundware-ios-framework-v2/blob/client-mixing/RWFramework/RWFramework/Playlist/AudioTrack.swift
Audiotracks data looks like this:
[{
"id": 8,
"minvolume": 0.7,
"maxvolume": 0.7,
"minduration": 200.0,
"maxduration": 250.0,
"mindeadair": 1.0,
"maxdeadair": 3.0,
"minfadeintime": 2.0,
"maxfadeintime": 4.0,
"minfadeouttime": 0.3,
"maxfadeouttime": 1.0,
"minpanpos": 0.0,
"maxpanpos": 0.0,
"minpanduration": 10.0,
"maxpanduration": 20.0,
"repeatrecordings": false,
"active": true,
"start_with_silence": false,
"banned_duration": 600,
"tag_filters": [],
"project_id": 9
}]
asset looks like:
{
alt_text_loc_ids: []
audio_length_in_seconds: 14.4
created: "2019-03-13T20:09:34.237155"
description: ""
description_loc_ids: []
end_time: 14.396
envelope_ids: [6204]
file: "https://prod.roundware.com/rwmedia/20190313-200933-43867.mp3"
filename: "20190313-200933-43867.wav"
id: 11511
language_id: 1
latitude: 42.4985662
longitude: -71.2809467
media_type: "audio"
project_id: 27
session_id: 43867
shape: null
start_time: 0
submitted: true
tag_ids: [290]
updated: "2019-03-13T20:09:34.237155"
user: null
volume: 1
weight: 50
}
*/
//const LOGGABLE_AUDIO_ELEMENT_EVENTS = ['loadstart','playing','stalled','waiting']; // see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#Events
//const LOGGABLE_AUDIO_ELEMENT_EVENTS = ['playing','stalled']; // see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#Events
export class PlaylistAudiotrack {
constructor({ audioContext, windowScope, audioData = {}, playlist }) {
this.id = audioData.id;
this.data = audioData;
this.playlist = playlist;
this.playing = false;
this.trackOptions = new TrackOptions(audioData);
this.windowScope = windowScope;
const audioElement = new Audio();
audioElement.crossOrigin = 'anonymous';
audioElement.loop = false;
const audioSrc = audioContext.createMediaElementSource(audioElement);
const gainNode = audioContext.createGain();
audioSrc.connect(gainNode);
gainNode.connect(audioContext.destination);
//LOGGABLE_AUDIO_ELEMENT_EVENTS.forEach(name => audioElement.addEventListener(name,() => console.log(`[${this} audio ${name} event]`)));
audioElement.addEventListener('error',() => this.onAudioError());
audioElement.addEventListener('ended',() => this.onAudioEnded());
this.audioContext = audioContext;
this.audioElement = audioElement;
this.gainNode = gainNode;
this.setInitialTrackState();
}
setInitialTrackState() {
this.state = makeInitialTrackState(this,this.trackOptions);
}
onAudioError(evt) {
console.warn(`\t[${this} audio error, skipping to next track]`,evt);
this.setInitialTrackState();
}
onAudioEnded() {
console.log(`\t[${this} audio ended event]`);
}
play() {
console.log(`${timestamp} ${this}: ${this.state}`);
this.state.play();
}
updateParams(params = {}) {
this.state.updateParams(params);
}
// Halts any scheduled gain changes and holds at current level
// @see https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/cancelAndHoldAtTime
holdGain() {
const { gainNode: { gain }, audioContext: { currentTime } } = this;
gain.cancelAndHoldAtTime(currentTime);
}
fadeIn(fadeInDurationSeconds) {
const {
currentAsset,
audioElement,
gainNode: { gain },
audioContext: { currentTime }
} = this;
gain.value = NEARLY_ZERO;
const finalVolume = random(currentAsset.volume);
//const logline = `asset #${nextAsset.id}`;
//console.log(`${timestamp} Fading-in ${this} asset ${currentAsset.id}: ${fadeInDurationSeconds.toFixed(1)}s`);
//console.info("CONSOLEDEBUG",{ currentTime, fadeInDuration, finalVolume });
try {
audioElement.play();
gain.exponentialRampToValueAtTime(finalVolume,currentTime + fadeInDurationSeconds);
return true;
} catch(err) {
delete this.currentAsset;
console.warn(`${this} unable to play`,currentAsset,err);
return false;
}
}
rampGain(finalVolume,durationSeconds) {
const { gainNode, audioContext: { currentTime } } = this;
try {
gainNode.gain.exponentialRampToValueAtTime(finalVolume,currentTime + durationSeconds);
return true;
} catch(err) {
console.warn(`Unable to ramp gain ${this}`,err);
return false;
}
}
fadeOut(fadeOutDurationSeconds) {
return this.rampGain(NEARLY_ZERO,fadeOutDurationSeconds);
}
loadNextAsset() {
const { audioElement, currentAsset } = this;
if (currentAsset) {
currentAsset.playCount++;
currentAsset.lastListenTime = new Date();
}
const asset = this.playlist.next(this);
this.currentAsset = asset;
if (asset) {
//console.log(`Loading next asset`,asset);
audioElement.src = asset.file;
return asset;
} else {
return null;
}
}
pause() {
console.log(`${timestamp} pausing ${this}`);
this.state.pause();
if (this.audioElement) this.audioElement.pause();
}
transition(newState) {
console.log(`${timestamp} ${this}: '${this.state}' ➜ '${newState}'`);
this.state.finish();
this.state = newState;
this.state.play();
}
toString() {
const { id } = this.data;
return `Track #${id}`;
}
}
|
JavaScript
| 0 |
@@ -4616,35 +4616,30 @@
inNode.gain.
-exponential
+linear
RampToValueA
|
115d25c2a37cc309c530ca3c0edf63fd5a64fcf4
|
add hidden option to uiOptions
|
src/components/props/schema-prop.js
|
src/components/props/schema-prop.js
|
import { getIdSchema, getUiOptions } from '../../utils'
import UnsupportedProp from './unsupported-prop.vue'
const COMPONENT_TYPES = {
array: 'ArrayProp',
boolean: 'BooleanProp',
integer: 'NumberProp',
number: 'NumberProp',
object: 'ObjectProp',
string: 'StringProp'
}
export default {
functional: true,
props: {
name: String,
schema: Object,
uiSchema: Object,
errorSchema: [Object, Boolean],
idSchema: Object,
required: Boolean,
value: null,
registry: Object,
handlers: Object,
},
render (h, context) {
let errors
if (context.props.errorSchema &&
context.props.errorSchema._errors !== undefined &&
context.props.errorSchema._errors.length > 0) {
errors = context.props.errorSchema._errors
}
const uiOptions = getUiOptions(
context.props.schema,
context.props.uiSchema, {
name: context.props.name,
required: context.props.required,
invalid: errors && errors.length > 0,
handlers: context.props.handlers,
}
)
function getPropComponent () {
const prop = uiOptions.prop
if (typeof prop === 'function') {
return prop
}
if (typeof prop === 'string' && prop in context.props.registry.props) {
return context.props.registry.props[prop]
}
const componentName = COMPONENT_TYPES[context.props.schema.type]
return componentName in context.props.registry.props
? context.props.registry.props[componentName].name : UnsupportedProp.name
}
return h(getPropComponent(), {
props: {
name: context.props.name,
schema: context.props.schema,
uiSchema: context.props.uiSchema,
errorSchema: context.props.errorSchema,
idSchema: getIdSchema({
idSchema: context.props.idSchema,
id: uiOptions.$id
}),
errors: uiOptions.displayErrors ? errors : undefined,
value: context.props.value,
registry: context.props.registry,
uiOptions,
},
on: context.listeners,
})
},
}
|
JavaScript
| 0 |
@@ -1539,24 +1539,94 @@
name%0A %7D%0A%0A
+ if (uiOptions && uiOptions.hidden === true) %7B%0A return%0A %7D%0A%0A
return h
|
d49a8313ca0eeb903536110baac782fa7a9bad94
|
Remove tabs from uploadcare start
|
widget/index.js
|
widget/index.js
|
/* global JFCustomWidget, uploadcare */
/**
* Resize JotForm widget frame
*
* @param width
* @param height
*/
function resize(width, height) {
JFCustomWidget.requestFrameResize({
width: width,
height: height,
})
}
function cropOption(mode, width, height) {
switch (mode) {
case 'free crop':
return 'free'
break
case 'aspect ratio':
return parseInt(width) + ':' + parseInt(height)
break
case 'downscale':
return parseInt(width) + 'x' + parseInt(height)
break
case 'downscale & upscale':
return parseInt(width) + 'x' + parseInt(height) + ' upscale'
break
case 'downscale & minimum size':
return parseInt(width) + 'x' + parseInt(height) + ' minimum'
break
default:
return 'disabled'
}
}
function cleanGlobalSettings(str) {
var expr = /(UPLOADCARE_\w+)\s*=\s*({(\n(.+\n)+};)|{(.+};)|{((.+\n)+};)|([\w'":/\.\s,]+);)/gm
try {
var result = str.match(expr)
return result ? result.join('\n') : ''
}
catch(error) {
console.error(error)
return ''
}
}
JFCustomWidget.subscribe('ready', function(data) {
var isMultiple = (JFCustomWidget.getWidgetSetting('multiple') == 'Yes')
var globalSettings = JFCustomWidget.getWidgetSetting('globalSettings')
if (globalSettings) {
globalSettings = cleanGlobalSettings(globalSettings)
if (globalSettings) {
var script = document.createElement('script')
script.innerHTML = globalSettings
document.head.appendChild(script)
}
}
uploadcare.start({
publicKey: JFCustomWidget.getWidgetSetting('publicKey'),
locale: JFCustomWidget.getWidgetSetting('locale') || 'en',
imagesOnly: (JFCustomWidget.getWidgetSetting('imagesOnly') == 'Yes'),
multiple: isMultiple,
previewStep: (JFCustomWidget.getWidgetSetting('previewStep') == 'Yes'),
tabs: 'all',
crop: cropOption(
JFCustomWidget.getWidgetSetting('crop'),
JFCustomWidget.getWidgetSetting('cropWidth'),
JFCustomWidget.getWidgetSetting('cropHeight')
),
})
var widget = uploadcare.Widget('[role=uploadcare-uploader]')
var files = (data && data.value) ? data.value.split('\n') : []
if (files.length) {
widget.value(isMultiple ? files : files[0])
}
JFCustomWidget.subscribe('submit', function() {
var msg = {
valid: !!files.length,
value: files.join('\n'),
}
JFCustomWidget.sendSubmit(msg)
})
widget.onDialogOpen(function(dialog) {
resize(618, 600)
dialog.always(function() {
resize(458, 32)
})
})
widget.onChange(function(file) {
files = []
var uploadedFiles = file.files ? file.files() : [file]
uploadedFiles.forEach(function(uploadedFile) {
uploadedFile.done(function(fileInfo) {
files.push(fileInfo.cdnUrl)
})
})
})
})
|
JavaScript
| 0 |
@@ -1759,23 +1759,8 @@
'),%0A
-%09%09tabs: 'all',%0A
%09%09cr
|
75fa461a4c7aaafc8d3e12ae7027df563d1ceecb
|
Return metadata about screenshares when using electron
|
electron.js
|
electron.js
|
var crel = require('crel');
var EventEmitter = require('eventemitter3');
var extend = require('cog/extend');
/**
Returns true if we should use Chrome screensharing
**/
exports.supported = function() {
return window && window.process && window.process.type && window.require;
}
/**
Creates the share context.
**/
exports.share = function(opts) {
opts = opts || {};
var extension = new EventEmitter();
extension.type = 'github/electron';
var electron = null;
try {
electron = window.require('electron');
} catch (err) {}
extension.available = function(callback) {
return callback((electron ? null : 'Electron was unable to be found'));
};
// patch in our capture function
extension.request = function(callback) {
function selectMedia(source, sourceId) {
if (!source) return callback('No media selected');
return callback(null, extend({
audio: false,
video: {
mandatory: {
chromeMediaSource: source,
chromeMediaSourceId: sourceId,
maxWidth: screen.width,
maxHeight: screen.height,
minFrameRate: 1,
maxFrameRate: 5
},
optional: []
}
}, opts.constraints));
}
// If we are a version of Electron (>= 0.36.0) that supports desktopCapture
if (electron && electron.desktopCapturer && !opts.screenOnly) {
electron.desktopCapturer.getSources(
extend({types: ['window', 'screen']}, opts.capturer || {}),
function(err, sources) {
if (err) return callback(err);
// If we only have one, select only that
if (sources && sources.length === 1) {
return selectMedia('desktop', sources[i].id);
}
// Allow a customised visual selector
(opts.selectorFn || simpleSelector)(sources, function(err, sourceId) {
if (err) return callback(err);
return selectMedia('desktop', sourceId);
});
}
);
}
// Otherwise we only share the screen
else {
return selectMedia('screen');
}
};
extension.cancel = function() {
};
return extension;
};
/**
This is just a simple default screen selector implementation
**/
function simpleSelector(sources, callback) {
var options = crel('select', {
style: 'margin: 0.5rem'
}, sources.map(function(source) {
return crel('option', {id: source.id, value: source.id}, source.name);
}));
var selector = crel('div',
{
style: 'position: absolute; padding: 1rem; z-index: 999999; background: #ffffff; width: 100%; font-family: \'Lucida Sans Unicode\', \'Lucida Grande\', sans-serif; box-shadow: 0px 2px 4px #dddddd;'
},
crel('label', { style: 'margin: 0.5rem' }, 'Share screen:'),
options,
crel('span', { style: 'margin: 0.5rem; display: inline-block' },
button('Share', function() {
close();
return callback(null, options.value);
}),
button('Cancel', close)
)
);
function button(text, fn) {
var button = crel('button', {
style: 'background: #555555; color: #ffffff; padding: 0.5rem 1rem; margin: 0rem 0.2rem;'
}, text);
button.addEventListener('click', fn);
return button;
}
function close() {
document.body.removeChild(selector);
}
document.body.appendChild(selector);
}
|
JavaScript
| 0.000004 |
@@ -780,32 +780,42 @@
source, sourceId
+, metadata
) %7B%0A if (!s
@@ -1243,16 +1243,26 @@
traints)
+, metadata
);%0A %7D
@@ -1751,16 +1751,36 @@
es%5Bi%5D.id
+, %7Btitle: 'Screen'%7D
);%0A
@@ -1911,16 +1911,26 @@
sourceId
+, metadata
) %7B%0A
@@ -2018,16 +2018,26 @@
sourceId
+, metadata
);%0A
@@ -2156,16 +2156,43 @@
'screen'
+, null, %7B title: 'Screen' %7D
);%0A %7D
@@ -3004,16 +3004,144 @@
lose();%0A
+ var selected = sources.filter(function(source) %7B%0A return source && source.id === options.value;%0A %7D)%5B0%5D;%0A
@@ -3175,16 +3175,42 @@
ns.value
+, %7B title: selected.name %7D
);%0A
|
869a861862de04d58fecb47974c822f7fc4480b1
|
suporte a letras maiúsculas
|
js/dinofauref.js
|
js/dinofauref.js
|
/**
* Created by matheuf grafiano on 01/06/15.
* Efe algoritmo pega palafra por palafra e fubftitui of fonemaf do array FONEMAS por F.
*/
//Os fonemas estão em ordem de prioridade
FONEMAS = {
'xce' : 'fe',
'xci' : 'fi',
'ch' : 'f',
'ss' : 'f',
'ce' : 'fe',
'ci' : 'fi',
've' : 'fe',
'ge ' : 'fe',
'gi' : 'fi',
's' : 'f',
'v': 'f',
'z' : 'f',
'j' : 'f',
'ç' : 'f'
};
/**
* @param palavra
* @returns palafra
*/
traduzPalavra = function(palavra){
var palafra = palavra;
for (var fonema in FONEMAS) {
if (FONEMAS.hasOwnProperty(fonema)) {
palafra = palafra.replace(new RegExp(fonema, 'gi'),FONEMAS[fonema]);
}
}
return palafra;
};
traduzTexto = function(texto){
var traduzido = "";
var palavras = texto.split(' ');
for(var i=0; i<palavras.length; i++){
var palavra = palavras[i];
traduzido = traduzido+traduzPalavra(palavra)+" ";
}
return traduzido.trim();
};
|
JavaScript
| 0.000001 |
@@ -420,16 +420,85 @@
'f'%0A%7D;%0A%0A
+var isLowerCase = function(s)%7B%0A return s.toLowerCase() === s;%0A%7D;%0A%0A
/**%0A * @
@@ -744,23 +744,967 @@
i'),
-FONEMAS%5Bfonema%5D
+function(match)%7B%0A var replaceString = %22%22;%0A var replafe = FONEMAS%5Bmatch.toLowerCase()%5D;%0A var lastLowerCase = true;%0A for(var i=0; i%3Cmatch.length && i%3Creplafe.length; i++)%7B%0A var letra = match%5Bi%5D;%0A if(lastLowerCase = isLowerCase(letra))%0A replaceString = replaceString + replafe%5Bi%5D;%0A else%0A replaceString = replaceString + replafe%5Bi%5D.toUpperCase();%0A %7D%0A if(match.length %3C replafe.length)%7B%0A for(i=match.length; i%3Creplafe.length; i++)%7B%0A if(lastLowerCase)%0A replaceString = replaceString + replafe%5Bi%5D;%0A else%0A replaceString = replaceString + replafe%5Bi%5D.toUpperCase();%0A %7D%0A %7D%0A return replaceString;%0A %7D
);%0A
|
b729dfd13b122e28ff80a4ff5ade4816c353448a
|
make httService a more common js ctor
|
lib/services/http-service.js
|
lib/services/http-service.js
|
var request = require('request');
/**
* A generic HTTP Service,
* used to make GET and POST request to a remote server.
* Use request library to perform the request.
*/
var HttpService = function() {
/**
* Perform a GET request.
*
* @param {string} uri The remote server's uri.
* @param {Function} cb A callback fired when all operations are done.
* @return {undefined}
*/
this.get = function(uri, cb) {
request.get(uri, cb);
};
/**
* Perform a POST request.
*
* @param {string} uri The remote server's uri.
* @param {object} data The data to send.
* @param {Function} cb A callback fired when all operations are done.
* @return {undefined}
*/
this.post = function(uri, data, cb) {
var payLoad = {
form: data || {}
};
request.post(uri, payLoad, cb);
};
};
module.exports = new HttpService();
|
JavaScript
| 0.000284 |
@@ -167,19 +167,24 @@
st.%0A */%0A
-var
+function
HttpSer
@@ -187,27 +187,16 @@
pService
- = function
() %7B%0A%0A%09/
@@ -933,8 +933,9 @@
rvice();
+%0A
|
51f04fdbc10041106eee45ca539d842bc74c5c80
|
Add checkpoint/rollback to ReactNativeReconcileTransaction (#7619)
|
src/renderers/native/ReactNativeReconcileTransaction.js
|
src/renderers/native/ReactNativeReconcileTransaction.js
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeReconcileTransaction
* @flow
*/
'use strict';
var CallbackQueue = require('CallbackQueue');
var PooledClass = require('PooledClass');
var Transaction = require('Transaction');
var ReactInstrumentation = require('ReactInstrumentation');
var ReactUpdateQueue = require('ReactUpdateQueue');
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks during
* the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
},
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
if (__DEV__) {
TRANSACTION_WRAPPERS.push({
initialize: ReactInstrumentation.debugTool.onBeginFlush,
close: ReactInstrumentation.debugTool.onEndFlush,
});
}
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactNativeReconcileTransaction
*/
function ReactNativeReconcileTransaction() {
this.reinitializeTransaction();
this.reactMountReady = CallbackQueue.getPooled(null);
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
* TODO: convert to ReactMountReady
*/
getReactMountReady: function() {
return this.reactMountReady;
},
/**
* @return {object} The queue to collect React async events.
*/
getUpdateQueue: function() {
return ReactUpdateQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
},
};
Object.assign(
ReactNativeReconcileTransaction.prototype,
Transaction,
ReactNativeReconcileTransaction,
Mixin
);
PooledClass.addPoolingTo(ReactNativeReconcileTransaction);
module.exports = ReactNativeReconcileTransaction;
|
JavaScript
| 0 |
@@ -2679,32 +2679,418 @@
ateQueue;%0A %7D,%0A%0A
+ /**%0A * Save current transaction state -- if the return value from this method is%0A * passed to %60rollback%60, the transaction will be reset to that state.%0A */%0A checkpoint: function() %7B%0A // reactMountReady is the our only stateful wrapper%0A return this.reactMountReady.checkpoint();%0A %7D,%0A%0A rollback: function(checkpoint) %7B%0A this.reactMountReady.rollback(checkpoint);%0A %7D,%0A%0A
/**%0A * %60Pool
|
ac1a25d7a0a7cf35c7753d8cf2cc52b04f368ee0
|
allow passing a single options object to a MultiCompiler
|
lib/MultiCompiler.js
|
lib/MultiCompiler.js
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Tapable = require("tapable");
var async = require("async");
var MultiWatching = require("./MultiWatching");
var MultiStats = require("./MultiStats");
function MultiCompiler(compilers) {
Tapable.call(this);
if(!Array.isArray(compilers)) {
compilers = Object.keys(compilers).map(function(name) {
compilers[name].name = name;
return compilers[name];
});
}
this.compilers = compilers;
function delegateProperty(name) {
Object.defineProperty(this, name, {
configurable: false,
get: function() {
throw new Error("Cannot read " + name + " of a MultiCompiler");
},
set: function(value) {
this.compilers.forEach(function(compiler) {
compiler[name] = value;
});
}.bind(this)
});
}
delegateProperty.call(this, "outputFileSystem");
delegateProperty.call(this, "inputFileSystem");
Object.defineProperty(this, "outputPath", {
configurable: false,
get: function() {
var commonPath = compilers[0].outputPath;
for(var i = 1; i < compilers.length; i++) {
while(compilers[i].outputPath.indexOf(commonPath) !== 0 && /[\/\\]/.test(commonPath)) {
commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, "");
}
}
if(!commonPath && compilers[0].outputPath[0] === "/") return "/";
return commonPath;
}
});
var doneCompilers = 0;
var compilerStats = [];
this.compilers.forEach(function(compiler, idx) {
var compilerDone = false;
compiler.plugin("done", function(stats) {
if(!compilerDone) {
compilerDone = true;
doneCompilers++;
}
compilerStats[idx] = stats;
if(doneCompilers === this.compilers.length) {
this.applyPlugins("done", new MultiStats(compilerStats));
}
}.bind(this));
compiler.plugin("invalid", function() {
if(compilerDone) {
compilerDone = false;
doneCompilers--;
}
this.applyPlugins("invalid");
}.bind(this));
}, this);
}
module.exports = MultiCompiler;
MultiCompiler.prototype = Object.create(Tapable.prototype);
MultiCompiler.prototype.constructor = MultiCompiler;
function runWithDependencies(compilers, fn, callback) {
var fulfilledNames = {};
var remainingCompilers = compilers;
function isDependencyFulfilled(d) {
return fulfilledNames[d];
}
function getReadyCompilers() {
var readyCompilers = [];
var list = remainingCompilers;
remainingCompilers = [];
for(var i = 0; i < list.length; i++) {
var c = list[i];
var ready = !c.dependencies || c.dependencies.every(isDependencyFulfilled);
if(ready)
readyCompilers.push(c);
else
remainingCompilers.push(c);
}
return readyCompilers;
}
function runCompilers(callback) {
if(remainingCompilers.length === 0) return callback();
async.map(getReadyCompilers(), function(compiler, callback) {
fn(compiler, function(err) {
if(err) return callback(err);
fulfilledNames[compiler.name] = true;
runCompilers(callback);
});
}, callback);
}
runCompilers(callback);
}
MultiCompiler.prototype.watch = function(watchOptions, handler) {
var watchings = [];
var allStats = this.compilers.map(function() {
return null;
});
var compilerStatus = this.compilers.map(function() {
return false;
});
if(!Array.isArray(watchOptions)) {
watchOptions = [watchOptions];
}
runWithDependencies(this.compilers, function(compiler, callback) {
var compilerIdx = this.compilers.indexOf(compiler);
var firstRun = true;
var watching = compiler.watch(watchOptions[compilerIdx], function(err, stats) {
if(err)
handler(err);
if(stats) {
allStats[compilerIdx] = stats;
compilerStatus[compilerIdx] = "new";
if(compilerStatus.every(Boolean)) {
var freshStats = allStats.filter(function(s, idx) {
return compilerStatus[idx] === "new";
});
compilerStatus.fill(true);
var multiStats = new MultiStats(freshStats);
handler(null, multiStats);
}
}
if(firstRun && !err) {
firstRun = false;
callback();
}
});
watchings.push(watching);
}.bind(this), function() {
// ignore
});
return new MultiWatching(watchings);
};
MultiCompiler.prototype.run = function(callback) {
var allStats = this.compilers.map(function() {
return null;
});
runWithDependencies(this.compilers, function(compiler, callback) {
var compilerIdx = this.compilers.indexOf(compiler);
compiler.run(function(err, stats) {
if(err) return callback(err);
allStats[compilerIdx] = stats;
callback();
});
}.bind(this), function(err) {
if(err) return callback(err);
callback(null, new MultiStats(allStats));
});
};
MultiCompiler.prototype.purgeInputFileSystem = function() {
this.compilers.forEach(function(compiler) {
if(compiler.inputFileSystem && compiler.inputFileSystem.purge)
compiler.inputFileSystem.purge();
});
};
|
JavaScript
| 0 |
@@ -3244,80 +3244,8 @@
%7D);%0A
-%09if(!Array.isArray(watchOptions)) %7B%0A%09%09watchOptions = %5BwatchOptions%5D;%0A%09%7D%0A
%09run
@@ -3417,16 +3417,46 @@
r.watch(
+Array.isArray(watchOptions) ?
watchOpt
@@ -3472,16 +3472,31 @@
ilerIdx%5D
+ : watchOptions
, functi
|
80076e6208c36ac3045eac3505943a32850354b0
|
Whoops. Rounded the wrong date
|
js/generateTP.js
|
js/generateTP.js
|
/**
* ownCloud - spreedme
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Leon <[email protected]>
* @copyright Leon 2015
*/
// This file is loaded in ownCloud context
(function($, OC) {
$(document).ready(function() {
var requestTP = function(userid, expiration, cb) {
if (userid.length < 1) {
alert("Please enter a valid username to invite");
return;
}
if (expiration.length < 1 || expiration < 1 || parseInt(expiration, 10) != expiration) {
alert("Please enter a valid expiration date");
return;
}
if (expiration > Math.round(new Date().getTime() / 1000) + (60 * 60 * 24)) {
var response = confirm("Do you really want to generate a Temporary Passwords which is valid for more than 1 day?");
if (!response) {
return;
}
}
var baseUrl = OC.generateUrl('/apps/spreedme');
var data = {
userid: userid,
expiration: expiration
};
$.ajax({
url: baseUrl + '/api/v1/admin/tp',
type: 'POST',
data: $.param(data)
}).done(function (response) {
if (response.success === true) {
cb(response.tp);
}
}).fail(function (response, code) {
console.log(response, code);
});
};
var useridField = $("form input[name=userid]");
var expirationField = $("form input[name=expiration]");
$("form input[type=submit]").click(function(e) {
e.preventDefault();
requestTP(useridField.val(), (new Date(expirationField.datetimepicker("getDate")).getTime() / 1000), function(tp) {
var tpField = $("<input>")
.attr("value", tp)
.attr("size", "80")
.attr("readonly", "readonly")
.click(function() {
$(this).select();
});
$("#tp")
.text("")
.append("Temporary Password generated:<br />")
.append(tpField)
.append("<br /><br />");
});
});
expirationField.datetimepicker({
oneLine: true,
minDate: new Date(),
controlType: "select"
});
var date = new Date((new Date()).getTime() + (1000 * 60 * 60 * 2)); // Add 2 hours
expirationField.datetimepicker("setDate", date);
});
})(jQuery, OC);
|
JavaScript
| 0.999999 |
@@ -621,18 +621,8 @@
n %3E
-Math.round
(new
@@ -1417,16 +1417,26 @@
.val(),
+Math.round
(new Dat
|
ad3c8f5c83b5e40d49c6779ac98f7f4ca7f13c71
|
fix lint errors
|
src/containers/editable-popover3.js
|
src/containers/editable-popover3.js
|
/**
* Editable Popover3 (for Bootstrap 3)
* ---------------------
* requires bootstrap-popover.js
*/
(function ($) {
"use strict";
//extend methods
$.extend($.fn.editableContainer.Popup.prototype, {
containerName: 'popover',
containerDataName: 'bs.popover',
innerCss: '.popover-content',
defaults: $.fn.popover.Constructor.DEFAULTS,
initContainer: function(){
$.extend(this.containerOptions, {
trigger: 'manual',
selector: false,
content: ' ',
template: this.defaults.template
});
//as template property is used in inputs, hide it from popover
var t;
if(this.$element.data('template')) {
t = this.$element.data('template');
this.$element.removeData('template');
}
this.call(this.containerOptions);
if(t) {
//restore data('template')
this.$element.data('template', t);
}
},
/* show */
innerShow: function () {
this.call('show');
},
/* hide */
innerHide: function () {
this.call('hide');
},
/* destroy */
innerDestroy: function() {
this.call('destroy');
},
setContainerOption: function(key, value) {
this.container().options[key] = value;
},
/**
* move popover to new position. This function mainly copied from bootstrap-popover.
*/
/*jshint laxcomma: true, eqeqeq: false*/
setPosition: function () {
(function() {
/*
var $tip = this.tip()
, inside
, pos
, actualWidth
, actualHeight
, placement
, tp
, tpt
, tpb
, tpl
, tpr;
placement = typeof this.options.placement === 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
inside = /in/.test(placement);
$tip
// .detach()
//vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover
.removeClass('top right bottom left')
.css({ top: 0, left: 0, display: 'block' });
// .insertAfter(this.$element);
pos = this.getPosition(inside);
actualWidth = $tip[0].offsetWidth;
actualHeight = $tip[0].offsetHeight;
placement = inside ? placement.split(' ')[1] : placement;
tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
switch (placement) {
case 'bottom':
if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) {
if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else {
placement = 'right';
}
}
break;
case 'top':
if (tpt.top < $(window).scrollTop()) {
if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) {
placement = 'bottom';
} else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else {
placement = 'right';
}
}
break;
case 'left':
if (tpl.left < $(window).scrollLeft()) {
if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) {
placement = 'right';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'bottom';
} else {
placement = 'right';
}
}
break;
case 'right':
if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) {
if (tpl.left > $(window).scrollLeft()) {
placement = 'left';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'top';
} else if (tpt.top > $(window).scrollTop()) {
placement = 'bottom';
}
}
break;
}
switch (placement) {
case 'bottom':
tp = tpb;
break;
case 'top':
tp = tpt;
break;
case 'left':
tp = tpl;
break;
case 'right':
tp = tpr;
break;
}
$tip
.offset(tp)
.addClass(placement)
.addClass('in');
*/
var $tip = this.tip();
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement;
var autoToken = /\s?auto?\s?/i;
var autoPlace = autoToken.test(placement);
if (autoPlace) placement = placement.replace(autoToken, '') || 'top';
var pos = this.getPosition();
var actualWidth = $tip[0].offsetWidth;
var actualHeight = $tip[0].offsetHeight;
if (autoPlace) {
var $parent = this.$element.parent();
var orgPlacement = placement;
var docScroll = document.documentElement.scrollTop || document.body.scrollTop;
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth();
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight();
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left;
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement;
$tip
.removeClass(orgPlacement)
.addClass(placement);
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight);
this.applyPlacement(calculatedOffset, placement);
}).call(this.container());
/*jshint laxcomma: false, eqeqeq: true*/
}
});
}(window.jQuery));
|
JavaScript
| 0.000037 |
@@ -7196,16 +7196,34 @@
toPlace)
+ %7B%0A
placeme
@@ -7262,32 +7262,46 @@
, '') %7C%7C 'top';%0A
+ %7D%0A
%0A
|
0fbc91e6b831d1183d18874ceab7e847eef5ee7a
|
use _.cellsize instead of T.cellsize
|
src/objects/cosc.js
|
src/objects/cosc.js
|
(function(T) {
"use strict";
var fn = T.fn;
var Oscillator = T.modules.Oscillator;
function COscNode(_args) {
T.Object.call(this, 1, _args);
fn.fixAR(this);
var _ = this._;
_.freq = T(440);
_.osc1 = new Oscillator(T.samplerate);
_.osc2 = new Oscillator(T.samplerate);
_.osc1.step = T.cellsize;
_.osc2.step = T.cellsize;
_.tmp = new fn.SignalArray(T.cellsize);
_.beats = 0.5;
this.once("init", oninit);
}
fn.extend(COscNode);
var oninit = function() {
if (!this.wave) {
this.wave = "sin";
}
};
var $ = COscNode.prototype;
Object.defineProperties($, {
wave: {
set: function(value) {
this._.osc1.setWave(value);
this._.osc2.setWave(value);
},
get: function() {
return this._.osc1.wave;
}
},
freq: {
set: function(value) {
this._.freq = T(value);
},
get: function() {
return this._.freq;
}
},
beats: {
set: function(value) {
if (typeof value === "number" && value > 0) {
this._.beats = value;
}
},
get: function() {
return this._.beats;
}
}
});
$.bang = function() {
this._.osc1.reset();
this._.osc2.reset();
this._.emit("bang");
return this;
};
$.process = function(tickID) {
var _ = this._;
var cell = this.cells[0];
if (this.tickID !== tickID) {
this.tickID = tickID;
var i, imax = cell.length;
var freq = _.freq.process(tickID).cells[0][0];
var osc1 = _.osc1, osc2 = _.osc2, tmp = _.tmp;
osc1.frequency = freq - (_.beats * 0.5);
osc1.process(tmp);
for (i = 0; i < imax; ++i) {
cell[i] = tmp[i] * 0.5;
}
osc2.frequency = freq + (_.beats * 0.5);
osc2.process(tmp);
for (i = 0; i < imax; ++i) {
cell[i] += tmp[i] * 0.5;
}
fn.outputSignalAR(this);
}
return this;
};
fn.register("cosc", COscNode);
})(timbre);
|
JavaScript
| 0.000169 |
@@ -358,33 +358,33 @@
_.osc1.step =
-T
+_
.cellsize;%0A
@@ -400,17 +400,17 @@
.step =
-T
+_
.cellsiz
@@ -447,17 +447,17 @@
alArray(
-T
+_
.cellsiz
|
d2f2816ccf145bf4d1f89d5f2825e69a45af60ac
|
improve error and on event info
|
worker_relay.js
|
worker_relay.js
|
var http = require('http');
var MG = require('./my_globals').C;
var url = require('url');
var db = require('./dbrelayer');
function do_job(task, callback) {
var target_host = task.headers[MG.HEAD_RELAYER_HOST];
if (!target_host) {
console.log("Not target host");
}
else {
var options = url.parse(target_host);
task.headers['host'] = options.host;
options.headers = task.headers;
options.method = task.method;
req = http.request(options, function (rly_res) {
if (Math.floor(rly_res.statusCode / 100) != 5) {
//if no 5XX ERROR
get_response(rly_res, task, function (task, resp_obj) {
//PERSISTENCE
do_persistence(task, resp_obj, task.headers[MG.HEAD_RELAYER_PERSISTENCE], function onPersistence(errP, resultP) {
//CALLBACK
do_http_callback(task, resp_obj, function onCallback(errC, resultC) {
var cb_error = {
persistence_error: errP,
httpcb_error: errC
};
if (!(cb_error.persistence_error || cb_error.httpcb_error)){
cb_error=null;
}
var cb_result = {
persistence_result: resultP,
httpcb_result: resultC
};
if (callback) callback(cb_error, cb_result);
});
});
});
}
else {
handle_request_error(task, callback)({message:'Server error:' + rly_res.statusCode, statusCode:rly_res.statusCode, headers:rly_res.headers});
}
}
);
req.on('error', handle_request_error(task, callback));
if (options.method == 'POST' || options.method == 'PUT') {
//write body
req.write(task.body);
}
req.end(); //?? sure HERE?
}
}
function handle_request_error(task, callback) {
return function (e) {
console.log('problem with relayed request: ' + e.message);
do_retry(task, e, callback);
}
}
function get_response(resp, task, callback) {
var data = "";
resp.on('data', function (chunk) {
data += chunk;
});
resp.on('end', function (chunk) {
if (chunk) {
if (chunk) {
data += chunk;
} //avoid tail undefined
}
var resp_obj = {statusCode:resp.statusCode, headers:resp.headers, body:data, state:'relay_response'};
if (callback) {
callback(task, resp_obj);
}
});
}
function set_object(task, resp_obj, type, callback) {
//remove from response what is not needed
var set_obj = {};
type = type.toUpperCase();
//todo
if (type === 'STATUS') {
set_obj.statusCode = resp_obj.statusCode;
}
else if (type == 'HEADER') {
set_obj.statusCode = resp_obj.statusCode;
set_obj.headers = resp_obj.headers;
}
else if (type == 'BODY') {
set_obj.statusCode = resp_obj.statusCode;
set_obj.headers = resp_obj.headers;
set_obj.body = resp_obj.body;
}
else if (type == 'ERROR') {
set_obj = resp_obj;
}
else {
//Error
var err_msg = type + " is not a valid value for " + MG.HEAD_RELAYER_PERSISTENCE;
console.log(err_msg);
callback && callback(err_msg);
}
db.update(task.id, set_obj, function (err, red_res) {
if (err) {
console.log(err);
}
callback && callback(err, set_obj);
});
}
function do_persistence(task, resp_obj, type, callback) {
if (type) {
set_object(task, resp_obj, type, callback);
}
else if (callback) callback(null, 'no persistence/no data');
}
function do_http_callback(task, resp_obj, callback) {
var callback_host = task.headers[MG.HEAD_RELAYER_HTTPCALLBACK];
var db_err;
if (callback_host) {
var callback_options = url.parse(callback_host);
callback_options.method = 'POST';
var callback_req = http.request(callback_options, function (callback_res) {
//check callback_res status (modify state) Not interested in body
db_res = {callback_status:callback_res.statusCode, callback_details:'callback sent OK'};
db.update(task.id, db_res, function (err) {
if (err) {
console.log("BD Error setting callback status:" + err);
}
if (callback) callback(err, db_res);
});
}
);
callback_req.on('error', function (err) {
//error in request
var str_err = JSON.stringify(err); // Too much information?????
db_st = {callback_status:'error', callback_details:str_err};
//store
db.update(task.id, db_st, function (dberr) {
if (dberr) {
console.log("BD Error setting callback ERROR:" + dberr);
}
if (callback) callback(dberr, db_st);
});
});
var str_resp_obj = JSON.stringify(resp_obj);
callback_req.write(str_resp_obj);
callback_req.end();
}
else {
if (callback) callback(null);
}
}
function do_retry(task, error, callback) {
var retry_list = task.headers[MG.HEAD_RELAYER_RETRY];
var time = -1;
if (retry_list) {
retry_a = retry_list.split(",");
if (retry_a.length > 0) {
time = parseInt(retry_a.shift(), 10);
if (retry_a.length > 0) {
// there is retry times still
task.headers[MG.HEAD_RELAYER_RETRY] = retry_a.join(",");
}
else {
//Retry End with no success
delete task.headers[MG.HEAD_RELAYER_RETRY];
}
if (time > 0) {
setTimeout(function () {
do_job(task, callback);
}, time);
}
}
}
else {
//no more attempts (or no retry policy)
//error persistence
do_persistence(task, error, 'ERROR', function (errP, resultP) {
//CALLBACK
do_http_callback(task, error, function (errC, resultC){
var cb_error = {
persistence_error: errP,
httpcb_error: errC
};
if (!(cb_error.persistence_error || cb_error.httpcb_error)){
cb_error=null;
}
var cb_result = {
relayed_request_error: error,
persistence_result: resultP,
httpcb_result: resultC
};
if (callback) callback(cb_error, cb_result);
});
});
}
}
exports.do_job = do_job;
|
JavaScript
| 0 |
@@ -1455,32 +1455,103 @@
cb_result = %7B%0D%0A
+ relayed_request_result: resp_obj,%0D%0A
@@ -6895,32 +6895,83 @@
r cb_error = %7B%0D%0A
+ relayed_request_error: error,%0D%0A
@@ -7125,32 +7125,66 @@
ror.httpcb_error
+ %7C%7C cb_error.relayed_request_error
))%7B%0D%0A
@@ -7266,59 +7266,8 @@
%7B%0D%0A
- relayed_request_error: error,%0D%0A
|
2d56aa941cc7d3e616817a63a184eebc279a2155
|
refactor adapter
|
lib/adapter/style.js
|
lib/adapter/style.js
|
var util = require('util'),
css = require('css'),
path = require('path'),
_fs = require('../util/file.js'),
_util = require('../util/util.js'),
_path = require('../util/path.js'),
_Abstract = require('../util/event.js');
// token parser
// file file path
// content file content
var CSSParser = module.exports = function(config){
_Abstract.apply(this,arguments);
// private variable
var _gAST,_gRes;
// dump static resource
var _rMap = {
// background with url(/path/to/image.png)
background:function(rule){
if (/url\(['"]?(.*?)['"]?\)/i.test(rule.value)){
return RegExp.$1;
}
}
};
var _doDumpStaticRes = function(rules){
var list = Object.keys(rules||{});
if (!list||!list.length){
return;
}
// check static resource
list.forEach(function(key){
var rule = rules[key];
if (key!=='declaration'){
_doDumpStaticRes(rule);
return;
}
// check resource in css rule
var func = _rMap[rule.property];
if (!!func){
var ret = func(rule);
if (!!ret){
_gRes[ret] = rule;
}
}
});
};
// update content
this.parse = function(config){
// init options
this.file = config.file;
// parse css source
_gAST = css.parse(
config.content,{
silent:!0,
source:this.file
}
);
// dump static resource
_gRes = {};
_doDumpStaticRes(_gAST);
};
// merge static resource
// webRoot web root path
// resRoot static resource root
// domain domain config
// version version config
this.stringify = function(config){
var pathRoot = path.dirname(this.file)+'/';
Object.keys(_gRes).forEach(function(key){
var arr = key.split('?'),
file = _path.absoluteAltRoot(
arr[0],pathRoot,config.webRoot
);
// only update resource root for files in resource root
if (!_fs.exist(file)||
_fs.isdir(file)||
file.indexOf(config.resRoot)<0){
return;
}
// check version
if (!!config.version&&!arr[1]){
arr[1] = _util.version(
_fs.raw(file)
);
}
// check file path
if (!config.domain){
// use relative path
arr[0] = _path.normalize(
path.relative(
pathRoot,file
)
);
}else{
// use absolute path
var domain = config.domain;
if (util.isArray(domain)){
domain = domain[_util.rand(
0,domain.length
)];
}
arr[0] = file.replace(
config.webRoot,domain
);
}
// update rule
var rule = _gRes[key];
rule.value = rule.value.replace(
key,arr.join('?')
);
});
return css.stringify(_gAST,{
indent:0,
compress:!0,
sourcemap:!1,
inputSourcemaps:!1
});
};
// update content
if (!!config){
this.parse(config);
}
};
util.inherits(CSSParser,_Abstract);
|
JavaScript
| 0.000002 |
@@ -1,12 +1,353 @@
+/*%0A * CSS Content Parser Adapter%0A * @module adapter/style%0A * @author genify([email protected])%0A */%0Avar Parser = module.exports =%0A require('../util/klass.js').create();%0Avar pro = Parser.extend(require('../util/event.jss'));%0A%0A%0Apro.init = function()%7B%0A%0A%7D;%0A%0A%0Apro.parse = function(config)%7B%0A%0A%7D;%0A%0A%0Apro.stringify = function()%7B%0A%0A%7D;%0A%0A%0A%0A%0A%0A%0A%0A
var util
|
db51c4f2181a1ea625ba37d5965c06741bb91565
|
Add function isDatabaseExists in sqlCommands.spec.js
|
sashimi-webapp/test/unit/specs/database/sqlCommands.spec.js
|
sashimi-webapp/test/unit/specs/database/sqlCommands.spec.js
|
import SqlCommands from 'src/database/sql-related/sqlCommands';
import SqlArray from 'src/database/generated-data/sqlArray';
import dataDelete from 'src/database/data-modifier/dataDelete';
import exceptions from 'src/database/exceptions';
const testDatabaseName = 'test';
const sqlCommands = new SqlCommands();
const alasqlArray = new SqlArray();
function cleanTestCase() {
dataDelete.deleteAllEntities(testDatabaseName);
}
describe('sqlCommands', () => {
describe('link to indexeddb database', () => {
it('should link to indexeddb database', (done) => {
if (!window.indexedDB) {
done(exceptions.IndexedDBNotSupported);
}
sqlCommands.linkDatabaseToIndexedDB(testDatabaseName)
.then(() => {
const request = window.indexedDB.open(testDatabaseName);
request.onsuccess = function onsuccess(event) {
expect(event.target.result).to.not.equal(1);
};
}).then(() => {
cleanTestCase();
done();
})
.catch(sqlErr => done(sqlErr));
});
});
describe('creation', () => {
it('should create table', (done) => {
if (!window.indexedDB) {
done(exceptions.IndexedDBNotSupported);
}
sqlCommands.linkDatabaseToIndexedDB(testDatabaseName) // link to database
.then(() => { // create table
const createTableString = 'abc(a NUMBER, b STRING, c DATE)';
return sqlCommands.createTable(createTableString)
.then(() => { // test for table exists in database
const request = window.indexedDB.open(testDatabaseName);
request.onsuccess = function onsuccess(event) {
const transaction = request.result.transaction([testDatabaseName], 'read');
const tableStore = transaction.objectStore(testDatabaseName).get('abc');
tableStore.onsuccess = function suceed(data) {
expect(data).to.equal([]);
};
};
}).catch(sqlErr => done(sqlErr));
}).then(() => {
cleanTestCase();
done();
}).catch(sqlErr => done(sqlErr));
});
});
});
|
JavaScript
| 0.000007 |
@@ -345,16 +345,380 @@
ray();%0A%0A
+function isDatabaseExists(databaseName, callback) %7B%0A const req = indexedDB.open(databaseName);%0A let existed = true;%0A req.onsuccess = function onSuccess() %7B%0A req.result.close();%0A if (!existed) %7B%0A indexedDB.deleteDatabase(databaseName);%0A %7D%0A callback(existed);%0A %7D;%0A req.onupgradeneeded = function onUpgradeNeeded() %7B%0A existed = false;%0A %7D;%0A%7D%0A
function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.