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
|
---|---|---|---|---|---|---|---|
cb7a5d595b14d47349030ed29725ee959cd0f99b
|
Fix syntax error in blueprint's example code
|
blueprints/ember-cli-mirage/files/__root__/mirage/config.js
|
blueprints/ember-cli-mirage/files/__root__/mirage/config.js
|
export default function() {
// These comments are here to help you get started. Feel free to delete them.
/*
Config (with defaults).
Note: these only affect routes defined *after* them!
*/
// this.urlPrefix = ''; // make this `http://localhost:8080`, for example, if your API is on a different server
// this.namespace = ''; // make this `api`, for example, if your API is namespaced
// this.timing = 400; // delay for each request, automatically set to 0 during testing
/*
Route shorthand cheatsheet
*/
/*
GET shorthands
// Collections
this.get('/contacts');
this.get('/contacts', 'users');
this.get('/contacts', ['contacts', 'addresses']);
// Single objects
this.get('/contacts/:id');
this.get('/contacts/:id', 'user');
this.get('/contacts/:id', ['contact', 'addresses']);
*/
/*
POST shorthands
this.post('/contacts');
this.post('/contacts', 'user'); // specify the type of resource to be created
*/
/*
PUT shorthands
this.put('/contacts/:id');
this.put('/contacts/:id', 'user'); // specify the type of resource to be updated
*/
/*
DELETE shorthands
this.del('/contacts/:id');
this.del('/contacts/:id', 'user'); // specify the type of resource to be deleted
// Single object + related resources. Make sure parent resource is first.
this.del('/contacts/:id', ['contact', 'addresses']);
*/
/*
Function fallback. Manipulate data in the db via
- db.{collection}
- db.{collection}.find(id)
- db.{collection}.where(query)
- db.{collection}.update(target, attrs)
- db.{collection}.remove(target)
// Example: return a single object with related models
this.get('/contacts/:id', function(db, request) {
var contactId = +request.params.id;
return {
contact: db.contacts.find(contactId),
addresses: db.addresses.where({contact_id: contactId});
};
});
*/
}
/*
You can optionally export a config that is only loaded during tests
export function testConfig() {
}
*/
|
JavaScript
| 0.00004 |
@@ -1950,17 +1950,16 @@
tactId%7D)
-;
%0A %7D
|
ae747250105b84d8edd97ec4ecefcebbd6ddaf17
|
修复database,js读取不到平台信息的错误
|
install/public/static/js/install/database.js
|
install/public/static/js/install/database.js
|
define(["jquery", 'jquery-ui', "text!templates/database.html"], function($, ui, tpl) {
var Database = function() {
this.isShow = false;
this.$container = $('#step-database');
this.platform = $('#step-environment').data('platform') || 'default';
this.init();
}
//init html
Database.prototype.init = function() {
var $this = this;
this.$container.html(tpl);
this.$nextBtn = $(this.$container).find('.modal-footer > button');
this.$form = this.$container.find('form');
this.$server = $('#server');
this.$db = $('#db');
this.$prefix = $('#prefix');
this.$user = $('#user');
this.$password = $('#password');
this.$console = $('#console');
this.$nextBtn.click(function() {
window.wizard.wizard('next');
});
this.$form.submit(function() {
if ($this.platform == 'default')
{
//do somecheck here
if ($this.$server.val() == '')
{
$this.$server.focus().parent().effect('shake');
return false;
}
if ($this.$db.val() == '')
{
$this.$db.focus().parent().effect('shake');
return false;
}
if ($this.$user.val() == '')
{
$this.$user.focus().parent().effect('shake');
return false;
}
}
$this.checkConnection();
return false;
});
}
//when show
Database.prototype.show = function() {
this.$nextBtn.addClass('disabled');
this.$console.hide();
if (this.platform == 'sae')
{
this.$server.attr('readonly', true);
this.$db.attr('readonly', true);
this.$prefix.attr('readonly', true);
this.$user.attr('readonly', true);
this.$password.attr('readonly', true);
this.$nextBtn.before('<p class="alert alert-error pull-left"><strong>SAE平台无需填写表单,直接点击导入即可.</strong></p>');
this.$nextBtn.prev().effect('shake');
}
this.isShow = true;
}
//on change, check
Database.prototype.change = function(e) {
if ( ! this.isPassed())
{
this.$container.effect('shake');
e.preventDefault();
}
}
// changed
Database.prototype.changed = function() {
//do nothing
}
Database.prototype.isPassed = function() {
return this.$console.find('span.label-info').length == 17;
}
Database.prototype.checkConnection = function() {
var $this = this;
var $logList = this.$console.find('ol').html('');
this.$console.show();
var fields = this.$form.serialize();
var params = fields+'&step=check';
$.ajax({
url: 'index.php/install/database',
async: true,
type: "POST",
dataType: 'json',
data: params,
beforeSend: function (xhr){
$this.$form.find('button').hide();
}
}).done(function (data) {
var css = 'label-info';
if ( ! data.status)
{
css = 'label-important';
}
$.each(data.messages, function (k, v) {
$logList.append('<li><span class="label '+ css +'">'+ v +'</span></li>');
});
if (data.status)
{
$this.installDb();
}
else
{
$logList.append('<li> \
<span class="label label-important">数据库连接失败,可能的原因:</span> \
<ul> \
<li>数据库不存在</li> \
<li>用户名或者密码错误</li> \
</ul> \
</li>');
}
}).always(function() {
$this.$form.find('button').show();
});
}
Database.prototype.installDb = function() {
var steps = Array(
'admins',
'attachments',
'backend_settings',
'cate_fields',
'cate_models',
'fieldtypes',
'menus',
'model_fields',
'models',
'plugins',
'rights',
'roles',
'sessions',
'site_settings',
'validations'
);
var $this = this;
var $logList = this.$console.find('ol');
var fields = this.$form.serialize();
for(var i = 0, len = steps.length; i < len; i++)
{
var params = fields+'&step='+steps[i];
$.ajax({
url: 'index.php/install/database',
async: true,
type: "POST",
dataType: 'json',
data: params,
beforeSend: function (xhr){
$this.$form.find('button').hide();
}
}).done(function (data) {
var css = 'label-info';
if ( ! data.status)
{
css = 'label-important';
}
$.each(data.messages, function (k, v) {
$logList.append('<li><span class="label '+ css +'">'+ v +'</span></li>');
})
$logList.parent().scrollTop(1000);
if ($this.isPassed())
{
$this.$form.find('button').hide();
$this.$nextBtn.removeClass('disabled');
}
}).always(function() {
$this.$form.find('button').show();
});
}
}
var database = new Database();
return database;
}
);
|
JavaScript
| 0 |
@@ -204,90 +204,8 @@
');%0A
- this.platform = $('#step-environment').data('platform') %7C%7C 'default';%0A
@@ -1861,32 +1861,101 @@
console.hide();%0A
+ this.platform = $('#step-environment').data('platform');%0A
if (
|
9cf5e3ab11cff21a8ebf996eb08f1f70012adb72
|
remove untranslated langs
|
packages/docs/src/i18n/locales.js
|
packages/docs/src/i18n/locales.js
|
module.exports = [
{
title: 'English',
locale: 'en',
},
{
title: 'Deutsch',
locale: 'de-DE',
alternate: 'de',
},
{
title: 'Français',
locale: 'fr-FR',
alternate: 'fr',
},
{
title: 'Русский',
locale: 'ru-RU',
alternate: 'ru',
},
{
title: '简体中文',
locale: 'zh-CN',
alternate: 'zh-Hans',
},
{
title: '한국어',
locale: 'ko-KR',
alternate: 'ko',
},
{
title: '日本語',
locale: 'ja-JP',
alternate: 'ja',
},
{
title: 'Help translate',
locale: 'eo-UY',
},
]
|
JavaScript
| 0.000003 |
@@ -69,441 +69,8 @@
%7B%0A
- title: 'Deutsch',%0A locale: 'de-DE',%0A alternate: 'de',%0A %7D,%0A %7B%0A title: 'Fran%C3%A7ais',%0A locale: 'fr-FR',%0A alternate: 'fr',%0A %7D,%0A %7B%0A title: '%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9',%0A locale: 'ru-RU',%0A alternate: 'ru',%0A %7D,%0A %7B%0A title: '%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87',%0A locale: 'zh-CN',%0A alternate: 'zh-Hans',%0A %7D,%0A %7B%0A title: '%ED%95%9C%EA%B5%AD%EC%96%B4',%0A locale: 'ko-KR',%0A alternate: 'ko',%0A %7D,%0A %7B%0A title: '%E6%97%A5%E6%9C%AC%E8%AA%9E',%0A locale: 'ja-JP',%0A alternate: 'ja',%0A %7D,%0A %7B%0A
|
cb895718465d42ca223be7b513fc178757d92319
|
add option to use dynamic origin on fetch requests
|
packages/dynamic-import/client.js
|
packages/dynamic-import/client.js
|
var Module = module.constructor;
var cache = require("./cache.js");
var meteorInstall = require("meteor/modules").meteorInstall;
// Call module.dynamicImport(id) to fetch a module and any/all of its
// dependencies that have not already been fetched, and evaluate them as
// soon as they arrive. This runtime API makes it very easy to implement
// ECMAScript dynamic import(...) syntax.
Module.prototype.dynamicImport = function (id) {
var module = this;
return module.prefetch(id).then(function () {
return getNamespace(module, id);
});
};
// Called by Module.prototype.prefetch if there are any missing dynamic
// modules that need to be fetched.
meteorInstall.fetch = function (ids) {
var tree = Object.create(null);
var versions = Object.create(null);
var dynamicVersions = require("./dynamic-versions.js");
var missing;
function addSource(id, source) {
addToTree(tree, id, makeModuleFunction(id, source, ids[id].options));
}
function addMissing(id) {
addToTree(missing = missing || Object.create(null), id, 1);
}
Object.keys(ids).forEach(function (id) {
var version = dynamicVersions.get(id);
if (version) {
versions[id] = version;
} else {
addMissing(id);
}
});
return cache.checkMany(versions).then(function (sources) {
Object.keys(sources).forEach(function (id) {
var source = sources[id];
if (source) {
addSource(id, source);
} else {
addMissing(id);
}
});
return missing && fetchMissing(missing).then(function (results) {
var versionsAndSourcesById = Object.create(null);
var flatResults = flattenModuleTree(results);
Object.keys(flatResults).forEach(function (id) {
var source = flatResults[id];
addSource(id, source);
var version = dynamicVersions.get(id);
if (version) {
versionsAndSourcesById[id] = {
version: version,
source: source
};
}
});
cache.setMany(versionsAndSourcesById);
});
}).then(function () {
return tree;
});
};
function flattenModuleTree(tree) {
var parts = [""];
var result = Object.create(null);
function walk(t) {
if (t && typeof t === "object") {
Object.keys(t).forEach(function (key) {
parts.push(key);
walk(t[key]);
parts.pop();
});
} else if (typeof t === "string") {
result[parts.join("/")] = t;
}
}
walk(tree);
return result;
}
function makeModuleFunction(id, source, options) {
// By calling (options && options.eval || eval) in a wrapper function,
// we delay the cost of parsing and evaluating the module code until the
// module is first imported.
return function () {
// If an options.eval function was provided in the second argument to
// meteorInstall when this bundle was first installed, use that
// function to parse and evaluate the dynamic module code in the scope
// of the package. Otherwise fall back to indirect (global) eval.
return (options && options.eval || eval)(
// Wrap the function(require,exports,module){...} expression in
// parentheses to force it to be parsed as an expression.
"(" + source + ")\n//# sourceURL=" + id
).apply(this, arguments);
};
}
var secretKey = null;
exports.setSecretKey = function (key) {
secretKey = key;
};
var fetchURL = require("./common.js").fetchURL;
function fetchMissing(missingTree) {
// If the hostname of the URL returned by Meteor.absoluteUrl differs
// from location.host, then we'll be making a cross-origin request here,
// but that's fine because the dynamic-import server sets appropriate
// CORS headers to enable fetching dynamic modules from any
// origin. Browsers that check CORS do so by sending an additional
// preflight OPTIONS request, which may add latency to the first dynamic
// import() request, so it's a good idea for ROOT_URL to match
// location.host if possible, though not strictly necessary.
var url = Meteor.absoluteUrl(fetchURL);
if (secretKey) {
url += "key=" + secretKey;
}
return fetch(url, {
method: "POST",
body: JSON.stringify(missingTree)
}).then(function (res) {
if (! res.ok) throw res;
return res.json();
});
}
function addToTree(tree, id, value) {
var parts = id.split("/");
var lastIndex = parts.length - 1;
parts.forEach(function (part, i) {
if (part) {
tree = tree[part] = tree[part] ||
(i < lastIndex ? Object.create(null) : value);
}
});
}
function getNamespace(module, id) {
var namespace;
module.link(id, {
"*": function (ns) {
namespace = ns;
}
});
// This helps with Babel interop, since we're not just returning the
// module.exports object.
Object.defineProperty(namespace, "__esModule", {
value: true,
enumerable: false
});
return namespace;
}
|
JavaScript
| 0 |
@@ -3378,19 +3378,21 @@
ey;%0A%7D;%0A%0A
-var
+const
fetchUR
@@ -3429,16 +3429,125 @@
chURL;%0A%0A
+function inIframe() %7B%0A try %7B%0A return window.self !== window.top;%0A %7D catch (e) %7B%0A return true;%0A %7D%0A%7D%0A%0A
function
@@ -4127,21 +4127,411 @@
essary.%0A
+%0A
-var
+let url = fetchURL;%0A%0A // Lo and behold!%0A const useDynamicOrigin = Meteor.settings%0A && Meteor.settings.public%0A && Meteor.settings.public.packages%0A && Meteor.settings.public.packages.dynamicImport%0A && Meteor.settings.public.packages.dynamicImport.useDynamicOrigin;%0A%0A if (useDynamicOrigin && location && !inIframe()) %7B%0A url = location.origin.concat(url);%0A %7D else %7B%0A
url = M
@@ -4552,18 +4552,17 @@
Url(
-fetchURL);
+url);%0A %7D
%0A%0A
|
b61fa33416d9533fbbbee1a7b927e1d422b3e692
|
Fix "onChange" is read-only error
|
src/js/components/ui/DateInput.js
|
src/js/components/ui/DateInput.js
|
import React, { PropTypes, Component } from 'react';
export default class DateInput extends Component {
static propTypes = {
label : PropTypes.string.isRequired,
placeholder : PropTypes.string.isRequired,
defaultValue: PropTypes.string
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.state = {
calendar: null
}
}
getValue() {
return this.refs.input.value;
}
componentDidMount() {
let calendar = nekunoApp.calendar({
input : '#calendar-input',
convertToPopover : false,
closeOnSelect : true,
onChange : this.onChange,
value : [this.props.defaultValue],
monthPickerTemplate: '<div class="picker-calendar-month-picker">' +
'<a href="javascript:void(0)" class="link icon-only picker-calendar-prev-month">' +
'<i class="icon icon-prev"></i>' +
'</a>' +
'<span class="current-month-value"></span>' +
'<a href="javascript:void(0)" class="link icon-only picker-calendar-next-month">' +
'<i class="icon icon-next"></i>' +
'</a>' +
'</div>',
yearPickerTemplate : '<div class="picker-calendar-year-picker">' +
'<a href="javascript:void(0)" class="link icon-only picker-calendar-prev-year">' +
'<i class="icon icon-prev"></i>' +
'</a>' +
'<span class="current-year-value"></span>' +
'<a href="javascript:void(0)" class="link icon-only picker-calendar-next-year">' +
'<i class="icon icon-next"></i>' +
'</a>' +
'</div>'
});
this.setState({
calendar: calendar
});
}
onChange() {
const {onChange} = this.props;
typeof onChange == 'function' ? window.setTimeout(onChange, 0) : null;
}
render() {
return (
<li className="date-item">
<div className="item-content date-content">
<div className="item-title label date-label">{this.props.label}</div>
<div className="item-inner">
<div className="item-input">
<input {...this.props} id="calendar-input" ref="input" type="text" placeholder={this.props.placeholder}/>
</div>
</div>
</div>
</li>
);
}
}
|
JavaScript
| 0.000001 |
@@ -264,16 +264,54 @@
s.string
+,%0A onChange : PropTypes.func
%0A %7D;%0A
@@ -1939,54 +1939,26 @@
-const %7BonChange%7D = this.props;%0A typeof
+typeof this.props.
onCh
@@ -1964,16 +1964,17 @@
hange ==
+=
'functi
@@ -1997,16 +1997,27 @@
Timeout(
+this.props.
onChange
|
cb98f4ce831f490e5e85f1cb12b46ab9cb28c7f4
|
Fix conflict
|
src/js/controllers/paperWallet.js
|
src/js/controllers/paperWallet.js
|
angular.module('copayApp.controllers').controller('paperWalletController',
function($scope, $http, $timeout, $rootScope, profileService, go, addressService, isCordova, gettext, bitcore) {
self = this;
var fc = profileService.focusedClient;
var rawTx;
if (isCordova) self.message = "Decrypting a paper wallet could take around 5 minutes on this device. please be patient and keep the app open."
self.onQrCodeScanned = function(data) {
$scope.privateKey = data;
}
self.createTx = function(privateKey, passphrase) {
if (privateKey.charAt(0) != 6) {
var isValidPrivateKey = self.checkPrivateKey(privateKey);
if (isValidPrivateKey != true) return self.error = isValidPrivateKey;
}
self.error = null;
self.scanning = true;
$timeout(function() {
self.getRawTx(privateKey, passphrase, function(err, rawtx, utxos) {
self.scanning = false;
if (err)
self.error = err.toString();
else {
self.balance = (utxos / 1e8).toFixed(8);
rawTx = rawtx;
}
$timeout(function() {
$scope.$apply();
}, 1);
});
}, 100);
};
self.checkPrivateKey = function(privateKey) {
try {
new bitcore.PrivateKey(privateKey, 'livenet');
} catch (err) {
return err.toString();
}
return true;
}
self.getRawTx = function(privateKey, passphrase, cb) {
if (privateKey.charAt(0) == 6) {
fc.decryptBIP38PrivateKey(privateKey, passphrase, null, function(err, privateKey) {
if (err) return cb(err);
fc.getBalanceFromPrivateKey(privateKey, function(err, utxos) {
if (err) return cb(err);
addressService.getAddress(fc.credentials.walletId, true, function(err, destinationAddress) {
if (err) return cb(err);
fc.buildTxFromPrivateKey(privateKey, destinationAddress, null, function(err, tx) {
if (err) return cb(err);
return cb(null, tx.serialize(), utxos);
});
});
});
});
} else {
fc.getBalanceFromPrivateKey(privateKey, function(err, utxos) {
if (err) return cb(err)
addressService.getAddress(fc.credentials.walletId, true, function(err, destinationAddress) {
if (err) return cb(err);
fc.buildTxFromPrivateKey(privateKey, destinationAddress, null, function(err, tx) {
if (err) return cb(err);
return cb(null, tx.serialize(), utxos);
});
});
});
}
};
self.transaction = function() {
self.error = null;
self.sending = true;
$timeout(function() {
self.doTransaction(rawTx).then(function(err, response) {
self.sending = false;
self.goHome();
},
function(err) {
self.sending = false;
self.error = err.toString();
$timeout(function() {
$scope.$apply();
}, 1);
});
}, 100);
};
self.goHome = function() {
go.walletHome();
};
self.doTransaction = function(rawTx) {
return $http.post('https://insight.bitpay.com/api/tx/send', {
rawtx: rawTx
});
};
});
|
JavaScript
| 0.00644 |
@@ -107,20 +107,8 @@
out,
- $rootScope,
pro
@@ -154,17 +154,8 @@
ova,
- gettext,
bit
@@ -241,17 +241,17 @@
Tx;%0A
-%0A
-if (
+self.
isCo
@@ -259,137 +259,21 @@
dova
-) self.message = %22Decrypting a paper wallet could take around 5 minutes on this device. please be patient and keep the app open.%22
+ = isCordova;
%0A%0A
|
209d2dca2d0c56da471cd9cd538a930034006c7a
|
Refactor onChange callback to a prototype method
|
src/js/settings/AutoWootToggle.js
|
src/js/settings/AutoWootToggle.js
|
/**
* Stores the state of the Auto-Woot setting
* @module settings/AutoWootToggle
*/
/**
* AutoWoot setting constructor
* @constructor
* @param {object} toggler - The Toggle API used to keep track of state.
*/
function AutoWoot( toggler, userId ){
this.toggler = toggler || {};
this.userId = userId;
this.localStorageName = "autowoot";
toggler.onChange(function( isOn ){
if( isOn ){
startWooting();
API.on( API.DJ_ADVANCE, this.startWooting.bind(this) );
}else{
API.off( API.DJ_ADVANCE, this.startWooting.bind(this) );
}
});
if( toggler.isOn ){
this.startWooting();
}
/*
this.onChange = function(isOn){
if(isOn){
startWooting();
API.on(API.DJ_ADVANCE, startWooting);
}else{
API.off(API.DJ_ADVANCE, startWooting);
}
};
// Initialize if setting is already turned on
if(this.isOn){
this.onChange(this.isOn);
}
*/
}
/**
* Determines when to start wooting for current song
* @param {object} newSongInfo - Info about the newly started song. (Provided by Plug.dj API)
*/
AutoWoot.prototype.startWooting = function( newSongInfo ){
var wootButton = $('#woot');
// Immediately start wooting if the user just turned the feature on
if( !newSongInfo ){
wootButton.click();
return;
}
// No need to woot for yourself
if( newSongInfo.dj.id === this.userId ){
return;
}
// woot at a random time in the first 35 seconds of each song
var randTimeout = Math.round( 35 * Math.random() ) * 1000;
setTimeout(wootButton.click, randTimeout);
return randTimeout;
};
module.exports = AutoWoot;
|
JavaScript
| 0 |
@@ -363,193 +363,40 @@
nge(
-function( isOn )%7B%0A%09%09if( isOn )%7B%0A%09%09%09startWooting();%0A%09%09%09API.on( API.DJ_ADVANCE,
this.s
-tar
+e
tWoot
-ing.bind(this) );%0A%09%09%7Delse%7B%0A%09%09%09API.off( API.DJ_ADVANCE, this.startWooting
+State
.bind(
+
this
-)
)
-;%0A%09%09%7D%0A%09%7D
+
);%0A%0A
@@ -710,19 +710,360 @@
%0A%09%7D%0A%09*/%0A
-
%7D%0A%0A
+/**%0A * Sets auto-woot to ON/OFF%0A * @param %7Bboolean%7D isOn - true to turn auto-woot on, false to turn it off%0A */%0AAutoWoot.prototype.setWootState = function( isOn )%7B%0A%09if( isOn )%7B%0A%09%09this.startWooting.apply(this);%0A%09%09API.on( API.DJ_ADVANCE, this.startWooting.bind(this) );%0A%09%7Delse%7B%0A%09%09API.off( API.DJ_ADVANCE, this.startWooting.bind(this) );%0A%09%7D%0A%7D;%0A%0A
/**%0A * D
|
f8b51149c33cc2a78a5889dcea7734c50fb16ae4
|
Simplify method
|
hypem-resolver.js
|
hypem-resolver.js
|
// Copyright 2015 Fabian Dietenberger
"use strict";
var request = require('request-promise'),
url = require('url'),
_ = require('lodash');
var hypemResolver = {},
timeout = 5000,
cookie = "AUTH=03%3A406b2fe38a1ab80a2953869a475ff110%3A1412624464%3A1469266248%3A01-DE";
hypemResolver.urlToId = function (hypemUrl) {
var hypemTrackUrl = "http://hypem.com/track/";
var trimmedUrl = _.trim(hypemUrl);
if (_.startsWith(trimmedUrl, hypemTrackUrl)) { // maybe use url
var hypemPath = trimmedUrl.slice(hypemTrackUrl.length);
var hypemId = hypemPath.split("/")[0];
return hypemId;
}
return "";
};
hypemResolver.getById = function (hypemId, callback) {
var options = {
method: 'HEAD',
url: "http://hypem.com/go/sc/" + hypemId,
followRedirect: false,
simple: false,
resolveWithFullResponse: true,
timeout: timeout
};
request(options)
.then(function (response) {
var songUrl = response.headers.location;
if (songUrl === "http://soundcloud.com/not/found" || songUrl === "https://soundcloud.com/not/found") {
getSongFromExternalSource(hypemId, callback);
} else {
// TODO songUrl sometimes ends with /xyz -> remove this
callback(null, songUrl);
}
}).catch(function (reason) {
callback(reason, null);
});
};
function getSongFromExternalSource(hypemId, callback) {
var options = {
method: "GET",
url: "http://hypem.com/track/" + hypemId,
resolveWithFullResponse: true,
headers: {"Cookie": cookie},
timeout: timeout
};
request(options)
.then(function (response) {
var body = response.body.split('\n');
for (var num in body) {
var key;
if (String(body[num]).indexOf('key') != -1) {
// first strike should be the correct one
// fix if hypem changes that
try {
key = JSON.parse(body[num].replace('</script>', '')).tracks[0].key;
var hypemUrl = "http://hypem.com/serve/source/" + hypemId + "/" + key;
getMP3(hypemUrl, callback);
} catch (e) {
// if error happens here, first check the cookie value (maybe refresh)
// if this is not helping, manually check the body of the request for the key value
}
}
}
})
.catch(function (reason) {
callback(new Error("Nothing found: " + reason.options.url));
});
}
function getMP3(hypemLink, callback) {
var options = {
method: "GET",
url: hypemLink,
resolveWithFullResponse: true,
headers: {"Cookie": cookie},
timeout: timeout
};
request(options)
.then(function (response) {
// the request got a json from hypem
// where the link to the mp3 file is saved
var jsonBody = JSON.parse(response.body);
var mp3Url = jsonBody.url;
callback(null, mp3Url);
})
.catch(function (reason) {
callback(new Error("Nothing found: " + reason.options.url));
});
}
module.exports = hypemResolver;
|
JavaScript
| 0.000016 |
@@ -2190,118 +2190,27 @@
-var hypemUrl = %22http://hypem.com/serve/source/%22 + hypemId + %22/%22 + key;%0A getMP3(hypemUrl
+getMP3(hypemId, key
, ca
@@ -2664,20 +2664,28 @@
P3(hypem
-Link
+Id, hypemKey
, callba
@@ -2750,17 +2750,67 @@
rl:
-hypemLink
+%22http://hypem.com/serve/source/%22 + hypemId + %22/%22 + hypemKey
,%0A
|
4982141f985aecdf63cd6b51afaf1920c7fbaa04
|
Remove icon from VoicingHighlight, see https://github.com/phetsims/joist/issues/700
|
js/accessibility/speaker/VoicingHighlight.js
|
js/accessibility/speaker/VoicingHighlight.js
|
// Copyright 2020, University of Colorado Boulder
/**
* A focus highlight for the voicing prototype. Has a different color than the
* default focus highlight and includes an icon to indicate that interacting with
* the object will result in some speech. This highlight may also appear on
* mouse over as well as focus in the SpeakerHighlighter
*
* This should generally be used for otherwise NON interactive things that
* have voicing. Normally focusable things should have the default
* focus highlight.
* @author Jesse Greenberg
*/
import merge from '../../../../phet-core/js/merge.js';
import Text from '../../../../scenery/js/nodes/Text.js';
import Node from '../../../../scenery/js/nodes/Node.js';
import PhetFont from '../../PhetFont.js';
import FontAwesomeNode from '../../../../sun/js/FontAwesomeNode.js';
import sceneryPhet from '../../sceneryPhet.js';
import FocusHighlightFromNode from '../../../../scenery/js/accessibility/FocusHighlightFromNode.js';
class VoicingHighlight extends FocusHighlightFromNode {
constructor( node, options ) {
options = merge( {
outerStroke: 'grey',
innerStroke: 'black'
}, options );
super( node, options );
// icon to indicate that the Node being focused has some content
const bubbleIcon = new FontAwesomeNode( 'comment', { fill: 'grey', scale: 0.55 } );
const rText = new Text( 'R', { font: new PhetFont( { size: 8 } ), fill: 'white', center: bubbleIcon.center.plusXY( 1, -2 ) } );
const speakableIcon = new Node( {
children: [ bubbleIcon, rText ]
} );
node.localBoundsProperty.link( bounds => {
speakableIcon.rightBottom = node.localBounds.rightBottom;
} );
this.addChild( speakableIcon );
}
}
sceneryPhet.register( 'VoicingHighlight', VoicingHighlight );
export default VoicingHighlight;
|
JavaScript
| 0 |
@@ -106,247 +106,124 @@
s a
-different color than the%0A * default focus highlight and includes an icon to indicate that interacting with%0A * the object will result in some speech. This highlight may also appear on%0A * mouse over as well as focus in the SpeakerHighlighter
+unique color to indicate that focus is not around something%0A * that is interactive, but can be read with activation.
%0A *%0A
@@ -296,19 +296,16 @@
ngs that
-%0A *
have vo
@@ -336,16 +336,19 @@
e things
+%0A *
should
@@ -363,19 +363,16 @@
default
-%0A *
focus h
@@ -472,281 +472,8 @@
s';%0A
-import Text from '../../../../scenery/js/nodes/Text.js';%0Aimport Node from '../../../../scenery/js/nodes/Node.js';%0Aimport PhetFont from '../../PhetFont.js';%0Aimport FontAwesomeNode from '../../../../sun/js/FontAwesomeNode.js';%0Aimport sceneryPhet from '../../sceneryPhet.js';%0A
impo
@@ -568,16 +568,64 @@
ode.js';
+%0Aimport sceneryPhet from '../../sceneryPhet.js';
%0A%0Aclass
@@ -835,541 +835,8 @@
s );
-%0A%0A // icon to indicate that the Node being focused has some content%0A const bubbleIcon = new FontAwesomeNode( 'comment', %7B fill: 'grey', scale: 0.55 %7D );%0A const rText = new Text( 'R', %7B font: new PhetFont( %7B size: 8 %7D ), fill: 'white', center: bubbleIcon.center.plusXY( 1, -2 ) %7D );%0A const speakableIcon = new Node( %7B%0A children: %5B bubbleIcon, rText %5D%0A %7D );%0A%0A node.localBoundsProperty.link( bounds =%3E %7B%0A speakableIcon.rightBottom = node.localBounds.rightBottom;%0A %7D );%0A%0A this.addChild( speakableIcon );
%0A %7D
|
9a795296f5534d044090e198c46cceb4a81958a4
|
add ts-nocheck
|
js/buttons/BooleanRectangularToggleButton.js
|
js/buttons/BooleanRectangularToggleButton.js
|
// Copyright 2013-2022, University of Colorado Boulder
/**
* This toggle button uses a boolean Property and a trueNode and falseNode to display its content.
*/
import merge from '../../../phet-core/js/merge.js';
import Tandem from '../../../tandem/js/Tandem.js';
import BooleanToggleNode from '../BooleanToggleNode.js';
import sun from '../sun.js';
import RectangularToggleButton from './RectangularToggleButton.js';
import { Node } from '../../../scenery/js/imports.js'; // eslint-disable-line
class BooleanRectangularToggleButton extends RectangularToggleButton {
/**
* @param {Node} trueNode
* @param {Node} falseNode
* @param {Property.<boolean>} booleanProperty
* @param {Object} [options]
*/
constructor( trueNode, falseNode, booleanProperty, options ) {
options = merge( {
tandem: Tandem.REQUIRED
}, options );
assert && assert( !options.content, 'options.content cannot be set' );
options.content = new BooleanToggleNode( trueNode, falseNode, booleanProperty );
super( false, true, booleanProperty, options );
// @private
this.disposeBooleanRectangularToggleButton = () => {
options.content && options.content.dispose();
};
}
/**
* @public
* @override
*/
dispose() {
this.disposeBooleanRectangularToggleButton();
super.dispose();
}
}
sun.register( 'BooleanRectangularToggleButton', BooleanRectangularToggleButton );
export default BooleanRectangularToggleButton;
|
JavaScript
| 0.000031 |
@@ -48,16 +48,30 @@
Boulder%0A
+// @ts-nocheck
%0A/**%0A *
|
605aa55b395e8f7acd404ffc13af3bcca854ad89
|
Fix for previous commit.
|
js/components/report/question-for-student.js
|
js/components/report/question-for-student.js
|
import React, { PureComponent } from "react";
import Answer from "./answer";
import QuestionHeader from "./question-header";
import SelectionCheckbox from "../../containers/report/selection-checkbox";
import Feedback from "../../containers/report/feedback";
import "../../../css/report/question.less";
import Prompt from "./prompt";
export default class QuestionForStudent extends PureComponent {
render() {
const { question, url, student, answerMap } = this.props;
const studentId = student.get("id");
const answer = answerMap.get(studentId);
return (
<div className={`question for-student ${question.get("visible") ? "" : "hidden"}`}>
<div className="question-header">
<SelectionCheckbox selected={question.get("selected")} questionKey={question.get("id")} trackEvent={trackEvent} />
<QuestionHeader question={question} url={url} />
</div>
<Prompt question={question} />
<Answer answer={answer} question={question} />
<Feedback answer={answer} student={student} question={question} htmlFor="student" />
</div>
);
}
}
|
JavaScript
| 0 |
@@ -450,16 +450,28 @@
nswerMap
+, trackEvent
%7D = thi
|
3b3c649071eae7909d5631a4dcaf9cef355134d1
|
put some template changes in compile
|
js/ext/angular/src/directive/ionicContent.js
|
js/ext/angular/src/directive/ionicContent.js
|
(function() {
'use strict';
angular.module('ionic.ui.content', ['ionic.ui.service'])
/**
* Panel is a simple 100% width and height, fixed panel. It's meant for content to be
* added to it, or animated around.
*/
.directive('pane', function() {
return {
restrict: 'E',
link: function(scope, element, attr) {
element.addClass('pane');
}
};
})
// The content directive is a core scrollable content area
// that is part of many View hierarchies
.directive('content', ['$parse', '$timeout', 'ScrollDelegate', function($parse, $timeout, ScrollDelegate) {
return {
restrict: 'E',
replace: true,
template: '<div class="scroll-content"></div>',
transclude: true,
scope: {
onRefresh: '&',
onRefreshOpening: '&',
onScroll: '&',
onScrollComplete: '&',
refreshComplete: '=',
scroll: '@',
hasScrollX: '@',
hasScrollY: '@',
scrollbarX: '@',
scrollbarY: '@',
scrollEventInterval: '@'
},
compile: function(element, attr, transclude) {
return function($scope, $element, $attr) {
var clone, sc, sv,
addedPadding = false,
c = $element.eq(0);
if(attr.hasHeader == "true") { c.addClass('has-header'); }
if(attr.hasSubheader == "true") { c.addClass('has-subheader'); }
if(attr.hasFooter == "true") { c.addClass('has-footer'); }
if(attr.hasTabs == "true") { c.addClass('has-tabs'); }
// If they want plain overflow scrolling, add that as a class
if($scope.scroll === "false") {
clone = transclude($scope.$parent);
$element.append(clone);
} else if(attr.overflowScroll === "true") {
c.addClass('overflow-scroll');
clone = transclude($scope.$parent);
$element.append(clone);
} else {
sc = document.createElement('div');
sc.className = 'scroll';
if(attr.padding == "true") {
sc.className += ' padding';
addedPadding = true;
}
$element.append(sc);
// Pass the parent scope down to the child
clone = transclude($scope.$parent);
angular.element($element[0].firstElementChild).append(clone);
var refresher = $element[0].querySelector('.scroll-refresher');
var refresherHeight = refresher && refresher.clientHeight || 0;
if(attr.refreshComplete) {
$scope.refreshComplete = function() {
if($scope.scrollView) {
refresher && refresher.classList.remove('active');
$scope.scrollView.finishPullToRefresh();
$scope.$parent.$broadcast('scroll.onRefreshComplete');
}
};
}
// Otherwise, supercharge this baby!
$timeout(function() {
sv = new ionic.views.Scroll({
el: $element[0],
scrollbarX: $scope.$eval($scope.scrollbarX) !== false,
scrollbarY: $scope.$eval($scope.scrollbarY) !== false,
scrollingX: $scope.$eval($scope.hasScrollX) === true,
scrollingY: $scope.$eval($scope.hasScrollY) !== false,
scrollEventInterval: parseInt($scope.scrollEventInterval, 10) || 20,
scrollingComplete: function() {
$scope.onScrollComplete({
scrollTop: this.__scrollTop,
scrollLeft: this.__scrollLeft
});
}
});
// Activate pull-to-refresh
if(refresher) {
sv.activatePullToRefresh(50, function() {
refresher.classList.add('active');
}, function() {
refresher.classList.remove('refreshing');
refresher.classList.remove('active');
}, function() {
refresher.classList.add('refreshing');
$scope.onRefresh();
$scope.$parent.$broadcast('scroll.onRefresh');
});
}
// Register for scroll delegate event handling
ScrollDelegate.register($scope, $element);
// Let child scopes access this
$scope.$parent.scrollView = sv;
});
}
// if padding attribute is true, then add padding if it wasn't added to the .scroll
if(attr.padding == "true" && !addedPadding) {
c.addClass('padding');
}
};
}
};
}])
.directive('refresher', function() {
return {
restrict: 'E',
replace: true,
require: ['^?content', '^?list'],
template: '<div class="scroll-refresher"><div class="ionic-refresher-content"><i class="icon ion-arrow-down-c icon-pulling"></i><i class="icon ion-loading-d icon-refreshing"></i></div></div>',
scope: true
};
})
.directive('scrollRefresher', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div class="scroll-refresher"><div class="scroll-refresher-content" ng-transclude></div></div>'
};
});
})();
|
JavaScript
| 0 |
@@ -984,16 +984,17 @@
%0A %7D,%0A
+%0A
comp
@@ -1040,149 +1040,8 @@
) %7B%0A
- return function($scope, $element, $attr) %7B%0A var clone, sc, sv,%0A addedPadding = false,%0A c = $element.eq(0);%0A%0A
@@ -1065,33 +1065,39 @@
er == %22true%22) %7B
-c
+element
.addClass('has-h
@@ -1099,34 +1099,32 @@
has-header'); %7D%0A
-
if(attr.ha
@@ -1139,33 +1139,39 @@
er == %22true%22) %7B
-c
+element
.addClass('has-s
@@ -1176,34 +1176,32 @@
-subheader'); %7D%0A
-
if(attr.ha
@@ -1213,33 +1213,39 @@
er == %22true%22) %7B
-c
+element
.addClass('has-f
@@ -1251,26 +1251,24 @@
footer'); %7D%0A
-
if(att
@@ -1290,17 +1290,23 @@
rue%22) %7B
-c
+element
.addClas
@@ -1319,24 +1319,168 @@
-tabs'); %7D%0A%0A
+ return function link($scope, $element, $attr) %7B%0A var clone, sc, sv,%0A addedPadding = false,%0A c = $element.eq(0);%0A%0A
// I
@@ -1787,32 +1787,33 @@
$scope.$parent);
+
%0A $elem
@@ -2770,17 +2770,16 @@
%7D%0A%0A
-%0A
@@ -4169,21 +4169,8 @@
);%0A%0A
- %0A
@@ -4269,17 +4269,16 @@
%7D);%0A%0A
-%0A
|
67a8216038b19e82070bd4746c93a17af94c99b5
|
Fix missing icons in weekly BestOf email
|
app/mailers/BestOfDigestMailer.js
|
app/mailers/BestOfDigestMailer.js
|
import { promisifyAll } from 'bluebird';
import createDebug from 'debug';
import { default as juice } from 'juice';
import ReactDOMServer from 'react-dom/server';
import Mailer from '../../lib/mailer';
import { load as configLoader } from '../../config/config';
import { SummaryEmail } from '../views/emails/best-of-digest/SummaryEmail.jsx';
import { fa } from '../views/emails/best-of-digest/assets/font-awesome-base64';
promisifyAll(juice);
const config = configLoader();
export async function sendDailyBestOfEmail(user, data, digestDate) {
const debug = createDebug('freefeed:BestOfDigestMailer');
// TODO: const subject = config.mailer.dailyBestOfDigestEmailSubject
const emailBody = ReactDOMServer.renderToStaticMarkup(SummaryEmail(data));
const emailBodyWithInlineStyles = await juice.juiceResourcesAsync(emailBody, (err, html) => {
debug('Error occurred while trying to inline styles', err, html);
});
const attachments = [fa['fa-heart'], fa['fa-lock'], fa['fa-comment-o'], fa['post-protected']];
return Mailer.sendMail(user, `The best of your FreeFeed for ${digestDate}`, {
digest: {
body: emailBodyWithInlineStyles,
date: digestDate
},
recipient: user,
baseUrl: config.host,
mailerConfig: { subjectTransformation: (subject) => subject, },
}, `${config.appRoot}/app/scripts/views/mailer/dailyBestOfDigest.ejs`, true, attachments);
}
export async function sendWeeklyBestOfEmail(user, data, digestDate) {
const debug = createDebug('freefeed:BestOfDigestMailer');
// TODO: const subject = config.mailer.weeklyBestOfDigestEmailSubject
const emailBody = ReactDOMServer.renderToStaticMarkup(SummaryEmail(data));
const emailBodyWithInlineStyles = await juice.juiceResourcesAsync(emailBody, (err, html) => {
debug('Error occurred while trying to inline styles', err, html);
});
const attachments = [fa['fa-heart'], fa['fa-lock']];
return Mailer.sendMail(user, `The best of your FreeFeed for the week of ${digestDate}`, {
digest: {
body: emailBodyWithInlineStyles,
date: digestDate
},
recipient: user,
baseUrl: config.host,
mailerConfig: { subjectTransformation: (subject) => subject, },
}, `${config.appRoot}/app/scripts/views/mailer/weeklyBestOfDigest.ejs`, true, attachments);
}
|
JavaScript
| 0.00869 |
@@ -1906,16 +1906,58 @@
a-lock'%5D
+, fa%5B'fa-comment-o'%5D, fa%5B'post-protected'%5D
%5D;%0A%0A re
|
8d060053de44d006f6fd1ae4ee9c207539b8bacd
|
Make sure to make the request for a list if the user mousedowns on the last active button
|
public/js/render/saved-history-preview.js
|
public/js/render/saved-history-preview.js
|
// inside a ready call because history DOM is rendered *after* our JS to improve load times.
if (!jsbin.embed) $(function () {
var listLoaded = false;
function loadList() {
if (listLoaded) {
return;
}
listLoaded = true;
$.ajax({
dataType: 'html',
url: '/list',
error: function () {
setTimeout(loadList, 500);
},
success: function (html) {
$body.append(html);
hookUserHistory();
}
});
}
// this code attempts to only call the list ajax request only if
// the user should want to see the list page - most users will
// jump in and jump out of jsbin, and never see this page,
// so let's not send this ajax request.
setTimeout(function () {
var panelsVisible = $body.hasClass('panelsVisible');
if (!panelsVisible) {
loadList();
} else {
// if the user hovers over their profile page or the 'open' link, then load the list then
$('.homebtn').one('hover', loadList);
}
}, 0);
function hookUserHistory() {
if ($('#history').length) (function () {
function render(url) {
if (url.lastIndexOf('/') !== url.length - 1) {
url += '/';
}
iframe.src = url + 'quiet';
iframe.removeAttribute('hidden');
viewing.innerHTML = url;
}
function matchNode(el, nodeName) {
if (el.nodeName == nodeName) {
return el;
} else if (el.nodeName == 'BODY') {
return false;
} else {
return matchNode(el.parentNode, nodeName);
}
}
function visit() {
window.location = this.getAttribute('data-edit-url');
}
var preview = $('#history .preview'),
iframe = $('#history iframe')[0],
bins = $('#history'),
trs = $('#history tr'),
current = null,
viewing = $('#history #viewing')[0],
hoverTimer = null;
// stop iframe load removing focus from our main window
bins.delegate('tr', 'click', visit);
// this is some nasty code - just because I couldn't be
// bothered to bring jQuery to the party.
bins.mouseover(function (event) {
clearTimeout(hoverTimer);
var url, target = event.target;
if (target = matchNode(event.target, 'TR')) {
if (target.getAttribute('data-type') !== 'spacer') {
// target.className = 'hover';
// target.onclick = visit;
url = target.getAttribute('data-url');
if (current !== url) {
hoverTimer = setTimeout(function () {
bins.find('tr').removeClass('selected').filter(target).addClass('selected');
current = url;
render(url);
}, 400);
}
}
}
return false;
});
// Need to replace Z in ISO8601 timestamp with +0000 so prettyDate() doesn't
// completely remove it (and parse the date using the local timezone).
$('#history a[pubdate]').attr('pubdate', function (i, val) {
return val.replace('Z', '+0000');
}).prettyDate();
setInterval(function(){ $('#history td.created a').prettyDate(); }, 30 * 1000);
})();
}
});
|
JavaScript
| 0 |
@@ -1,133 +1,4 @@
-// inside a ready call because history DOM is rendered *after* our JS to improve load times.%0Aif (!jsbin.embed) $(function () %7B%0A%0A
var
@@ -170,24 +170,50 @@
nction () %7B%0A
+ listLoaded = false;%0A
setTim
@@ -338,518 +338,11 @@
%7D);%0A
+
%7D%0A%0A
-// this code attempts to only call the list ajax request only if%0A// the user should want to see the list page - most users will%0A// jump in and jump out of jsbin, and never see this page,%0A// so let's not send this ajax request.%0AsetTimeout(function () %7B%0A var panelsVisible = $body.hasClass('panelsVisible');%0A%0A if (!panelsVisible) %7B%0A loadList();%0A %7D else %7B%0A // if the user hovers over their profile page or the 'open' link, then load the list then%0A $('.homebtn').one('hover', loadList);%0A %7D%0A%7D, 0);%0A%0A
func
@@ -2445,12 +2445,1019 @@
)();%0A%7D%0A%0A
+// inside a ready call because history DOM is rendered *after* our JS to improve load times.%0Aif (!jsbin.embed) $(function () %7B%0A%0A // this code attempts to only call the list ajax request only if%0A // the user should want to see the list page - most users will%0A // jump in and jump out of jsbin, and never see this page,%0A // so let's not send this ajax request.%0A setTimeout(function () %7B%0A var panelsVisible = $body.hasClass('panelsVisible');%0A%0A if (!panelsVisible) %7B%0A loadList();%0A %7D else %7B%0A // if the user hovers over their profile page or the 'open' link, then load the list then%0A $('.homebtn').one('hover', loadList);%0A function panelCloseIntent() %7B%0A var activeCount = $panelButtons.filter('.active').length;%0A if (activeCount === 1 && $(this).hasClass('active')) %7B%0A $panelButtons.unbind('mousedown', panelCloseIntent);%0A loadList();%0A %7D%0A %7D;%0A%0A var $panelButtons = $('#panels a').on('mousedown', panelCloseIntent);%0A %7D%0A %7D, 0);%0A%0A
%7D);
-%0A
|
bae1d12948b69d5d6a4eb4b92dcd231cd89cbddb
|
return null, instead of empty union
|
type-checker/lib/get-union-without-bool.js
|
type-checker/lib/get-union-without-bool.js
|
'use strict';
var JsigAST = require('../../ast/');
module.exports = getUnionWithoutBool;
function getUnionWithoutBool(type, truthy) {
if (type.type !== 'unionType') {
if (truthy && !isAlwaysFalsey(type)) {
return type;
} else if (!truthy && !isAlwaysTruthy(type)) {
return type;
}
return null;
}
var unions = [];
for (var i = 0; i < type.unions.length; i++) {
var t = type.unions[i];
if (
(truthy && !isAlwaysFalsey(t)) ||
(!truthy && !isAlwaysTruthy(t))
) {
unions.push(t);
}
}
if (unions.length === 1) {
return unions[0];
}
return JsigAST.union(unions);
}
// handle more literals like 0 or "" or false
function isAlwaysTruthy(t) {
return !(
(t.type === 'valueLiteral' && t.name === 'undefined') ||
(t.type === 'valueLiteral' && t.name === 'null') ||
(t.type === 'typeLiteral' && t.name === 'String') ||
(t.type === 'typeLiteral' && t.name === 'Boolean') ||
(t.type === 'typeLiteral' && t.name === 'Number')
);
}
function isAlwaysFalsey(t) {
return (t.type === 'valueLiteral' && t.name === 'undefined') ||
(t.type === 'valueLiteral' && t.name === 'null') ||
(t.type === 'typeLiteral' && t.builtin &&
t.name === '%Void%%Uninitialized'
);
}
|
JavaScript
| 0.999365 |
@@ -618,24 +618,83 @@
%7D%0A %7D%0A%0A
+ if (unions.length === 0) %7B%0A return null;%0A %7D%0A%0A
if (unio
|
632435eeaa52df6cec366b6aa115f37f76eb4a2b
|
Fix TOC layout for large screen (#31953)
|
docs/src/modules/components/AppTableOfContents.js
|
docs/src/modules/components/AppTableOfContents.js
|
/* eslint-disable react/no-danger */
import * as React from 'react';
import PropTypes from 'prop-types';
import throttle from 'lodash/throttle';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import NoSsr from '@mui/material/NoSsr';
import Link from 'docs/src/modules/components/Link';
import { useTranslate } from 'docs/src/modules/utils/i18n';
import TableOfContentsBanner from 'docs/src/components/banner/TableOfContentsBanner';
const Nav = styled('nav')(({ theme }) => ({
top: 'var(--MuiDocs-header-height)',
order: 1,
width: 240,
flexShrink: 0,
position: 'sticky',
height: 'calc(100vh - var(--MuiDocs-header-height))',
overflowY: 'auto',
padding: theme.spacing(2, 4, 2, 0),
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
}));
const NavLabel = styled(Typography)(({ theme }) => ({
marginTop: theme.spacing(2),
marginBottom: theme.spacing(1),
paddingLeft: theme.spacing(1.4),
fontSize: theme.typography.pxToRem(11),
fontWeight: theme.typography.fontWeightBold,
textTransform: 'uppercase',
letterSpacing: '.08rem',
color: theme.palette.grey[600],
}));
const NavList = styled(Typography)({
padding: 0,
margin: 0,
listStyle: 'none',
});
const NavItem = styled(Link, {
shouldForwardProp: (prop) => prop !== 'active' && prop !== 'secondary',
})(({ active, secondary, theme }) => {
const activeStyles = {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.primary[200] : theme.palette.primary[600],
color: theme.palette.mode === 'dark' ? theme.palette.primary[300] : theme.palette.primary[600],
'&:hover': {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.primary[600] : theme.palette.primary[400],
color:
theme.palette.mode === 'light' ? theme.palette.primary[600] : theme.palette.primary[400],
},
};
return {
fontSize: theme.typography.pxToRem(13),
padding: theme.spacing(0, 1, 0, secondary ? 2.5 : '10px'),
margin: theme.spacing(0.5, 0, 1, 0),
borderLeft: `1px solid transparent`,
boxSizing: 'border-box',
fontWeight: 500,
'&:hover': {
borderLeftColor:
theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600],
color: theme.palette.mode === 'light' ? theme.palette.grey[600] : theme.palette.grey[200],
},
...(!active && {
color: theme.palette.mode === 'dark' ? theme.palette.grey[500] : theme.palette.text.primary,
}),
// TODO: We probably want `aria-current="location"` instead.
...(active && activeStyles),
'&:active': activeStyles,
};
});
const noop = () => {};
function useThrottledOnScroll(callback, delay) {
const throttledCallback = React.useMemo(
() => (callback ? throttle(callback, delay) : noop),
[callback, delay],
);
React.useEffect(() => {
if (throttledCallback === noop) {
return undefined;
}
window.addEventListener('scroll', throttledCallback);
return () => {
window.removeEventListener('scroll', throttledCallback);
throttledCallback.cancel();
};
}, [throttledCallback]);
}
function flatten(headings) {
const itemsWithNode = [];
headings.forEach((item) => {
itemsWithNode.push(item);
if (item.children.length > 0) {
item.children.forEach((subitem) => {
itemsWithNode.push(subitem);
});
}
});
return itemsWithNode;
}
export default function AppTableOfContents(props) {
const { toc } = props;
const t = useTranslate();
const items = React.useMemo(() => flatten(toc), [toc]);
const [activeState, setActiveState] = React.useState(null);
const clickedRef = React.useRef(false);
const unsetClickedRef = React.useRef(null);
const findActiveIndex = React.useCallback(() => {
// Don't set the active index based on scroll if a link was just clicked
if (clickedRef.current) {
return;
}
let active;
for (let i = items.length - 1; i >= 0; i -= 1) {
// No hash if we're near the top of the page
if (document.documentElement.scrollTop < 200) {
active = { hash: null };
break;
}
const item = items[i];
const node = document.getElementById(item.hash);
if (process.env.NODE_ENV !== 'production') {
if (!node) {
console.error(`Missing node on the item ${JSON.stringify(item, null, 2)}`);
}
}
if (
node &&
node.offsetTop <
document.documentElement.scrollTop + document.documentElement.clientHeight / 8
) {
active = item;
break;
}
}
if (active && activeState !== active.hash) {
setActiveState(active.hash);
}
}, [activeState, items]);
// Corresponds to 10 frames at 60 Hz
useThrottledOnScroll(items.length > 0 ? findActiveIndex : null, 166);
const handleClick = (hash) => (event) => {
// Ignore click for new tab/new window behavior
if (
event.defaultPrevented ||
event.button !== 0 || // ignore everything but left-click
event.metaKey ||
event.ctrlKey ||
event.altKey ||
event.shiftKey
) {
return;
}
// Used to disable findActiveIndex if the page scrolls due to a click
clickedRef.current = true;
unsetClickedRef.current = setTimeout(() => {
clickedRef.current = false;
}, 1000);
if (activeState !== hash) {
setActiveState(hash);
}
};
React.useEffect(
() => () => {
clearTimeout(unsetClickedRef.current);
},
[],
);
const itemLink = (item, secondary) => (
<NavItem
display="block"
href={`#${item.hash}`}
underline="none"
onClick={handleClick(item.hash)}
active={activeState === item.hash}
secondary={secondary}
>
<span dangerouslySetInnerHTML={{ __html: item.text }} />
</NavItem>
);
return (
<Nav aria-label={t('pageTOC')}>
<NoSsr>
<TableOfContentsBanner />
</NoSsr>
{toc.length > 0 ? (
<React.Fragment>
<NavLabel gutterBottom>{t('tableOfContents')}</NavLabel>
<NavList component="ul">
{toc.map((item) => (
<li key={item.text}>
{itemLink(item)}
{item.children.length > 0 ? (
<NavList as="ul">
{item.children.map((subitem) => (
<li key={subitem.text}>{itemLink(subitem, true)}</li>
))}
</NavList>
) : null}
</li>
))}
</NavList>
</React.Fragment>
) : null}
</Nav>
);
}
AppTableOfContents.propTypes = {
toc: PropTypes.array.isRequired,
};
|
JavaScript
| 0 |
@@ -532,38 +532,9 @@
op:
-'var(--MuiDocs-header-height)'
+0
,%0A
@@ -611,50 +611,13 @@
t: '
-calc(100vh - var(--MuiDocs-header-height))
+100vh
',%0A
@@ -661,17 +661,59 @@
spacing(
-2
+'calc(var(--MuiDocs-header-height) + 1rem)'
, 4, 2,
|
076feb591f5c9a8b1982864dad3d3008f7d98cb1
|
Update tests
|
Workshops/21-February-2017/tests/task-1-tests-playlist.js
|
Workshops/21-February-2017/tests/task-1-tests-playlist.js
|
// Generated by CoffeeScript 1.9.3
const { expect } = require('chai');
const result = require('../tasks/task-1')();
describe('Sample exam tests', function () {
describe('PlayList', function () {
describe('With valid input', function () {
it('expect getPlaylist to exist, to be a function and to take a single parameter and to enable chaining', function () {
expect(result.getPlaylist).to.exist;
expect(result.getPlaylist).to.be.a('function');
expect(result.getPlaylist).to.have.length(1);
});
it('expect getPlaylist to return a new playlist instance, with provided name and generated id', function () {
const name = 'Rock and roll';
const playlist = result.getPlaylist(name);
expect(playlist).to.exist;
expect(playlist).to.be.an('object');
expect(playlist.name).to.equal(name);
expect(playlist.id).to.exist;
expect(playlist.id > 0).to.equal(true);
});
it('expect getPlaylist to generate different ids', function () {
const name = 'Rock and roll',
playlist1 = result.getPlaylist(name),
playlist2 = result.getPlaylist(name);
expect(playlist1).to.exist;
expect(playlist2).to.exist;
expect(playlist1.id).not.to.equal(playlist2.id);
});
it('expect playlist.addPlayable() to exists, to be a function and to take a single parameter and to enable chaining', function () {
const name = 'Rock and roll',
playlist = result.getPlaylist(name),
playable = {id: 1, title: 'Banana Rock', author: 'Wombles'};
expect(playlist.addPlayable).to.exist;
expect(playlist.addPlayable).to.be.a('function');
expect(playlist.addPlayable).to.have.length(1);
const returnedPlaylist = playlist.addPlayable(playable);
expect(returnedPlaylist).to.equal(playlist);
});
it('expect playlist.getPlayableById() to exists, to be a function and to take a single parameter', function () {
const name = 'Rock and roll';
const playlist = result.getPlaylist(name);
expect(playlist.getPlayableById).to.exist;
expect(playlist.getPlayableById).to.be.a('function');
expect(playlist.getPlayableById).to.have.length(1);
});
it('expect playlist.addPlayable() to add the playable and playlist.getPlayableById() to retrieve the same playable', function () {
const name = 'Rock and roll',
playlist = result.getPlaylist(name),
playable = {id: 1, title: 'Banana Rock', author: 'Wombles'};
const returnedPlayable = playlist.addPlayable(playable).getPlayableById(1);
expect(returnedPlayable.id).to.equal(playable.id);
expect(returnedPlayable.name).to.equal(playable.name);
expect(returnedPlayable.author).to.equal(playable.author);
});
it('expect playlist.removePlayable() to exists, to be a function and to take a single parameter', function () {
const name = 'Rock and roll',
playlist = result.getPlaylist(name);
expect(playlist.removePlayable).to.exist;
expect(playlist.removePlayable).to.be.a('function');
expect(playlist.removePlayable).to.have.length(1);
});
it('expect playlist.removePlayable() remove the playable with that id', function () {
const name = 'Rock and roll';
const plName = 'Banana Rock';
const plAuthor = 'Wombles';
const playlist = result.getPlaylist(name);
const playable = {id: 1, title: plName, author: plAuthor};
playlist.addPlayable(playable);
playlist.removePlayable(playable);
let gotten = playlist.getPlayableById(1);
expect(gotten).to.be.null;
playlist.addPlayable(playable);
playlist.removePlayable(1);
gotten = playlist.getPlayableById(1);
expect(gotten).to.be.null;
expect(function() { playlist.removePlayable(10); }).to.throw();
});
it('expect playlist.listPlayables() to exists, to be a function and to take 2 parameters', function () {
const name = 'Rock and roll';
const playlist = result.getPlaylist(name);
expect(playlist.listPlayables).to.exist;
expect(playlist.listPlayables).to.be.a('function');
expect(playlist.listPlayables).to.have.length(2);
});
it('expect playlist.listPlayables() to return correct number of playables and to throw errors when invalid data is passed', function () {
const name = 'Hard Rock';
const playlist = result.getPlaylist(name);
for (let i = 0; i < 35; i += 1) {
playlist.addPlayable({id: (i + 1), title: 'Rock' + (9 - (i % 10))});
}
expect(playlist.listPlayables(2, 10).length).to.equal(10);
expect(playlist.listPlayables(3, 10).length).to.equal(5);
expect(function() { playlist.listPlayables(-1, 10) }).to.throw();
expect(function() { playlist.listPlayables(5, 10) }).to.throw();
expect(function() { playlist.listPlayables(1, -1) }).to.throw();
});
});
});
});
|
JavaScript
| 0.000001 |
@@ -1,54 +1,17 @@
-// Generated by CoffeeScript 1.9.3%0A
const %7B
-
expect
-
%7D =
@@ -87,25 +87,25 @@
be('
-Sample exam
+Audio Player
test
-s
', f
|
c6c59740770e68b3899367b0db53a445849e57de
|
Allow to compile only one section through webpack
|
gulp/tasks/common.js
|
gulp/tasks/common.js
|
var argv = require( 'minimist' )( process.argv );
var gulp = require( 'gulp' );
var shell = require( 'gulp-shell' );
var FwdRef = require( 'undertaker-forward-reference' );
// https://github.com/gulpjs/undertaker-forward-reference
// https://github.com/gulpjs/gulp/issues/802
gulp.registry( FwdRef() );
module.exports = function( config, projectBase )
{
config.production = argv.production || false;
config.watching = argv._.indexOf( 'watch' ) !== -1 ? 'initial' : false;
config.noSourcemaps = config.noSourcemaps || false;
config.write = argv.write || false;
config.analyze = argv.analyze || false;
// Whether or not the environment of angular should be production or development.
// Even when not doing prod builds we use the prod environment by default.
// This way it's easy for anyone to build without the GJ dev environment.
// You can pass this flag in to include the dev environment config for angular instead.
config.developmentEnv = argv.development || false;
config.port = config.port || 8080;
config.framework = config.framework || 'angular';
config.sections = config.sections || [];
config.translationSections = config.translationSections || [];
config.sections.push( 'app' );
config.buildSection = argv['section'] || 'app';
config.projectBase = projectBase;
config.buildBaseDir = process.env.BUILD_DIR || './';
config.buildDir = config.buildBaseDir + (config.production ? 'build/prod' : 'build/dev');
config.libDir = 'src/lib/';
config.gjLibDir = 'src/lib/gj-lib-client/';
config.bowerDir = 'src/bower-lib/';
// require( './styles.js' )( config );
// require( './js.js' )( config );
// require( './html.js' )( config );
// require( './fonts.js' )( config );
// require( './markdown.js' )( config );
// require( './images.js' )( config );
require( './translations.js' )( config );
require( './webpack.js' )( config );
// require( './inject.js' )( config );
require( './clean.js' )( config );
// gulp.task( 'extra', function()
// {
// return gulp.src( [
// '!src/bower-lib/**/*',
// 'src/**/*.xml',
// 'src/**/*.mp4',
// 'src/**/*.wav',
// 'src/**/*.ogg',
// 'src/**/*.pdf',
// 'src/**/*.txt',
// 'src/channel.html',
// ], { allowEmpty: true } )
// .pipe( gulp.dest( config.buildDir ) );
// } );
function noop( cb )
{
cb();
}
// This will probably break eventually.
// unwrap exists in gulp, but not in the forward ref thing
// That's why this works, but it could easily not work in future.
function checkHooks( cb )
{
if ( !gulp.task( 'pre' ).unwrap ) {
gulp.task( 'pre', noop );
}
if ( !gulp.task( 'post' ).unwrap ) {
gulp.task( 'post', noop );
}
cb();
}
// gulp.task( 'default', gulp.series(
// checkHooks,
// 'clean:pre',
// 'pre',
// gulp.parallel(
// // 'styles',
// 'js'
// // 'images',
// // 'html',
// // 'fonts',
// // 'markdown',
// // 'extra'
// ),
// 'translations:compile',
// // 'inject',
// 'post',
// 'clean:post'
// ) );
// require( './watch.js' )( config );
gulp.task( 'update-lib', shell.task( [
'cd ' + config.gjLibDir + ' && git pull',
'git add ' + config.gjLibDir,
'git commit -m "Update GJ lib."'
] ) );
gulp.task( 'commit-build', shell.task( [
'git add --all build/prod',
'git commit -m "New build."',
'git push'
] ) );
};
|
JavaScript
| 0 |
@@ -1250,24 +1250,95 @@
%7C%7C 'app';%0A%0A
+%09if ( argv%5B'section'%5D ) %7B%0A%09%09config.sections = %5B argv%5B'section'%5D %5D;%0A%09%7D%0A%0A
%09config.proj
|
466176d2c0ee453325f7044267809e1b32861240
|
update gulp serve task
|
gulp/tasks/server.js
|
gulp/tasks/server.js
|
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')({lazy: false});
var argv = require('yargs').argv;
var sass = require('gulp-sass');
var sassSync = require('node-sass');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var fs = require('fs-extra');
var appDir = 'views/' + argv.view + '/';
var serveDir = '.tmp';
var commonDir = 'views/_common/';
var commonStyles = commonDir + 'styles/';
gulp.task('copyMock', function () {
gulp.src(appDir + 'mock.js')
.pipe(gulp.dest(appDir + serveDir));
});
gulp.task('copyImg', function () {
gulp.src(appDir + 'img/*')
.pipe(gulp.dest(appDir + serveDir + '/img'));
});
gulp.task('copyLib', function () {
if (fs.existsSync(appDir + 'lib')) {
fs.copySync(appDir + 'lib', appDir + serveDir + '/lib');
}
});
gulp.task('css', function () {
gulp.src(appDir + '**/*.scss')
.pipe(sass())
.pipe(gulp.dest(appDir + serveDir));
});
gulp.task('browserify', function () {
return browserify({debug: false})
.add('./' + appDir + 'main.js')
.transform(require('partialify'))
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest(appDir + serveDir));
});
gulp.task('compilePage', ['browserify', 'copyMock', 'css', 'copyImg', 'copyLib'], function () {
var fs = require('fs-extra');
var pageTemplate = fs.readFileSync(commonDir + 'page-template.html', {encoding: 'utf8'});
var page = '';
var cssResult = sassSync.renderSync({
file: commonStyles + 'common.scss',
outputStyle: 'compressed'
});
if (!fs.existsSync(appDir + serveDir)) {
fs.mkdirSync(appDir + serveDir);
}
fs.copySync(commonDir + 'fonts', appDir + 'tmp/fonts');
fs.copySync(commonDir + 'img', appDir + 'tmp/img');
page = pageTemplate.replace('<!--include:css-->',
'<style>' + fs.readFileSync(commonStyles + 'normalize.min.css', {encoding: 'utf8'}) + '</style>' +
'<style>' + fs.readFileSync(commonStyles + 'simplegrid.css', {encoding: 'utf8'}) + '</style>' +
'<style>' + cssResult.css + '</style>');
page = page.replace('<!--include:template-->', fs.readFileSync(appDir + 'main.html', {encoding: 'utf8'}));
fs.writeFileSync(appDir + serveDir + '/index.html', page, {encoding: 'utf8'});
});
gulp.task('watch', function () {
gulp.watch([
appDir + 'tmp/**/*.html',
appDir + 'tmp/**/*.js',
appDir + 'tmp/**/*.css'
], function (event) {
return gulp.src(event.path)
.pipe(plugins.connect.reload());
});
gulp.watch([
//commonDir + 'lib/**/*.js',
appDir + '*.js',
appDir + 'main.html',
appDir + '*.scss',
commonStyles + 'common.scss'
], ['compilePage']);
});
gulp.task('connect', plugins.connect.server({
root: [appDir + serveDir],
port: 9000,
livereload: true
}));
/**
* Runs localhost server with non compiled files
* @return {void}
*/
gulp.task('serve', ['compilePage'], function () {
gulp.start('connect');
gulp.start('watch');
});
|
JavaScript
| 0.000001 |
@@ -1746,20 +1746,28 @@
ppDir +
-'tmp
+serveDir + '
/fonts')
@@ -1812,20 +1812,28 @@
ppDir +
-'tmp
+serveDir + '
/img');%0A
@@ -2410,28 +2410,36 @@
appDir +
-'tmp
+serveDir + '
/**/*.html',
@@ -2452,28 +2452,36 @@
appDir +
-'tmp
+serveDir + '
/**/*.js',%0A
@@ -2500,12 +2500,20 @@
r +
-'tmp
+serveDir + '
/**/
|
5f7db3d03cb3641b464a531f3f68986bd169526e
|
Update autoprefixer to use default settings
|
gulp/tasks/styles.js
|
gulp/tasks/styles.js
|
/* ***** ----------------------------------------------- ***** **
/* ***** Gulp - Styles
/* ***** ----------------------------------------------- ***** */
// Require all development dependencies
var addSrc = require('gulp-add-src'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync'),
cleanCSS = require('gulp-clean-css'),
concat = require('gulp-concat'),
config = require('../config'),
gif = require('gulp-if'),
gulp = require('gulp'),
gutil = require('gulp-util'),
header = require('gulp-header'),
mainBowerFiles = require('main-bower-files'),
plumber = require('gulp-plumber'),
postcss = require('gulp-postcss'),
rename = require('gulp-rename'),
reporter = require('postcss-reporter'),
sass = require('gulp-sass'),
scss = require('postcss-scss'),
size = require('gulp-size'),
sourcemaps = require('gulp-sourcemaps'),
stylelint = require('stylelint'),
isProduction = !!gutil.env.production,
isStaging = !!gutil.env.staging,
isDevelopment = !isProduction && !isStaging;
/*
** -- Lint scss files with Stylelint
** -- Add Bower files to the build
** -- Create sourcemaps if in development mode (use gulp --production or gulp --staging to disable soucemaps)
** -- Compile scss files
** -- Autoprefix necessary properties
** -- Minify
** -- Add ByMattLee header to bundled file
** -- Print bundled file size
** -- Inject styles into page
*/
gulp.task('styles', function () {
var bowerFiles = mainBowerFiles({
filter: '**/*.css',
includeDev: true
});
console.log('Bower Files: ', bowerFiles);
return gulp.src(config.styles.src)
.pipe(plumber())
.pipe(
postcss([
stylelint(),
reporter({
clearMessages: true
})
], {
syntax: scss
})
)
.pipe(gif(isDevelopment, sourcemaps.init()))
.pipe(addSrc.prepend(bowerFiles))
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(cleanCSS())
.pipe(concat('main.css'))
.pipe(rename({
suffix: '.min'
}))
.pipe(header(config.fileHeader.join('\n')))
.pipe(size({
title: 'Compressed File Size:',
showFiles: true
}))
.pipe(gif(isDevelopment, sourcemaps.write('./')))
.pipe(gulp.dest(config.styles.dest))
.pipe(browserSync.stream({
match: '**/*.css'
}));
});
|
JavaScript
| 0 |
@@ -1878,68 +1878,8 @@
xer(
-%7B%0A%09%09%09%09browsers: %5B'last 2 versions'%5D,%0A%09%09%09%09cascade: false%0A%09%09%09%7D
))%0A%09
|
308d4df2abee090cc6af821f167e566145026236
|
update example with filter
|
node_craftsman/mongodb-test/index.js
|
node_craftsman/mongodb-test/index.js
|
'use strict';
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/accounting',
function (err, connection) {
var collection = connection.collection('customers2');
var listDocuments = function (callback) {
// comma separates AND parameters
// $or or
// $lt less than
// $gt greater than
// $lte less than equal
// $gte greater than equal
// $ne not equal
// n is a string, so > and < do not apply to it
// we can use regexp instead
// WHERE n like '#1%'
collection.find(
{
'n': /^#1/
}
,
{
// skip first two, show next and sort by v
// seems sort is done first, then two are skipped then five from the remainng top are shown
'limit': 5,
'skip': 2,
'sort': [ ['v', 'asc'], ['n', 'desc'] ]
}
).toArray(function (err, documents) {
console.dir(documents);
callback();
});
};
var doInsert = function (i) {
if (i < 20) {
var value = Math.floor(Math.random() * 10);
collection.insert(
{'n': '#' + i, 'v': value}, function (err, count) {
doInsert(i + 1);
});
} else {
console.log();
console.log('Inserted', i, 'documents:');
listDocuments(function () {
doUpdateAndDelete();
});
}
};
var doUpdateAndDelete = function () {
collection.update(
{'v': {'$gt': 5}}, // all whose "v > 5"
{'$set': {'valuable': true}},
{'multi': true},
function (err, count) {
console.log();
console.log('Updated', count, 'documents:');
listDocuments(function () {
// remove doesn’t need a multi parameter in order to work on all matched documents
// it does so by default
collection.remove({}, function () {
connection.close();
});
});
});
};
listDocuments(function() {connection.close()});
});
|
JavaScript
| 0 |
@@ -946,71 +946,8 @@
own%0A
- 'limit': 5,%0A 'skip': 2,%0A
@@ -971,17 +971,16 @@
sort': %5B
-
%5B'v', 'a
@@ -998,17 +998,16 @@
'desc'%5D
-
%5D%0A
@@ -2443,32 +2443,1011 @@
%7D);%0A %7D;%0A%0A
+ var doUpdate = function () %7B%0A // increase v by 1 (There is no $dec operation, but we can increase by -1)%0A // there's also $mul for multiply%0A // $rename Renames a field%0A // $unset Removes the specified field from a document%0A // $min Only updates the field if the specified value is less than the existing field value%0A // $max Only updates the field if the specified value is greater than the existing field value%0A // $currentDate Sets the value of a field to current date, either as a Date or a Timestamp%0A // more at http://docs.mongodb.org/manual/reference/operator/update- field/%0A collection.update(%0A %7B'n': /%5E#1/%7D, // those starting with #1%0A %7B'$inc': %7B'v': +1%7D%7D,%0A %7B'multi': true%7D,%0A function (err, count) %7B%0A console.log('%5Cn%5Cn');%0A %7D);%0A %7D;%0A%0A%0A // list documents as is
%0A listDoc
@@ -3461,20 +3461,244 @@
function
+
() %7B
+%0A console.log('%5Cn%5Cn');%0A %7D);%0A%0A // increase v by 1 for those starting with #1%0A doUpdate();%0A%0A // list documents again and close connection%0A listDocuments(function () %7B%0A
connecti
@@ -3707,16 +3707,26 @@
.close()
+;%0A
%7D);%0A%0A%0A
|
e6cca539679c1b84c73572146f9f89380fb60f8a
|
revert incorrect fix for login flickering, try another one that works in monodb mode
|
addons/portal_anonymous/static/src/js/portal_anonymous.js
|
addons/portal_anonymous/static/src/js/portal_anonymous.js
|
openerp.portal_anonymous = function(instance) {
instance.web.Session.include({
load_translations: function() {
var self = this;
// browser_lang can contain 'xx' or 'xx_XX'
// we use the 'xx' to find matching languages installed in the DB
var browser_lang = (navigator.language || navigator.userLanguage).replace('-', '_');
// By default for anonymous session.user_context.lang === 'en_US',
// so do nothing if browser_lang is contained in 'en_US' (like 'en' or 'en_US')
if (this.username === 'anonymous' && this.user_context.lang.indexOf(browser_lang) === -1) {
return (new instance.web.Model('res.lang')).query(['code', 'iso_code'])
.filter([['code', 'like', browser_lang.substring(0, 2).toLowerCase()]]).all()
.then(function(langs) {
// If langs is empty (OpenERP doesn't support the language),
// then don't change session.user_context.lang
if (langs.length > 0) {
// Try to get the right user preference in the browser, else
// get the shortest language returned ('xx' country code) or
// just the first one
var l = _.filter(langs, function(lang) { return lang.code === browser_lang || lang.iso_code === browser_lang; });
if (!_.isEmpty(l)) {
self.user_context.lang = l[0].code;
} else {
l = _.filter(langs, function(lang) {
return lang.iso_code === _.pluck(langs, 'iso_code')
.sort(function(a, b) {
return a.length - b.length;
})[0];
});
self.user_context.lang = l[0].code;
}
}
return self.rpc('/web/webclient/translations', { mods: self.module_list, lang: self.user_context.lang }).done(function(trans) {
instance.web._t.database.set_bundle(trans);
});
});
}
return this._super();
},
});
instance.web.Login.include({
start: function() {
if (!this.session.session_is_valid() && !(this.params.token || this.params.login)) {
this.$el.hide();
this.remember_credentials = false;
// XXX get login/pass from server (via a rpc call) ?
return this.do_login(this.selected_db, 'anonymous', 'anonymous');
} else {
return this._super.apply(this, arguments);
}
},
});
instance.web.UserMenu.include({
init: function(parent) {
this._super(parent);
if (this.session.username == 'anonymous') {
this.template = 'UserMenu.portal_anonymous';
this.do_update = function() {}; // avoid change of avatar
}
},
start: function() {
var self = this;
this._super.apply(this, arguments);
this.$el.find('a.login').click(function() {
var p = self.getParent();
var am = p.action_manager;
p.$el.find('.oe_leftbar, .oe_topbar').hide();
self.session.session_logout().done(function () {
am.do_action({
type:'ir.actions.client',
tag:'login',
target: 'current',
params: {
login_successful: function() {
am.do_action("reload");
}
}
});
});
});
}
});
instance.web.WebClient.include({
check_timezone: function() {
if (this.session.username !== 'anonymous') {
return this._super.apply(this, arguments);
}
return false;
},
});
};
|
JavaScript
| 0.000003 |
@@ -2434,17 +2434,64 @@
-if (!this
+var self = this;%0A var anonymous_mode = (!self
.ses
@@ -2519,20 +2519,20 @@
() && !(
-this
+self
.params.
@@ -2540,20 +2540,20 @@
oken %7C%7C
-this
+self
.params.
@@ -2559,16 +2559,49 @@
.login))
+;%0A if (anonymous_mode)
%7B%0A
@@ -2607,28 +2607,28 @@
-this
+self
.$el.hide();
@@ -2640,24 +2640,139 @@
+%7D%0A
-this
+ return $.when(this._super()).then(function() %7B%0A if (anonymous_mode) %7B%0A self
.remembe
@@ -2786,32 +2786,36 @@
ntials = false;%0A
+
@@ -2883,27 +2883,31 @@
+
return
-this
+self
.do_logi
@@ -2908,20 +2908,20 @@
o_login(
-this
+self
.selecte
@@ -2969,75 +2969,13 @@
-%7D else %7B%0A return this._super.apply(this, arguments);
+ %7D
%0A
@@ -2976,32 +2976,34 @@
%7D%0A %7D
+);
%0A %7D,%0A
|
cfb3c5f3b26194c35d7b37e8b8f0a6f647191dca
|
Set Timeout Counter
|
get-started/promises/data.js
|
get-started/promises/data.js
|
var dataVar = new Promise((resolve, reject) => {
if (false) {
resolve('RESOLVE');
} else {
reject('REJECT');
}
});
dataVar.then((data) => console.log('success: ', data));
dataVar.catch((error) => console.error('error: ', error));
|
JavaScript
| 0 |
@@ -48,16 +48,38 @@
%7B%0A
-if (fals
+setTimeout(() =%3E %7B%0A if (tru
e) %7B
@@ -140,16 +140,28 @@
');%0A %7D%0A
+ %7D, 2000);%0A
%7D);%0A%0Adat
|
b066596f11e8e468af205da69e86fb5ccf52e8f8
|
add more option for nmr annotations
|
eln/nmrGUI.js
|
eln/nmrGUI.js
|
var options1D = {
type: 'rect',
line: 0,
lineLabel: 1,
labelColor: 'red',
strokeColor: 'red',
strokeWidth: '1px',
fillColor: 'green',
width: 0.05,
height: 10,
toFixed: 1,
maxLines: Number.MAX_VALUE,
selectable: true,
fromToc: false
};
var options2D = {type: 'rect', labelColor: 'red', strokeColor: 'red', strokeWidth: '1px', fillColor: 'green', width: '6px', height: '6px'};
/**
* Add missing highlight in ranges array
* A range must have highlights to link the various modules in the visualizer
* If there is no assignment, highlight will be a random number
* If there is an assignment, we will take it from the signals
* @param {Array} ranges - An array of ranges
* @return {boolean}
*/
function ensureRangesHighlight(ranges) {
let isChanged = false;
if (ranges && Array.isArray(ranges)) {
for (let range of ranges) {
if (!range._highlight) {
Object.defineProperty(range, '_highlight', {
value: [],
enumerable: false,
writable: true
});
}
// assignment can only be done at the level of a signal !
if (range.signal) {
let newHighlight = [];
for (let signal of range.signal) {
if (!signal._highlight) {
Object.defineProperty(signal, '_highlight', {
enumerable: false,
writable: true
});
}
signal._highlight = signal.diaID;
if (signal.diaID) {
if (Array.isArray(signal.diaID)) {
for (let diaID of signal.diaID) {
newHighlight.push(diaID);
}
} else {
newHighlight.push(signal.diaID);
}
}
}
// there is some newHighlight and before it was just a random number
// or the highlight changed
if (
(newHighlight.length > 0 && range._highlight.length > 0 && range._highlight[0].match(/^[0-9.]+$/)) ||
(newHighlight.length !== 0 && range._highlight.join('.') !== newHighlight.join('.')) ||
(newHighlight.length === 0 && range._highlight.length > 0 && !range._highlight[0].match(/^[0-9.]+$/))
) {
range._highlight = newHighlight;
isChanged = true;
}
}
// is there is still no highlight ... we just add a random number
if (range._highlight.length === 0) {
range._highlight.push(String(Math.random()));
isChanged = true;
}
}
}
return isChanged;
}
function annotations1D(ranges, optionsG) {
var options = Object.assign({}, options1D, optionsG);
var height = options.height;
var annotations = [];
for (var i = 0; i < ranges.length; i++) {
var currentRange = ranges[i];
var annotation = {};
annotation.info = ranges[i];
annotations.push(annotation);
annotation.line = options.line;
annotation._highlight = options._highlight || currentRange._highlight;
if ((typeof currentRange.to === 'undefined' || typeof currentRange.from === 'undefined' || currentRange.to === currentRange.from) &&
(currentRange.signal && currentRange.signal.length > 0)) {
annotation.position = [{x: currentRange.signal[0].delta - options.width, y: (options.line * height) + 'px'},
{x: currentRange.signal[0].delta + options.width, y: (options.line * height + 8) + 'px'}];
} else {
annotation.position = [
{
x: currentRange.to,
y: (options.line * height) + 'px'
}, {
x: currentRange.from,
y: (options.line * height + 5) + 'px'
}
];
}
annotation.type = options.type;
if (!options.noLabel && currentRange.integral) {
annotation.label = {
text: Number(currentRange.integral).toFixed(options.toFixed),
size: '11px',
anchor: 'middle',
color: options.labelColor,
position: {
x: (annotation.position[0].x + annotation.position[1].x) / 2,
dy: height + 20 + 'px'
}
};
}
annotation.selectable = options.selectable;
annotation.strokeColor = options.strokeColor;
annotation.strokeWidth = options.strokeWidth;
annotation.fillColor = options.fillColor;
}
// we could shift the annotations to prevent overlap
if (options.zigzag) {
annotations.sort((a, b) => b.position[0].x - a.position[0].x);
annotations.forEach((a, i) => {
a.position[0].dy = 25 * (i % 2) + 'px;';
a.position[1].dy = 25 * (i % 2) + 'px;';
if (a.label) {
a.label.position.dy = 25 * (i % 2) + height + 20 + 'px';
}
});
}
return annotations;
}
function annotations2D(zones, optionsG) {
var options = Object.assign({}, options2D, optionsG);
var annotations = [];
for (var k = zones.length - 1; k >= 0; k--) {
var signal = zones[k];
var annotation = {};
annotation.type = options.type;
annotation._highlight = signal._highlight;
if (!annotation._highlight || annotation._highlight.length === 0) {
annotation._highlight = [signal.signalID];
}
signal._highlight = annotation._highlight;
annotation.position = [{x: signal.fromTo[0].from - 0.01, y: signal.fromTo[1].from - 0.01, dx: options.width, dy: options.height},
{x: signal.fromTo[0].to + 0.01, y: signal.fromTo[1].to + 0.01}];
annotation.fillColor = options.fillColor;
annotation.label = {text: signal.remark,
position: {
x: signal.signal[0].delta[0],
y: signal.signal[0].delta[1] - 0.025}
};
if (signal.integral === 1) {
annotation.strokeColor = options.strokeColor;
} else {
annotation.strokeColor = 'rgb(0,128,0)';
}
annotation.strokeWidth = options.strokeWidth;
annotation.width = options.width;
annotation.height = options.height;
annotation.info = signal;
annotations.push(annotation);
}
return annotations;
}
export {annotations2D, annotations1D, ensureRangesHighlight};
|
JavaScript
| 0 |
@@ -3072,18 +3072,80 @@
-var height
+let %7B%0A height,%0A line,%0A dy = %5B0, 0%5D,%0A y%0A %7D
= o
@@ -3146,31 +3146,24 @@
%7D = options
-.height
;%0A var an
@@ -3394,24 +3394,16 @@
.line =
-options.
line;%0A
@@ -4050,32 +4050,45 @@
y:
+ (y) ? y%5B0%5D :
(options.line *
@@ -4094,32 +4094,63 @@
* height) + 'px'
+,%0A dy: dy%5B0%5D
%0A
@@ -4219,16 +4219,29 @@
y:
+ (y) ? y%5B1%5D :
(option
@@ -4263,24 +4263,55 @@
+ 5) + 'px'
+,%0A dy: dy%5B1%5D
%0A
|
a24210c043940213089f75fbea14ec15cc3bf971
|
add breadcrumbs
|
src/components/admin/app-breadcrumbs/Breadcrumbs.js
|
src/components/admin/app-breadcrumbs/Breadcrumbs.js
|
export default {
root: {
path: '/',
displayName: 'Home'
},
routes: [
{
path: 'dashboard',
displayName: 'menu.dashboard'
},
{
path: 'statistics',
displayName: 'menu.statistics',
disabled: true,
children: [
{
path: 'charts',
displayName: 'menu.charts',
},
{
path: 'progress-bars',
displayName: 'menu.progressBars'
},
]
},
{
path: 'forms',
displayName: 'menu.forms',
disabled: true,
children: [
{
path: 'form-elements',
displayName: 'menu.formElements'
},
{
path: 'form-wizards',
displayName: 'menu.formWizards'
},
{
path: 'medium-editor',
displayName: 'menu.mediumEditor'
}
]
},
{
path: 'tables',
displayName: 'menu.tables'
},
{
path: 'ui',
displayName: 'menu.uiElements',
disabled: true,
children: [
{
path: 'typography',
displayName: 'menu.typography'
},
{
path: 'buttons',
displayName: 'menu.buttons'
},
{
path: 'notifications',
displayName: 'menu.notifications'
},
{
path: 'icons',
displayName: 'menu.icons'
},
{
path: 'spinners',
displayName: 'menu.spinners',
},
{
path: 'grid',
displayName: 'menu.grid',
},
{
path: 'modals',
displayName: 'menu.modals'
},
{
path: 'file-upload',
displayName: 'menu.fileUpload'
},
{
path: 'tags',
displayName: 'menu.tags'
},
{
path: 'tree-view',
displayName: 'menu.treeView'
}
]
},
{
path: 'extra',
displayName: 'menu.extra'
},
{
path: 'maps',
displayName: 'menu.maps',
disabled: true,
children: [
{
path: 'google-maps',
displayName: 'Google Maps'
},
{
path: 'yandex-maps',
displayName: 'Yandex Maps'
},
{
path: 'leaflet-maps',
displayName: 'Leaflet Maps',
},
{
path: 'bubble-maps',
displayName: 'Bubble Maps',
},
{
path: 'line-maps',
displayName: 'Line Maps'
}
]
}
]
}
|
JavaScript
| 0.000019 |
@@ -1210,32 +1210,129 @@
%7D,%0A %7B%0A
+ path: 'color-pickers',%0A displayName: 'menu.colorPickers'%0A %7D,%0A %7B%0A
path:
|
6659c189596f0a32f5cf38cfa7ef6f8dee92f08d
|
Update stories
|
src/components/silentBanner/silentBanner.stories.js
|
src/components/silentBanner/silentBanner.stories.js
|
import React from 'react';
import { addStoryInGroup, MID_LEVEL_BLOCKS } from '../../../.storybook/utils';
import { boolean, select, text } from '@storybook/addon-knobs/react';
import SilentBanner from './SilentBanner';
import Link from '../link';
const statusValues = ['info', 'error', 'success', 'warning'];
export default {
title: addStoryInGroup(MID_LEVEL_BLOCKS, 'Silent banners'),
parameters: {
design: {
type: 'figma',
url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=1225%3A0',
},
info: {
propTables: [SilentBanner],
},
},
};
export const basic = () => (
<SilentBanner title={text('Title', 'I am the title of this message')}>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam <Link inherit={false}>nonumy eirmod</Link> tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</SilentBanner>
);
export const dismissable = () => (
<SilentBanner
onClose={() => console.log('onClose click handler')}
title={text('Title', 'I am the title of this message')}
>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam <Link inherit={false}>nonumy eirmod</Link> tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</SilentBanner>
);
export const withActions = () => (
<SilentBanner
primaryAction={{
label: text('Primary action label', 'Primary action'),
onClick: () => console.log('primaryAction.onClick'),
}}
secondaryAction={{
label: text('Secondary action label', 'Secondary action'),
onClick: () => console.log('secondaryAction.onClick'),
}}
title={text('Title', 'I am the title of this message')}
>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam <Link inherit={false}>nonumy eirmod</Link> tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</SilentBanner>
);
export const withStatus = () => (
<SilentBanner
showIcon={boolean('Show icon', false)}
status={select('Status', statusValues, 'success')}
title={text('Title', 'I am the title of this message')}
>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam <Link inherit={false}>nonumy eirmod</Link> tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</SilentBanner>
);
export const fullOption = () => (
<SilentBanner
onClose={() => console.log('onClose click handler')}
primaryAction={{
label: text('Primary action label', 'Primary action'),
onClick: () => console.log('primaryAction.onClick'),
}}
secondaryAction={{
label: text('Secondary action label', 'Secondary action'),
onClick: () => console.log('secondaryAction.onClick'),
}}
showIcon={boolean('Show icon', true)}
status={select('Status', statusValues, 'success')}
title={text('Title', 'I am the title of this message')}
>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam <Link inherit={false}>nonumy eirmod</Link> tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</SilentBanner>
);
|
JavaScript
| 0 |
@@ -648,16 +648,50 @@
ntBanner
+ inline=%7Bboolean('Inline', false)%7D
title=%7B
@@ -740,16 +740,16 @@
age')%7D%3E%0A
-
Lore
@@ -998,32 +998,70 @@
%3CSilentBanner%0A
+ inline=%7Bboolean('Inline', false)%7D%0A
onClose=%7B()
@@ -1427,24 +1427,62 @@
ilentBanner%0A
+ inline=%7Bboolean('Inline', false)%7D%0A
primaryA
@@ -2098,24 +2098,62 @@
ilentBanner%0A
+ inline=%7Bboolean('Inline', false)%7D%0A
showIcon
@@ -2543,32 +2543,32 @@
ption = () =%3E (%0A
-
%3CSilentBanner%0A
@@ -2563,24 +2563,62 @@
ilentBanner%0A
+ inline=%7Bboolean('Inline', false)%7D%0A
onClose=
|
cd0aae5b54f1bd2da20e1a996f382c64b5fb548d
|
Remove need for status section of api.
|
backfeed.js
|
backfeed.js
|
/* backfeed.js */
var Backfeed = (function() {
"use strict";
//define classes to add/remove
const errorStatusClass = 'glyphicon-remove';
const errorGroupClass = 'has-error';
const successStatusClass = 'glyphicon-ok';
const successGroupClass = 'has-success';
const formGroupClass = 'form-group';
const formControlFeedbackClass = 'form-control-feedback';
//attach change listeners to each input
var watchInputs = function(inputList) {
for (let formInput in inputList) {
var currInput = inputList[formInput];
_registerListener('keyup', currInput['input'], currInput['status']);
}
};
//Traverse upward through the DOM to the nearest form group
var _getParentFormGroup = function(element) {
while (! element.parentNode.classList.contains(formGroupClass)) {
element = element.parentNode;
}
return element.parentNode;
};
//Traverse input siblings to find sibling form-control-feedback
var _getSiblingFormControlFeedback = function(element) {
var siblingsInclusive = element.parentNode.children;
var sibling;
for (var i = 0; i < siblingsInclusive.length; i ++) {
sibling = siblingsInclusive[i];
if (sibling !== element) {
if (sibling.classList.contains(formControlFeedbackClass)) {
return sibling;
}
}
}
return null;
};
//Add an event listener to a single form input
var _registerListener = function(eventName, element, status) {
element = document.getElementById(element);
var status = _getSiblingFormControlFeedback(element);
var group = _getParentFormGroup(element);
element.addEventListener(eventName, function invoke(event) {
_updateStatus(event, status, group);
}, false);
};
//update the classes of the usernameInput field
var _updateStatus = function(event, statusTag, groupTag) {
var statusClasses = statusTag.classList;
var groupClasses = groupTag.classList;
if (event.target.checkValidity()) {
//contents are valid
if (!statusClasses.contains(successStatusClass)) {
statusClasses.add(successStatusClass);
}
if (!groupClasses.contains(successGroupClass)) {
groupClasses.add(successGroupClass);
}
if (statusClasses.contains(errorStatusClass)) {
statusClasses.remove(errorStatusClass);
}
if (groupClasses.contains(errorGroupClass)) {
groupClasses.remove(errorGroupClass);
}
} else {
//contents are invalid
if (statusClasses.contains(successStatusClass)) {
statusClasses.remove(successStatusClass);
}
if (groupClasses.contains(successGroupClass)) {
groupClasses.remove(successGroupClass);
}
if (!statusClasses.contains(errorStatusClass)) {
statusClasses.add(errorStatusClass);
}
if (!groupClasses.contains(errorGroupClass)) {
groupClasses.add(errorGroupClass);
}
}
};
return {
watch: watchInputs
}
})();
|
JavaScript
| 0 |
@@ -585,29 +585,8 @@
ut'%5D
-, currInput%5B'status'%5D
);%0A
@@ -1428,24 +1428,16 @@
element
-, status
) %7B%0A
|
ed30fa7cfe659ae082322c1f61a2b372f118bf81
|
Fix login test by mocking device url function.
|
kolibri/core/assets/test/state/store.spec.js
|
kolibri/core/assets/test/state/store.spec.js
|
/* eslint-env mocha */
import Vue from 'vue';
import Vuex from 'vuex';
import assert from 'assert';
import _ from 'lodash';
import * as s from '../../src/state/store';
import * as getters from '../../src/state/getters';
import * as coreActions from '../../src/state/actions';
import * as constants from '../../src/constants';
import sinon from 'sinon';
import urls from 'kolibri.urls';
import { SessionResource } from 'kolibri.resources';
import * as browser from '../../src/utils/browser';
Vue.use(Vuex);
function createStore() {
return new Vuex.Store({
state: _.cloneDeep(s.initialState),
mutations: s.mutations,
getters,
actions: coreActions,
});
}
describe('Vuex store/actions for core module', () => {
describe('error handling', () => {
const errorMessage = 'testError';
Vue.prototype.$formatMessage = () => errorMessage;
it('handleError action updates core state', () => {
const store = createStore();
coreActions.handleError(store, 'catastrophic failure');
assert.equal(store.state.core.error, 'catastrophic failure');
assert.equal(store.state.core.loading, false);
assert.equal(store.state.core.title, errorMessage);
});
it('handleApiError action updates core state', () => {
const store = createStore();
const apiError = { message: 'Too Bad' };
coreActions.handleApiError(store, apiError);
assert(store.state.core.error.match(/Too Bad/));
assert.equal(store.state.core.loading, false);
assert.equal(store.state.core.title, errorMessage);
});
});
describe('kolibriLogin', () => {
let store;
let assignStub;
beforeEach(() => {
store = createStore();
assignStub = sinon.stub(browser, 'redirectBrowser');
});
afterEach(() => {
assignStub.restore();
});
it('successful login', done => {
urls['kolibri:managementplugin:management'] = () => '';
Object.assign(SessionResource, {
createModel: () => ({
save: () =>
Promise.resolve({
// just sending subset of sessionPayload
id: '123',
username: 'e_fermi',
kind: ['cool-guy-user'],
}),
}),
});
function runAssertions() {
const { session } = store.state.core;
assert.equal(session.id, '123');
assert.equal(session.username, 'e_fermi');
assert.deepEqual(session.kind, ['cool-guy-user']);
sinon.assert.called(assignStub);
}
coreActions.kolibriLogin(store, {}).then(runAssertions).then(done, done);
});
it('failed login (401)', done => {
Object.assign(SessionResource, {
createModel: () => ({
save: () => Promise.reject({ status: { code: 401 } }),
}),
});
coreActions
.kolibriLogin(store, {})
.then(() => {
assert.equal(store.state.core.loginError, constants.LoginErrors.INVALID_CREDENTIALS);
})
.then(done, done);
});
it('successful logout', done => {
const clearCachesSpy = sinon.spy();
const getModelStub = sinon.stub().returns({
delete: () => Promise.resolve('goodbye'),
});
Object.assign(SessionResource, {
getModel: getModelStub,
});
coreActions
.kolibriLogout(store)
.then(() => {
sinon.assert.calledWith(getModelStub, 'current');
sinon.assert.called(assignStub);
})
.then(done, done);
});
});
});
|
JavaScript
| 0 |
@@ -1916,16 +1916,85 @@
=%3E '';%0A
+ urls%5B'kolibri:managementplugin:device_management'%5D = () =%3E '';%0A
Ob
|
5558af6e7096d19fc03305847f7c17fa8e5caf23
|
fix fontSize rendering
|
rendering/renderer.js
|
rendering/renderer.js
|
import { promise } from "lively.lang";
import { addOrChangeCSSDeclaration, addOrChangeLinkedCSS } from "./dom-helper.js";
const defaultCSS = `
.no-html-select {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.morph {
/*for aliasing issue in chrome: http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome*/
-webkit-backface-visibility: hidden;
/*include border size in extent of element*/
box-sizing: border-box;
/*don't use dom selection on morphs*/
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.hand {
z-index: 1;
}
.halo {
z-index: 2;
}
.halo-item {
/*FIXME: we shouldn't need to hardcode the size...*/
line-height: 24px !important;
text-align: center;
}
`;
export class Renderer {
static default() { return this._default || new this() }
constructor(world, rootNode, domEnvironment) {
if (!domEnvironment) {
if (typeof window !== "undefined" && typeof document !== "undefined")
domEnvironment = {window, document};
else
throw new Error("Morphic renderer cannot find DOM environment (window / document)!");
}
if (!world || !world.isMorph)
throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
if (!rootNode || !("nodeType" in rootNode))
throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
this.worldMorph = world;
world._isWorld = true; // for world() method
world._renderer = this;
this.rootNode = rootNode;
this.domNode = null;
this.domEnvironment = domEnvironment;
this.renderMap = new WeakMap();
this.renderWorldLoopProcess = null;
}
clear() {
this.stopRenderWorldLoop();
this.domNode && this.domNode.parentNode.removeChild(this.domNode);
this.domNode = null;
this.renderMap = new WeakMap();
this._fontMetric && this._fontMetric.uninstall();
this._fontMetric = null;
}
ensureDefaultCSS() {
return promise.waitFor(3000, () => this.domNode.ownerDocument)
.then(doc => Promise.all([
addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc),
addOrChangeLinkedCSS("lively-font-awesome", System.decanonicalize("lively.morphic/assets/font-awesome/css/font-awesome.css"), doc)]));
}
startRenderWorldLoop() {
this.worldMorph.renderAsRoot(this);
this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
this.startRenderWorldLoop());
}
stopRenderWorldLoop() {
this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
this.renderWorldLoopProcess = null;
}
getNodeForMorph(morph) {
// Hmm, this also finds dom nodes not associated with this renderer, its
// domNode... Is this a problem?
// return this.domNode.ownerDocument.getElementById(morph.id);
// test, for scoped lookup, fixing the issue mentioned above
return this.domNode.querySelector("#" + morph.id);
}
getMorphForNode(node) {
return this.worldMorph ?
this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
null;
}
get fontMetric() {
if (!this._fontMetric) {
this._fontMetric = new FontMetric();
this._fontMetric.install(this.rootNode);
}
return this._fontMetric;
}
}
export class FontMetric {
static default(doc = document) {
if (!this._fontMetric) {
this._fontMetric = new FontMetric();
this._fontMetric.install(doc.body);
}
return this._fontMetric;
}
constructor() {
this.charMap = [];
this.parentElement = null;
this.element = null;
}
install(parentEl = document.body) {
this.parentElement = parentEl;
this.element = document.createElement("div");
this.setMeasureNodeStyles(this.element.style, true);
this.parentElement.appendChild(this.element);
}
uninstall() {
if (this.element) {
this.parentElement.removeChild(this.element);
this.parentElement = null;
this.element = null;
}
}
setMeasureNodeStyles(style, isRoot) {
style.width = style.height = "auto";
style.left = style.top = "0px";
style.visibility = "hidden";
style.position = "absolute";
style.whiteSpace = "pre";
style.font = "inherit";
style.overflow = isRoot ? "hidden" : "visible";
}
measure(fontFamily, fontSize, char) {
var rect = null;
this.element.innerHTML = char;
this.element.style.fontFamily = fontFamily;
this.element.style.fontSize = fontSize;
try {
rect = this.element.getBoundingClientRect();
} catch(e) {
rect = {width: 0, height:0};
};
return {
height: rect.height,
width: rect.width
}
}
sizeFor(fontFamily, fontSize, char) {
if (char.length > 1)
return this.sizeForStr(fontFamily, fontSize, char);
if (!this.charMap[fontFamily]) {
this.charMap[fontFamily] = [];
}
if (!this.charMap[fontFamily][fontSize]) {
this.charMap[fontFamily][fontSize] = [];
}
if (!this.charMap[fontFamily][fontSize][char])
this.charMap[fontFamily][fontSize][char] = this.measure(fontFamily, fontSize, char);
return this.charMap[fontFamily][fontSize][char];
}
sizeForStr(fontFamily, fontSize, str) {
var height = 0, width = 0;
for (let line of str.split('\n')) {
let lineHeight = 0, lineWidth = 0;
for (let char of line.split('')) {
let { height: charHeight, width: charWidth } = this.sizeFor(fontFamily, fontSize, char);
if (charHeight > lineHeight) lineHeight = charHeight;
lineWidth += charWidth;
}
if (lineWidth > width) width = lineWidth;
height += lineHeight || this.sizeFor(fontFamily, fontSize, " ").height;
}
return { height: height, width: width };
}
asciiSizes(fontFamily, fontSize) {
var result = {};
for (var i = 32; i <= 126; i++) {
var char = String.fromCharCode(i);
result[char] = this.sizeFor(fontFamily, fontSize, char)
}
return result;
}
}
|
JavaScript
| 0.000002 |
@@ -4708,16 +4708,23 @@
fontSize
+ + %22px%22
;%0A tr
|
9726d9c1ab7ea2ad5335aba696098a4b7e1cb064
|
Add tests for hypothesis service
|
app/components/hypothesis/service.hypo-hypothesis.test.js
|
app/components/hypothesis/service.hypo-hypothesis.test.js
|
describe('Service: hypo.hypoHypothesis', function() {
'use strict';
var hypoHypothesis;
beforeEach(module('hypo.hypothesis.service'));
beforeEach(inject(function(_hypoHypothesis_) {
hypoHypothesis = _hypoHypothesis_;
}));
var h;
beforeEach(function() {
h = hypoHypothesis(1,2,3,4);
});
it('should be a factory for Hypothesis intances', function() {
expect(h.constructor.name).toBe('Hypothesis');
});
describe('Hypothesis', function() {
it('should have a lower left x value', function() {
expect(h.lowerLeftX).toBe(1);
});
it('should have a lower left y value', function() {
expect(h.lowerLeftY).toBe(2);
});
it('should have a top right x value', function() {
expect(h.topRightX).toBe(3);
});
it('should have a top right y value', function() {
expect(h.topRightY).toBe(4);
});
it('should know when another hypothesis is less generic', function() {
// ...
});
it('should know when another hypothesis is more generic', function() {
// ...
});
it('should know when it is consistent with a given example', function() {
// ...
});
it('should knwo when it is not consistent with a given example', function() {
// ...
});
it('should generalize to accomodate an inconsistent, positive example', function() {
// ...
});
it('should not generalize to accomodate a consistent, positive example', function() {
// ...
});
it('should specialize to accomodate an inconsistent, negative example', function() {
// ...
});
it('should not specialize to accomodate a consistent, negative example', function() {
// ...
});
});
});
|
JavaScript
| 0.000001 |
@@ -466,24 +466,190 @@
unction() %7B%0A
+ var h1, h2, h3;%0A%0A beforeEach(function() %7B%0A h1 = hypoHypothesis(1,1,4,4);%0A h2 = hypoHypothesis(1,1,3,3);%0A h3 = hypoHypothesis(3,3,5,5);%0A %7D);%0A%0A
it('shou
@@ -1069,167 +1069,874 @@
hen
-another hypothesis is less generic', function() %7B%0A // ...%0A %7D);%0A%0A it('should know when another hypothesis is more generic', function() %7B%0A // ...
+it is more generic than another hypothesis', function() %7B%0A expect(h1.isMoreGeneralThan(h2)).toBe(true);%0A %7D);%0A%0A it('should not claim to be more generic than a more specific hypothesis', function() %7B%0A expect(h2.isMoreGeneralThan(h1)).toBe(false);%0A %7D);%0A%0A it('should not claim to be more generic than a non-comparable hypothesis', function() %7B%0A expect(h1.isMoreGeneralThan(h3)).toBe(false);%0A %7D);%0A%0A it('should know when it is more specific than another hypothesis', function() %7B%0A expect(h2.isMoreSpecificThan(h1)).toBe(true);%0A %7D);%0A%0A it('should not claim to be more specific than a more general hypothesis', function() %7B%0A expect(h1.isMoreSpecificThan(h2)).toBe(false);%0A %7D);%0A%0A it('should not claim to be more specific than a non-comparable hypothesis', function() %7B%0A expect(h3.isMoreSpecificThan(h1)).toBe(false);
%0A
|
98df16c76c1b89bddfc4d60544c1e77e1925a5d0
|
Change undefined to null in users.password.server.controller.js
|
app/controllers/users/users.password.server.controller.js
|
app/controllers/users/users.password.server.controller.js
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
config = require('../../../config/config'),
nodemailer = require('nodemailer'),
async = require('async'),
crypto = require('crypto');
var smtpTransport = nodemailer.createTransport(config.mailer.options);
/**
* Forgot for reset password (forgot POST)
*/
exports.forgot = function(req, res, next) {
async.waterfall([
// Generate random token
function(done) {
crypto.randomBytes(20, function(err, buffer) {
var token = buffer.toString('hex');
done(err, token);
});
},
// Lookup user by username
function(token, done) {
if (req.body.username) {
User.findOne({
$or: [
{'username': req.body.username},
{'email': req.body.username}
]
}, '-salt -password', function(err, user) {
if(err){
return res.status(500).send({
message: err.message
});
}
if (!user) {
return res.status(400).send({
message: 'No account with that username or email has been found'
});
} else if (user.provider !== 'local') {
return res.status(400).send({
message: 'It seems like you signed up using your ' + user.provider + ' account'
});
} else {
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
}
});
} else {
return res.status(400).send({
message: 'Username field must not be blank'
});
}
},
function(token, user, done) {
res.render('templates/reset-password-email', {
name: user.displayName || "TellForm User",
appName: config.app.title,
url: 'http://' + req.headers.host + '/auth/reset/' + token
}, function(err, emailHTML) {
done(err, emailHTML, user);
});
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Password Reset',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
if (!err) {
res.send({
message: 'An email has been sent to ' + user.email + ' with further instructions.'
});
} else {
return res.status(400).send({
message: 'Failure sending email'
});
}
done(err);
});
}
], function(err) {
if (err) return next(err);
});
};
/**
* Reset password GET from email token
*/
exports.validateResetToken = function(req, res) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if(err){
return res.status(500).send({
message: err.message
});
}
if (!user) {
return res.redirect('/#!/password/reset/invalid');
}
res.redirect('/#!/password/reset/' + req.params.token);
});
};
/**
* Reset password POST from email token
*/
exports.reset = function(req, res, next) {
// Init Variables
var passwordDetails = req.body;
async.waterfall([
function(done) {
User.findOne({
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: Date.now()
}
}, function(err, user) {
if (!err && user) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
if (err) {
done(err, null)
}
done(null, user);
});
} else {
done('Passwords do not match', null);
}
} else {
done('Password reset token is invalid or has expired.', null)
}
});
},
function(user, done) {
res.render('templates/reset-password-confirm-email', {
name: user.displayName,
appName: config.app.title
}, function(err, emailHTML) {
done(err, emailHTML, user);
});
},
// If valid email, send reset email using service
function(emailHTML, user, done) {
var mailOptions = {
to: user.email,
from: config.mailer.from,
subject: 'Your password has been changed',
html: emailHTML
};
smtpTransport.sendMail(mailOptions, function(err) {
done(err);
});
}
], function(err) {
debugger;
if (err) {
res.status(500).send({
message: err.message || err
});
}
return res.json({
message: "Successfully changed your password!"
});
});
};
/**
* Change Password
*/
exports.changePassword = function(req, res) {
// Init Variables
var passwordDetails = req.body;
if (req.user) {
if (passwordDetails.newPassword) {
User.findById(req.user.id, function(err, user) {
if (!err && user) {
if (user.authenticate(passwordDetails.currentPassword)) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.send({
message: 'Password changed successfully'
});
}
});
}
});
} else {
res.status(400).send({
message: 'Passwords do not match'
});
}
} else {
res.status(400).send({
message: 'Current password is incorrect'
});
}
} else {
res.status(400).send({
message: 'User is not found'
});
}
});
} else {
res.status(400).send({
message: 'Please provide a new password'
});
}
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
|
JavaScript
| 0.000009 |
@@ -3535,25 +3535,20 @@
Token =
-undefined
+null
;%0A%09%09%09%09%09%09
@@ -3579,17 +3579,12 @@
s =
-undefined
+null
;%0A%0A%09
|
3902f3437bb757d2b4d9a56cb7b6d16b3d19e158
|
Add opened class on drop
|
app/javascript/gobierto_admin/modules/terms_controller.js
|
app/javascript/gobierto_admin/modules/terms_controller.js
|
import Sortable from 'sortablejs';
window.GobiertoAdmin.TermsController = (function() {
function TermsController() {}
TermsController.prototype.index = function() {
_handleTermsList();
_handleSortableList();
};
function _handleTermsList() {
// Toggle selected element child
$('.v_container .v_el .icon-caret').click(function(e) {
e.preventDefault();
// ToDo: Don't relay on icon specific names
if($(this).is('.fa-caret-right')) {
$(this).removeClass('fa-caret-right');
$(this).addClass('fa-caret-down');
}
else {
$(this).removeClass('fa-caret-down');
$(this).addClass('fa-caret-right');
}
$(this).parent().parent().parent().parent().find('> .list-group > .v_el').toggleClass('el-opened');
});
// Close all elements except first level
$('.v_container .v_heading .fa-caret-square-right').click(function(e) {
e.preventDefault();
// closes all elements
$('.v_container .v_el_level .v_el').removeClass('el-opened');
$('.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-right');
});
// Open all elements except first level
$('.v_container .v_heading .fa-caret-square-down').click(function(e) {
e.preventDefault();
// Opens all elements
$('.v_container .v_el_level .v_el').addClass('el-opened');
$('.fa-caret-right').removeClass('fa-caret-right').addClass('fa-caret-down');
});
// show only action buttons (edit, delete) when hovering an item
// ToDo: Control that only elements for the item are shown, not for it's parents
$('.v_el').hover(
function(e) {
$(this).first('.v_el_actions').addClass('v_el_active');
},
function(e) {
$(this).first('.v_el_actions').removeClass('v_el_active');
}
);
}
function _getChildrenIds(idsTree, parent, parentId){
let children = $(parent).find('.list-group:eq(0)').children();
children.each((index, child) => {
let childId = child.dataset.id;
if(idsTree[parentId] === undefined) {
idsTree[parentId] = [];
}
idsTree[parentId].push(childId);
idsTree = _getChildrenIds(idsTree, child, childId);
});
return idsTree;
}
function _handleSortableList() {
var nestedSortables = [].slice.call(document.querySelectorAll('.list-group'));
// Loop through each nested sortable element
for (let i = 0; i < nestedSortables.length; i++) {
Sortable.create(nestedSortables[i], {
group: "nested",
animation: 150,
fallbackOnBody: true,
swapThreshold: 0.65,
onEnd: function (e) {
let nullParentId = 0;
let idsTree = {};
$('.list-group:eq(0)').children().each((index, node) => {
// For the parents, we add a special entry with id = 0
// to define the position of the parent nodes
if(idsTree[nullParentId] === undefined) {
idsTree[nullParentId] = [];
}
let nodeId = node.dataset.id;
idsTree[nullParentId].push(nodeId);
idsTree = _getChildrenIds(idsTree, node, nodeId);
});
_requestUpdate('[data-behavior="sortable"]', idsTree);
}
});
}
}
function _requestUpdate(wrapper, positions) {
$.ajax({
url: $(wrapper).data("sortable-target"),
method: "POST",
data: { positions: positions }
});
}
return TermsController;
})();
window.GobiertoAdmin.terms_controller = new GobiertoAdmin.TermsController;
|
JavaScript
| 0.000001 |
@@ -2651,24 +2651,67 @@
ction (e) %7B%0A
+ $(e.item).addClass('el-opened');%0A
le
|
25f9a60cf67627abdf7065d367cfe6b587bf2ce1
|
remove near real time and change to commodities
|
app/javascript/pages/map/components/menu/menu-sections.js
|
app/javascript/pages/map/components/menu/menu-sections.js
|
import forestChange from 'assets/icons/forest-change.svg';
import landCover from 'assets/icons/land-cover.svg';
import landUse from 'assets/icons/land-use.svg';
import climate from 'assets/icons/climate.svg';
import biodiversity from 'assets/icons/biodiversity.svg';
import explore from 'assets/icons/explore.svg';
import searchIcon from 'assets/icons/search.svg';
import Datasets from './components/sections/datasets';
import Explore from './components/sections/explore';
export const bottomSections = [
{
slug: 'explore',
name: 'EXPLORE',
icon: explore,
Component: Explore,
large: true,
section: 'topics'
},
{
slug: 'search',
name: 'SEARCH',
icon: searchIcon
}
];
export default [
{
slug: 'forestChange',
name: 'FOREST CHANGE',
icon: forestChange,
Component: Datasets,
subCategories: [
{
slug: 'deforestationAlerts',
title: 'Deforestation Alerts',
subTitle: 'near real time'
},
{
slug: 'fireAlerts',
title: 'Fire Alerts',
subTitle: 'near real time'
},
{
slug: 'treeCoverChange',
title: 'Tree Cover Change'
}
]
},
{
slug: 'landCover',
name: 'LAND COVER',
icon: landCover,
Component: Datasets,
subCategories: [
{
slug: 'landCover',
title: 'Land Cover'
}
]
},
{
slug: 'landUse',
name: 'LAND USE',
icon: landUse,
Component: Datasets,
subCategories: [
{
slug: 'concessions',
title: 'Concessions'
},
{
slug: 'infrastructure',
title: 'Infrastructure'
},
{
slug: 'people',
title: 'People'
}
]
},
{
slug: 'climate',
name: 'CLIMATE',
icon: climate,
Component: Datasets,
subCategories: [
{
slug: 'carbonDensity',
title: 'Carbon Density'
},
{
slug: 'carbonEmissions',
title: 'Carbon Emissions'
},
{
slug: 'carbonGains',
title: 'Carbon Gains'
}
]
},
{
slug: 'biodiversity',
name: 'BIODIVERSITY',
icon: biodiversity,
Component: Datasets,
subCategories: [
{
slug: 'conservation',
title: 'Conservation'
}
]
}
];
|
JavaScript
| 0.000001 |
@@ -936,44 +936,8 @@
rts'
-,%0A subTitle: 'near real time'
%0A
@@ -1010,44 +1010,8 @@
rts'
-,%0A subTitle: 'near real time'
%0A
@@ -1478,24 +1478,24 @@
tle: 'Co
-ncession
+mmoditie
s'%0A
|
896a87b740c5e228a81f23a11a26845aa849e346
|
Rename parameters from photo to gif to get more meaningful names
|
constants.js
|
constants.js
|
// URLs grom telegram
const TELEGRAM_BASE_URL = 'https://api.telegram.org';
const TELEGRAM_MESSAGE_PHOTO_ENDPOINT = '/sendPhoto';
const DEFAULT_PHOTO_URL = 'http://media.salemwebnetwork.com/cms/CROSSCARDS/17343-im-sorry-pug.jpg';
// URLs from giphy
const {GIPHY_PUBLIC_API_KEY} = require('./variables');
const GIPHY_BASE_URL = 'http://api.giphy.com';
const GIPHY_API_KEY_SUFIX = 'api_key=' + GIPHY_PUBLIC_API_KEY;
const GIPHY_SEARCH_ENDPOINT = '/v1/gifs/search';
module.exports = {
// Giphy
GIPHY_BASE_URL, GIPHY_API_KEY_SUFIX, GIPHY_SEARCH_ENDPOINT,
// Telegram
TELEGRAM_BASE_URL, TELEGRAM_MESSAGE_PHOTO_ENDPOINT, DEFAULT_PHOTO_URL
}
|
JavaScript
| 0 |
@@ -84,37 +84,35 @@
ELEGRAM_MESSAGE_
-PHOTO
+GIF
_ENDPOINT = '/se
@@ -117,12 +117,12 @@
send
-Phot
+Vide
o';%0A
@@ -131,29 +131,27 @@
nst DEFAULT_
-PHOTO
+GIF
_URL = 'http
@@ -157,71 +157,22 @@
p://
-media.salemwebnetwork.com/cms/CROSSCARDS/17343-im-sorry-pug.jpg
+gph.is/1KuNTVa
';%0A%0A
@@ -559,21 +559,19 @@
MESSAGE_
-PHOTO
+GIF
_ENDPOIN
@@ -585,13 +585,11 @@
ULT_
-PHOTO
+GIF
_URL
|
e7f04d006bb00678c0acc145e3d6204cbea73bd1
|
Add RESPONSE_LIMIT in constants.js
|
constants.js
|
constants.js
|
const SUPPORTED_LANGUAGES = [
{
twoLetterCode: "en",
name: "English",
},
{
twoLetterCode: "fr",
name: "French",
},
{
twoLetterCode: "de",
name: "German",
},
{
twoLetterCode: "es",
name: "Spanish",
},
{
twoLetterCode: "zh",
name: "Chinese",
},
{
twoLetterCode: "it",
name: "Italian",
},
{
twoLetterCode: "pt",
name: "Portuguese",
},
];
const ALLOWED_IMAGE_TYPES = ["image/png", "image/jpg", "image/jpeg"];
module.exports = { SUPPORTED_LANGUAGES, ALLOWED_IMAGE_TYPES };
|
JavaScript
| 0.000064 |
@@ -482,16 +482,43 @@
/jpeg%22%5D;
+%0Aconst RESPONSE_LIMIT = 20;
%0A%0Amodule
|
9fd6fd939f455a5a5d0e5a95596ef8646ffe7319
|
check for error codes rather than error message
|
src/javascript/binary/static/virtual_acc_opening.js
|
src/javascript/binary/static/virtual_acc_opening.js
|
pjax_config_page("new_account/virtualws", function(){
return {
onLoad: function() {
if (getCookieItem('login')) {
window.location.href = page.url.url_for('user/my_accountws');
return;
}
Content.populate();
var virtualForm = $('#virtual-form');
if ($.cookie('verify_token')) {
handle_residence_state_ws();
BinarySocket.send({residence_list:1});
var form = document.getElementById('virtual-form');
var errorEmail = document.getElementById('error-email'),
errorPassword = document.getElementById('error-password'),
errorRPassword = document.getElementById('error-r-password'),
errorResidence = document.getElementById('error-residence'),
errorAccount = document.getElementById('error-account-opening');
if (isIE() === false) {
$('#password').on('input', function() {
$('#password-meter').attr('value', testPassword($('#password').val())[0]);
});
} else {
$('#password-meter').remove();
}
if (form) {
virtualForm.submit( function(evt) {
evt.preventDefault();
var email = document.getElementById('email').value,
residence = document.getElementById('residence').value,
password = document.getElementById('password').value,
rPassword = document.getElementById('r-password').value;
Validate.errorMessageResidence(residence, errorResidence);
Validate.errorMessageEmail(email, errorEmail);
Validate.hideErrorMessage(errorAccount);
if (Validate.errorMessagePassword(password, rPassword, errorPassword, errorRPassword) && !Validate.errorMessageEmail(email, errorEmail) && !Validate.errorMessageResidence(residence, errorResidence)){
BinarySocket.init({
onmessage: function(msg){
var response = JSON.parse(msg.data);
if (response) {
var type = response.msg_type;
var error = response.error;
if (type === 'new_account_virtual' && !error){
// set a flag to push to gtm in my_account
localStorage.setItem('new_account', '1');
form.setAttribute('action', '/login');
form.setAttribute('method', 'POST');
virtualForm.unbind('submit');
form.submit();
} else if (type === 'error' || error){
if (/account opening is unavailable/.test(error.message)) {
errorAccount.textContent = error.message;
Validate.displayErrorMessage(errorAccount);
return;
} else if (/email address is already in use/.test(error.message)) {
errorEmail.textContent = Content.localize().textDuplicatedEmail;
} else if (/email address is unverified/.test(error.message)) {
virtualForm.empty();
var errorText = '<p class="errorfield">' + text.localize('The re-entered email address is incorrect.') + '</p>',
noticeText = '<p>' + text.localize('Your token has been invalidated. Please click <a class="pjaxload" href="[_1]">here</a> to restart the verification process.').replace('[_1]', page.url.url_for('')) + '</p>';
virtualForm.html(errorText + noticeText);
return;
} else if (/not strong enough/.test(error.message)) {
errorEmail.textContent = text.localize('Password is not strong enough.');
} else if (error.details && error.details.verification_code) {
if (/required/.test(error.details.verification_code)){
errorEmail.textContent = Content.localize().textTokenMissing;
}
} else if (error.message) {
errorEmail.textContent = error.message;
}
Validate.displayErrorMessage(errorEmail);
}
}
}
});
VirtualAccOpeningData.getDetails(email, password, residence);
}
});
}
} else {
virtualForm.empty();
var errorText = '<p class="errorfield">' + Content.localize().textTokenMissing + '</p>',
noticeText = '<p>' + Content.localize().textClickHereToRestart.replace('[_1]', page.url.url_for('')) + '</p>';
virtualForm.html(errorText + noticeText);
}
}
};
});
|
JavaScript
| 0 |
@@ -2618,60 +2618,285 @@
if (
-/account opening is unavailable/.test(error.message)
+error.code === 'InvalidAccount') %7B%0A errorAccount.textContent = error.message;%0A Validate.displayErrorMessage(errorAccount);%0A return;%0A %7D else if (error.code === 'InsufficientAccountDetails'
) %7B%0A
@@ -3098,61 +3098,40 @@
if (
-/email address is already in use/.test(error.message)
+error.code === 'duplicate email'
) %7B%0A
@@ -3256,57 +3256,73 @@
if (
-/email address is unverified/.test(error.message)
+error.code === 'UnverifiedEmail' or error.code === 'ExpiredToken'
) %7B%0A
@@ -3411,101 +3411,8 @@
= '
-%3Cp class=%22errorfield%22%3E' + text.localize('The re-entered email address is incorrect.') + '%3C/p%3E
',%0A
@@ -3640,32 +3640,259 @@
('')) + '%3C/p%3E';%0A
+ if (error.code === 'UnverifiedEmail') %7B%0A errorText = '%3Cp class=%22errorfield%22%3E' + text.localize('The re-entered email address is incorrect.') + '%3C/p%3E';%0A %7D%0A
@@ -4010,47 +4010,38 @@
if (
-/not strong enough/.test(error.message)
+error.code === 'PasswordError'
) %7B%0A
|
719c2ce691fc5f2ee50f9c73d930393b7020f168
|
Update tags-show.js.es6
|
assets/javascripts/discourse/controllers/tags-show.js.es6
|
assets/javascripts/discourse/controllers/tags-show.js.es6
|
import BulkTopicSelection from 'discourse/mixins/bulk-topic-selection';
export default Ember.Controller.extend(BulkTopicSelection, {
tag: null,
list: null,
canAdminTag: Ember.computed.alias('currentUser.staff'),
isTrue: true,
canFavorite: true,
canFavoriteTag: function() {
const self = this;
var ticker = this.get('tag.id');
console.log('checking can fav stock:' + ticker);
Discourse.ajax("/stock/get_users_favorite_stocks", {
type: "GET",
}).then(function(data) {
console.log(data.stock);
console.log('checking can fav stock step 2:' + ticker);
//data = data.toString;
var favable = true;
for (var i = data.stock.length - 1; i >= 0; i--) {
var stock = jQuery.parseJSON(data.stock[i]);
console.log('checking can fav stock step 3:' + ticker + i);
if(ticker.toLowerCase() == stock.symbol.toLowerCase()) { console.log(ticker + ' is a favorite stock: ' + stock.symbol.toLowerCase()); favable = false; }
}
console.log('favable: ' + favable);
self.set('canFavorite', favable);
console.log('canfavorite: ' + self.get('canFavorite'));
//return self.get('canFavorite');
return favable;
});
//return isStockUsersFavorite(ticker);
}.property('canFavoriteTag'),
loadMoreTopics() {
return this.get('list').loadMore();
},
actions: {
refresh() {
const self = this;
return Discourse.TopicList.list('tags/' + this.get('tag.id')).then(function(list) {
self.set('list', list);
self.resetSelected();
});
},
deleteTag() {
const self = this;
bootbox.confirm(I18n.t('tagging.delete_confirm'), function(result) {
if (!result) { return; }
self.get('tag').destroyRecord().then(function() {
self.transitionToRoute('tags.index');
}).catch(function() {
bootbox.alert(I18n.t('generic_error'));
});
});
},
favoriteTag() {
const self = this;
console.log('favoriting');
//Discourse.ajax("/stock/add_stock_to_users_favorite_stocks?ticker=" + this.get('tag.id') + ".ol", {
// type: "GET",
//});
addStockToUsersFavoriteStocks(this.get('tag.id'));
},
unFavoriteTag() {
const self = this;
console.log('unfavoriting');
removeStockFromUsersFavoriteStocks(this.get('tag.id'));
},
changeTagNotification(id) {
const tagNotification = this.get('tagNotification');
tagNotification.update({ notification_level: id });
}
}
});
|
JavaScript
| 0.000001 |
@@ -981,16 +981,22 @@
+ ' is a
+lready
favorit
@@ -1041,23 +1041,38 @@
));
-favable =
+self.set('canFavorite',
false
+)
; %7D%0A
@@ -1085,32 +1085,34 @@
%7D%0A
+//
console.log('fav
@@ -1145,52 +1145,8 @@
%0A
- self.set('canFavorite', favable);%0A
@@ -1257,24 +1257,26 @@
;%0A
+//
return favab
@@ -1363,19 +1363,16 @@
Favorite
-Tag
'),%0A%0A l
|
c67cc0c900c0fc338bb3cafa5826f974fdf2ccba
|
Update getMatchingWebDataStream selector.
|
assets/js/modules/analytics-4/datastore/webdatastreams.js
|
assets/js/modules/analytics-4/datastore/webdatastreams.js
|
/**
* `modules/analytics-4` data store: webdatastreams.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import invariant from 'invariant';
/**
* Internal dependencies
*/
import API from 'googlesitekit-api';
import Data from 'googlesitekit-data';
import { STORE_NAME } from './constants';
import { CORE_SITE } from '../../../googlesitekit/datastore/site/constants';
import { createFetchStore } from '../../../googlesitekit/data/create-fetch-store';
const { createRegistryControl, createRegistrySelector } = Data;
const fetchGetWebDataStreamsStore = createFetchStore( {
baseName: 'getWebDataStreams',
controlCallback( { propertyID } ) {
return API.get( 'modules', 'analytics-4', 'webdatastreams', { propertyID }, {
useCache: true,
} );
},
reducerCallback( state, webDataStreams, { propertyID } ) {
return {
...state,
webdatastreams: {
...state.webdatastreams,
[ propertyID ]: Array.isArray( webDataStreams ) ? webDataStreams : [],
},
};
},
argsToParams( propertyID ) {
return { propertyID };
},
validateParams( { propertyID } = {} ) {
invariant( propertyID, 'GA4 propertyID is required.' );
},
} );
const fetchCreateWebDataStreamStore = createFetchStore( {
baseName: 'createWebDataStream',
controlCallback( { propertyID } ) {
return API.set( 'modules', 'analytics-4', 'create-webdatastream', { propertyID } );
},
reducerCallback( state, webDataStream, { propertyID } ) {
return {
...state,
webdatastreams: {
...state.webdatastreams,
[ propertyID ]: [
...( state.webdatastreams[ propertyID ] || [] ),
webDataStream,
],
},
};
},
argsToParams( propertyID ) {
return { propertyID };
},
validateParams( { propertyID } = {} ) {
invariant( propertyID, 'GA4 propertyID is required.' );
},
} );
// Actions
const WAIT_FOR_WEBDATASTREAMS = 'WAIT_FOR_WEBDATASTREAMS';
const baseInitialState = {
webdatastreams: {},
};
const baseActions = {
/**
* Creates a new GA4 web data stream.
*
* @since n.e.x.t
*
* @param {string} propertyID GA4 property ID.
* @return {Object} Object with `response` and `error`.
*/
*createWebDataStream( propertyID ) {
invariant( propertyID, 'GA4 propertyID is required.' );
const { response, error } = yield fetchCreateWebDataStreamStore.actions.fetchCreateWebDataStream( propertyID );
return { response, error };
},
/**
* Waits for web data streams to be loaded for a property.
*
* @since n.e.x.t
*
* @param {string} propertyID GA4 property ID.
*/
*waitForWebDataStreams( propertyID ) {
yield {
payload: { propertyID },
type: WAIT_FOR_WEBDATASTREAMS,
};
},
};
const baseControls = {
[ WAIT_FOR_WEBDATASTREAMS ]: createRegistryControl( ( { __experimentalResolveSelect } ) => {
return async ( { payload } ) => {
const { propertyID } = payload;
await __experimentalResolveSelect( STORE_NAME ).getWebDataStreams( propertyID );
};
} ),
};
const baseReducer = ( state, { type } ) => {
switch ( type ) {
default: {
return state;
}
}
};
const baseResolvers = {
*getWebDataStreams( propertyID ) {
const registry = yield Data.commonActions.getRegistry();
// Only fetch web data streams if there are none in the store for the given property.
const webdatastreams = registry.select( STORE_NAME ).getWebDataStreams( propertyID );
if ( webdatastreams === undefined ) {
yield fetchGetWebDataStreamsStore.actions.fetchGetWebDataStreams( propertyID );
}
},
};
const baseSelectors = {
/**
* Gets all GA4 web data streams this account can access.
*
* @since n.e.x.t
*
* @param {Object} state Data store's state.
* @param {string} propertyID The GA4 property ID to fetch web data streams for.
* @return {(Array.<Object>|undefined)} An array of GA4 web data streams; `undefined` if not loaded.
*/
getWebDataStreams( state, propertyID ) {
return state.webdatastreams[ propertyID ];
},
/**
* Gets matched web data stream for selected property.
*
* @since n.e.x.t
*
* @param {Object} state Data store's state.
* @param {string} propertyID The GA4 property ID to find matched web data stream.
* @return {(Object|null|undefined)} A web data stream object if found, otherwise null; `undefined` if web data streams are not loaded.
*/
getMatchingWebDataStream: createRegistrySelector( ( select ) => ( state, propertyID ) => {
const datastreams = select( STORE_NAME ).getWebDataStreams( propertyID );
if ( datastreams === undefined ) {
return undefined;
}
const normalizeURL = ( incomingURL ) => incomingURL
.replace( /^https?:\/\/(www\.)?/i, '' ) // Remove protocol and optional "www." prefix from the URL.
.replace( /\/$/, '' ); // Remove trailing slash.
const url = normalizeURL( select( CORE_SITE ).getReferenceSiteURL() );
for ( const datastream of datastreams ) {
if ( normalizeURL( datastream.defaultUri ) === url ) {
return datastream;
}
}
return null;
} ),
};
const store = Data.combineStores(
fetchGetWebDataStreamsStore,
fetchCreateWebDataStreamStore,
{
initialState: baseInitialState,
actions: baseActions,
controls: baseControls,
reducer: baseReducer,
resolvers: baseResolvers,
selectors: baseSelectors,
}
);
export const initialState = store.initialState;
export const actions = store.actions;
export const controls = store.controls;
export const reducer = store.reducer;
export const resolvers = store.resolvers;
export const selectors = store.selectors;
export default store;
|
JavaScript
| 0 |
@@ -5089,353 +5089,92 @@
%0A%0A%09%09
-const normalizeURL = ( incomingURL ) =%3E incomingURL%0A%09%09%09.replace( /%5Ehttps?:%5C/%5C/(www%5C.)?/i, '' ) // Remove protocol and optional %22www.%22 prefix from the URL.%0A%09%09%09.replace( /%5C/$/, '' ); // Remove trailing slash.%0A%0A%09%09const url = normalizeURL( select( CORE_SITE ).getReferenceSiteURL() );%0A%09%09for ( const datastream of datastreams ) %7B%0A%09%09%09if ( normalizeURL
+for ( const datastream of datastreams ) %7B%0A%09%09%09if ( select( CORE_SITE ).isSiteURLMatch
( da
@@ -5198,16 +5198,8 @@
ri )
- === url
) %7B
|
c5a0a986ae747eeb60619affaaa9042536c5724a
|
Simplify datastore base.
|
assets/js/modules/subscribe-with-google/datastore/base.js
|
assets/js/modules/subscribe-with-google/datastore/base.js
|
/**
* `modules/subscribe-with-google` base data store
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
import { submitChanges, validateCanSubmitChanges } from './settings';
let baseModuleStore = Modules.createModuleStore( 'subscribe-with-google', {
storeName: STORE_NAME,
settingSlugs: [
'publicationName',
'publicationID',
'revenueModel',
'products',
'defaultProductPerPostType',
],
submitChanges,
validateCanSubmitChanges,
} );
// Rename generated pieces to adhere to our convention.
baseModuleStore = ( ( { actions, selectors, ...store } ) => {
const { ...restActions } = actions;
const { ...restSelectors } = selectors;
return {
...store,
actions: {
...restActions,
},
selectors: {
...restSelectors,
},
};
} )( baseModuleStore );
export default baseModuleStore;
|
JavaScript
| 0.000001 |
@@ -859,29 +859,22 @@
';%0A%0A
-let baseModuleStore =
+export default
Mod
@@ -1119,368 +1119,9 @@
es,%0A
+
%7D );%0A
-%0A// Rename generated pieces to adhere to our convention.%0AbaseModuleStore = ( ( %7B actions, selectors, ...store %7D ) =%3E %7B%0A%09const %7B ...restActions %7D = actions;%0A%09const %7B ...restSelectors %7D = selectors;%0A%0A%09return %7B%0A%09%09...store,%0A%09%09actions: %7B%0A%09%09%09...restActions,%0A%09%09%7D,%0A%09%09selectors: %7B%0A%09%09%09...restSelectors,%0A%09%09%7D,%0A%09%7D;%0A%7D )( baseModuleStore );%0A%0Aexport default baseModuleStore;%0A
|
33b03de385c4d845c114ccd764d7d9097d7b6677
|
Fix somewhat broken timing-test by being less anal about output.
|
test/StatsDClient.js
|
test/StatsDClient.js
|
var StatsDClient = require('../lib/statsd-client'),
FakeEphemeralSocket = require('./fakeEphemeralSocket'),
assert = require('chai').assert;
/*global describe before it*/
describe('StatsDClient', function () {
describe('Namespaces', function () {
it('test → test.', function () {
assert.equal(new StatsDClient({prefix: 'test'}).options.prefix, 'test.');
});
it('test. → test.', function () {
assert.equal(new StatsDClient({prefix: 'test.'}).options.prefix, 'test.');
});
});
describe('W. FakeEphemeralSocket', function () {
var c;
function assertGotMessage(m) {
assert(
c._ephemeralSocket.testAndDeleteMessage(m),
"Couldn't find message '" + m + "' among [" + c._ephemeralSocket.sent_messages.join(", ") + "]."
);
}
before(function () {
c = new StatsDClient({
_ephemeralSocket: new FakeEphemeralSocket()
});
});
describe("Counters", function () {
it('.counter("abc", 1) → "abc:1|c', function () {
c.counter('abc', 1);
assertGotMessage('abc:1|c');
});
it('.counter("abc", -5) → "abc:-5|c', function () {
c.counter('abc', -5);
assertGotMessage('abc:-5|c');
});
it('.increment("abc") → "abc:1|c', function () {
c.increment('abc');
assertGotMessage('abc:1|c');
});
it('.increment("abc", 10) → "abc:10|c', function () {
c.increment('abc', 10);
assertGotMessage('abc:10|c');
});
it('.decrement("abc", -2) → "abc:-2|c', function () {
c.decrement('abc', -2);
assertGotMessage('abc:-2|c');
});
it('.decrement("abc", 3) → "abc:-3|c', function () {
c.decrement('abc', -3);
assertGotMessage('abc:-3|c');
});
});
describe('Gauges', function () {
it('.gauge("gauge", 3) → "gauge:-3|g', function () {
c.gauge('gauge', 3);
assertGotMessage('gauge:3|g');
});
});
describe('Sets', function () {
it('.set("foo", 10) → "foo:10|s', function () {
c.set('foo', 10);
assertGotMessage('foo:10|s');
});
});
describe('Timers', function () {
it('.timing("foo", 10) → "foo:10|ms', function () {
c.timing('foo', 10);
assertGotMessage('foo:10|ms');
});
it('.timing("foo", new Date(-25ms)) ~→ "foo:25|ms', function (done) {
var d = new Date();
setTimeout(function () {
c.timing('foo', d);
assert(
c._ephemeralSocket.sent_messages.indexOf('foo:25|ms') !== -1 ||
c._ephemeralSocket.sent_messages.indexOf('foo:26|ms') !== -1
);
done();
}, 25);
});
});
});
});
|
JavaScript
| 0.000001 |
@@ -2745,17 +2745,17 @@
Date(-2
-5
+0
ms)) ~%E2%86%92
@@ -2760,20 +2760,21 @@
%E2%86%92 %22foo:2
-5
+0
%7Cms
+%22
', funct
@@ -2903,16 +2903,17 @@
o', d);%0A
+%0A
@@ -2916,39 +2916,79 @@
-assert(
+// Figure out if we git a right-looking message
%0A
@@ -2984,35 +2984,50 @@
-
+var sentMessages =
c._ephemeralSoc
@@ -3047,39 +3047,97 @@
ages
-.indexOf('foo:25%7Cms') !== -1 %7C%7C
+;%0A assert.lengthOf(sentMessages, 1);%0A assert.match(
%0A
@@ -3161,68 +3161,62 @@
-c._ephemeralSocket.
sent
-_m
+M
essages
-.indexOf('foo:26%7Cms') !== -1
+%5B0%5D,%0A /foo:2%5Cd%5C%7Cms/
%0A
@@ -3283,17 +3283,17 @@
%7D, 2
-5
+0
);%0A
|
8e91a5d9f7f415fe681cf377fc9f6dbf1d0cf1e5
|
add small molecule menu to build
|
client/build/build.js
|
client/build/build.js
|
({
findNestedDependencies: true,
baseUrl: '../js',
dir: '../dist',
mainConfigFile: '../js/main.js',
optimize: 'uglify2',
preserveLicenseComments: false,
removeCombined: true,
modules: [
{
name: "main",
include: ['backbone', 'marionette', 'jquery', 'underscore', 'backgrid', 'backbone.paginator', 'backgrid-paginator',
'views/pages', 'views/filter', 'views/table', 'views/form', 'utils/table',
'modules/types/mx/menu',
'modules/types/tomo/menu',
'modules/types/gen/menu',
'modules/types/saxs/menu',
'modules/types/em/menu',
],
exclude: ['json!config.json'],
},
{
name: "modules/dc/controller",
exclude: ['main'],
},
{
name: "modules/shipment/controller",
exclude: ['main'],
},
{
name: "modules/samples/controller",
exclude: ['main'],
},
{
name: "modules/projects/controller",
exclude: ['main'],
},
/*{
name: "modules/cell/controller",
exclude: ['main'],
},*/
/*{
name: "modules/calendar/controller",
exclude: ['main'],
},*/
{
name: "modules/contact/controller",
exclude: ['main'],
},
/*{
name: "modules/status/controller",
exclude: ['main'],
},*/
/*{
name: "modules/proposal/controller",
exclude: ['main'],
},*/
/*{
name: "modules/assign/controller",
exclude: ['main'],
},*/
{
name: "modules/fault/controller",
exclude: ['main'],
},
{
name: "modules/stats/controller",
exclude: ['main'],
},
{
name: "modules/blstats/controller",
exclude: ['main'],
},
{
name: "modules/mc/controller",
exclude: ['main'],
},
{
name: "modules/admin/controller",
exclude: ['main'],
},
{
name: "modules/imaging/controller",
exclude: ['main'],
},
]
})
|
JavaScript
| 0 |
@@ -705,32 +705,73 @@
types/em/menu',%0A
+ 'modules/types/sm/menu',%0A
|
388a1332e7cc0813c5602b048ce3e56894c1186b
|
Fix scroll to Top
|
reflow-maven-skin/src/main/resources/js/reflow-scroll.js
|
reflow-maven-skin/src/main/resources/js/reflow-scroll.js
|
// Support for smooth scrolling
// (simplified version, taken from http://stackoverflow.com/a/14805098/1173184)
$(window).load(function(){
$('a[href^="#"]:not([href^="#carousel"]):not([data-toggle="dropdown"])').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
});
|
JavaScript
| 0 |
@@ -1,115 +1,4 @@
-// Support for smooth scrolling%0A// (simplified version, taken from http://stackoverflow.com/a/14805098/1173184)
%0A$(w
@@ -123,16 +123,248 @@
n(e) %7B%0A%0A
+ function scrollTo(el, offset, clbck) %7B%0A var pos = (el && el.length %3E 0) ? el.offset().top : 0;%0A pos = pos + (offset ? offset : 0);%0A%0A $('html,body').animate(%7B%0A scrollTop: pos%0A %7D, 300, clbck);%0A %7D;%0A%0A
//
@@ -482,54 +482,96 @@
- // animate%0A $('html, body').animate(%7B%0A
+if (hash === %22%22) %7B%0A // other%0A scrollTo();%0A %7D else %7B%0A // heading click%0A
@@ -580,18 +580,25 @@
scrollTo
-p:
+(%0A
$(this.
@@ -606,29 +606,36 @@
ash)
-.offset().top
+,%0A undefined,
%0A
%7D, 3
@@ -630,23 +630,16 @@
%0A
-%7D, 300,
functio
@@ -643,17 +643,17 @@
tion()%7B%0A
-%0A
+
@@ -683,16 +683,17 @@
to url%0A
+
@@ -731,16 +731,17 @@
+
window.l
@@ -768,19 +768,33 @@
%0A
-%7D);
+ %7D%0A );%0A %7D
%0A%0A %7D);%0A
|
3d390b15a87b49cb5776e9010d1d3417107adfb1
|
Refactor Browser Matcher tests.
|
test/browser.test.js
|
test/browser.test.js
|
describe('Browser', function() {
describe('toBeWindow', function() {
it('should assert value is a host Window object', function() {
expect(window).toBeWindow();
expect({}).not.toBeWindow();
});
});
describe('toBeDocument', function() {
it('should assert value is a host Document object', function() {
expect(window.document).toBeDocument();
expect(document).toBeDocument();
expect({}).not.toBeDocument();
});
});
describe('toBeHtmlCommentNode', function() {
it('should assert value is a DOM reference to an HTML comment', function() {
var div = document.createElement('div');
var comment;
div.innerHTML = '<!-- some comment -->';
comment = div.childNodes[0];
expect(comment).toBeHtmlCommentNode();
});
});
describe('toBeHtmlNode', function() {
it('should assert value is a DOM reference to an HTML element', function() {
var div = document.createElement('div');
expect(div).toBeHtmlNode();
});
});
describe('toBeHtmlTextNode', function() {
it('should assert value is a DOM reference to an HTML text element', function() {
var div = document.createElement('div');
var text;
div.innerHTML = 'some text';
text = div.childNodes[0];
expect(text).toBeHtmlTextNode();
});
});
});
|
JavaScript
| 0 |
@@ -73,106 +73,328 @@
-it('should assert value is a host Window object', function() %7B%0A expect(window).toBeWindow();%0A
+describe('when invoked', function() %7B%0A describe('when value is a host Window object', function() %7B%0A it('should confirm', function() %7B%0A expect(window).toBeWindow();%0A %7D);%0A %7D);%0A describe('when value is NOT a host Window object', function() %7B%0A it('should deny', function() %7B%0A
@@ -420,24 +420,46 @@
BeWindow();%0A
+ %7D);%0A %7D);%0A
%7D);%0A %7D)
@@ -505,33 +505,74 @@
) %7B%0A
-it('should assert
+describe('when invoked', function() %7B%0A describe('when
value i
@@ -607,24 +607,70 @@
unction() %7B%0A
+ it('should confirm', function() %7B%0A
expect
@@ -701,32 +701,36 @@
cument();%0A
+
+
expect(document)
@@ -742,24 +742,161 @@
Document();%0A
+ %7D);%0A %7D);%0A describe('when value is NOT a host Document object', function() %7B%0A it('should deny', function() %7B%0A
expect
@@ -916,24 +916,46 @@
Document();%0A
+ %7D);%0A %7D);%0A
%7D);%0A %7D)
@@ -1008,33 +1008,74 @@
) %7B%0A
-it('should assert
+describe('when invoked', function() %7B%0A describe('when
value i
@@ -1118,32 +1118,68 @@
', function() %7B%0A
+ beforeEach(function() %7B%0A
var div =
@@ -1217,23 +1217,8 @@
- var comment;%0A
@@ -1266,16 +1266,25 @@
;%0A
+ this.
comment
@@ -1296,32 +1296,90 @@
.childNodes%5B0%5D;%0A
+ %7D);%0A it('should confirm', function() %7B%0A
expect(com
@@ -1375,16 +1375,21 @@
expect(
+this.
comment)
@@ -1404,32 +1404,54 @@
lCommentNode();%0A
+ %7D);%0A %7D);%0A
%7D);%0A %7D);%0A%0A
@@ -1493,33 +1493,74 @@
) %7B%0A
-it('should assert
+describe('when invoked', function() %7B%0A describe('when
value i
@@ -1609,36 +1609,73 @@
ction() %7B%0A
-var
+ beforeEach(function() %7B%0A this.
div = document.c
@@ -1691,24 +1691,82 @@
ent('div');%0A
+ %7D);%0A it('should confirm', function() %7B%0A
expect
@@ -1766,16 +1766,21 @@
expect(
+this.
div).toB
@@ -1784,32 +1784,54 @@
toBeHtmlNode();%0A
+ %7D);%0A %7D);%0A
%7D);%0A %7D);%0A%0A
@@ -1881,25 +1881,66 @@
-it('should assert
+describe('when invoked', function() %7B%0A describe('when
val
@@ -1996,24 +1996,60 @@
unction() %7B%0A
+ beforeEach(function() %7B%0A
var di
@@ -2091,20 +2091,8 @@
- var text;%0A
@@ -2128,16 +2128,25 @@
;%0A
+ this.
text = d
@@ -2159,24 +2159,82 @@
ldNodes%5B0%5D;%0A
+ %7D);%0A it('should confirm', function() %7B%0A
expect
@@ -2234,16 +2234,21 @@
expect(
+this.
text).to
@@ -2261,24 +2261,46 @@
TextNode();%0A
+ %7D);%0A %7D);%0A
%7D);%0A %7D)
|
dc249889fc5570f718588ce4f225a0960f41f11c
|
make sure remotes works without notes plugin being loaded #607
|
plugin/remotes/remotes.js
|
plugin/remotes/remotes.js
|
/**
* Touch-based remote controller for your presentation courtesy
* of the folks at http://remotes.io
*/
(function(window){
/**
* Detects if we are dealing with a touch enabled device (with some false positives)
* Borrowed from modernizr: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touch.js
*/
var hasTouch = (function(){
return ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
})();
/**
* Detects if notes are enable and the current page is opened inside an /iframe
* this prevents loading Remotes.io several times
*/
var remotesAndIsNotes = (function(){
return !(window.RevealNotes && self == top);
})();
if(!hasTouch && !remotesAndIsNotes){
head.ready( 'remotes.ne.min.js', function() {
new Remotes("preview")
.on("swipe-left", function(e){ Reveal.right(); })
.on("swipe-right", function(e){ Reveal.left(); })
.on("swipe-up", function(e){ Reveal.down(); })
.on("swipe-down", function(e){ Reveal.up(); })
.on("tap", function(e){ Reveal.next(); })
.on("zoom-out", function(e){ Reveal.toggleOverview(true); })
.on("zoom-in", function(e){ Reveal.toggleOverview(false); })
;
} );
head.js('https://raw.github.com/Remotes/Remotes/master/dist/remotes.ne.min.js');
}
})(window);
|
JavaScript
| 0 |
@@ -650,27 +650,27 @@
var
-rem
+isN
otesAndI
sNotes =
@@ -661,22 +661,21 @@
otesAndI
-sNotes
+frame
= (func
@@ -692,17 +692,17 @@
+
return
-!(
wind
@@ -719,16 +719,18 @@
otes &&
+!(
self ==
@@ -771,19 +771,19 @@
&& !
-rem
+isN
otesAndI
sNot
@@ -778,22 +778,21 @@
otesAndI
-sNotes
+frame
)%7B%0A
|
f7425dbd22b7fe17aa749196e10217d2f335d75e
|
Fix app title & isEditLink
|
src/javascripts/ng-admin/Main/component/service/config/ReferencedList.js
|
src/javascripts/ng-admin/Main/component/service/config/ReferencedList.js
|
/*global define*/
define(function (require) {
'use strict';
var Configurable = require('ng-admin/Main/component/service/config/Configurable'),
Reference = require('ng-admin/Main/component/service/config/Reference'),
utils = require('ng-admin/lib/utils');
function defaultValueTransformer(value) {
return value;
}
var config = {
name: 'myReference',
type: 'referenced-list',
label: 'My list',
edition : 'editable',
list: false,
order: null,
valueTransformer : defaultValueTransformer,
targetReferenceField : null,
targetFields : [],
isEditLink: true,
validation: {
required: false
},
defaultValue: null
};
/**
* @constructor
*/
function ReferencedList(fieldName) {
Reference.apply(this, arguments);
this.config.name = fieldName || 'reference';
this.config.type = 'referenced-list';
this.entries = [];
}
utils.inherits(ReferencedList, Reference);
Configurable(ReferencedList.prototype, config);
/**
* Set or get the type
*
* @param {[Field]} targetFields
* @returns ReferencedList
*/
ReferencedList.prototype.targetFields = function (targetFields) {
if (arguments.length === 0) {
return this.config.targetFields;
}
var i;
this.referencedView.removeFields();
for (i in targetFields) {
this.referencedView.addField(targetFields[i]);
}
this.config.targetFields = targetFields;
return this;
};
/**
* Returns columns used to display the datagrid
*
* @returns {Array}
*/
ReferencedList.prototype.getGridColumns = function () {
var columns = [],
field,
i,
l;
for (i = 0, l = this.config.targetFields.length; i < l; i++) {
field = this.config.targetFields[i];
if (!field.displayed()) {
continue;
}
columns.push({
field: field,
label: field.label()
});
}
return columns;
};
/**
* Returns only referencedList values for an entity (filter it by identifier value)
*
* @param {String|Number} entityId
*
* @returns {ReferencedList}
*/
ReferencedList.prototype.filterEntries = function (entityId) {
var results = [],
entry,
targetRefField = this.targetReferenceField(),
i,
l;
for (i = 0, l = this.entries.length; i < l; i++) {
entry = this.entries[i];
if (entry[targetRefField] == entityId) {
results.push(entry);
}
}
this.entries = results;
return this;
};
ReferencedList.prototype.getEntries = function () {
return this.entries;
};
ReferencedList.prototype.setEntries = function (entries) {
this.entries = entries;
return this;
};
ReferencedList.prototype.clear = function () {
return this;
};
ReferencedList.prototype.processDefaultValue = function() {
if (!this.value && this.defaultValue()) {
this.value = this.defaultValue();
}
};
Configurable(ReferencedList.prototype, config);
return ReferencedList;
});
|
JavaScript
| 0 |
@@ -665,19 +665,20 @@
itLink:
-tru
+fals
e,%0A
|
145007245641f528272b9696034a7687984d4067
|
fix duplicating in certain situations
|
web/app/assets/javascripts/formeditor/duplicate.js
|
web/app/assets/javascripts/formeditor/duplicate.js
|
/* Implements functions that allow duplicating sections and questions.
* It works by copying the DOM of that element and adjusting the IDs
* for that question/section to an unused one. */
/* @public
* Shows/hides the duplication buttons on sections/questions.
* @param enable if the buttons should be shown/hidden */
FormEditor.prototype.toggleDuplicating = function(enable) {
enable = enable === undefined || enable === null ? $("#duplicate").is(":visible") : enable;
if(enable) {
$("#duplicate").hide();
$(".duplicate, #cancel-duplicate").show();
} else {
$("#duplicate").show();
$(".duplicate, #cancel-duplicate").hide();
}
};
/* @public
* Duplicates Question.
* @param link DOM reference to an element inside the question that
* should be duplicated */
FormEditor.prototype.duplicateQuestion = function(link) {
var q = $(link).parents(".question");
this.addUndoStep("duplicating question " + q.children("h6").data("db-column"));
this.duplicate(q, "Question", "questions");
};
/* @public
* Duplicates Section.
* @param link DOM reference to an element inside the section that
* should be duplicated */
FormEditor.prototype.duplicateSection = function(link) {
var s = $(link).parents(".section");
this.addUndoStep("duplicating section " + s.children("h5").data("title"));
this.duplicate(s, "Section", "sections");
};
/* @private
* Handles copying the DOM element as well as replacing the old IDs with
* unused ones.
* @param DOM element which should be copied
* @param Type/AbstractForm Class of equivalent of DOM element being
* copied. Required to determine correct path from the hidden
* element (…/rubyobject).
* @param Name of the part in the path that preceeds the n-th question
* or section. Usually multiple and lower-case of type. E.g.
* /pages/0/sections/1/questions/2/ → "sections" if a section
* is to be duplicated */
FormEditor.prototype.duplicate = function(elm, type, pathGroup) {
var r = new RegExp("/" + pathGroup + "/([0-9]+)/");
// find new, not yet used id
var lastPath = elm.parent().find("[type=hidden][value="+type+"][id^='/']").last().attr("id").match(r),
oldPath = "/" + pathGroup + "/" + lastPath[1] + "/",
pos = parseInt(lastPath[1])+1;
while(true) {
newPath = "/" + pathGroup + "/" + pos + "/";
var check = document.getElementById(lastPath[0].replace(oldPath, newPath));
if(check === null) break;
pos++;
}
// clone and update id/for attributes
var newElm = elm.clone();
newElm.find("[id^='/']").each(function(pos, elm) {
$(elm).attr("id", $(elm).attr("id").replace(r, newPath));
});
newElm.find("[for^='/']").each(function(pos, elm) {
$(elm).attr("for", $(elm).attr("for").replace(r, newPath));
});
newElm.insertAfter(elm);
$(".sortable-question").sortable("refresh");
this.checkDuplicateIds();
};
|
JavaScript
| 0.99997 |
@@ -2106,20 +2106,19 @@
d%0A var
-last
+old
Path = e
@@ -2197,32 +2197,58 @@
id%22)
-.match(r),%0A
+;%0A var oldId = oldPath.match(r)%5B1%5D;%0A var
oldPath
= %22
@@ -2239,24 +2239,27 @@
var oldPath
+Seg
= %22/%22 + pat
@@ -2277,32 +2277,26 @@
%22 +
-lastPath%5B1%5D
+oldId
+ %22/%22
-,%0A
+;%0A var
pos
@@ -2311,19 +2311,13 @@
Int(
-lastPath%5B1%5D
+oldId
)+1;
@@ -2344,16 +2344,19 @@
newPath
+Seg
= %22/%22 +
@@ -2397,51 +2397,25 @@
var
-check = document.getElementById(last
+tmpPath = old
Path
-%5B0%5D
.rep
@@ -2426,16 +2426,19 @@
(oldPath
+Seg
, newPat
@@ -2442,24 +2442,118 @@
Path
-)
+Seg
);%0A
-if(check
+this.assert(oldPath !== tmpPath, %22Replacing didn%E2%80%99t work.%22);%0A if(document.getElementById(tmpPath);
===
@@ -2753,32 +2753,35 @@
place(r, newPath
+Seg
));%0A %7D);%0A newE
@@ -2888,16 +2888,19 @@
newPath
+Seg
));%0A %7D)
|
13153e740f23ddb102fd11f34fc3a5f1edd4131d
|
Check for error in kbox binary before throwing
|
bin/kbox.js
|
bin/kbox.js
|
#!/usr/bin/env node
'use strict';
/**
* This file is meant to be linked as a "kbox" executable.
*/
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var argv = require('minimist')(process.argv.slice(2));
var chalk = require('chalk');
var Liftoff = require('liftoff');
var tildify = require('tildify');
var kconfig = require('../lib/config.js');
var manager = require('../lib/manager.js');
var App = require('../lib/app.js');
var deps = require('../lib/deps.js');
// set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();
var cli = new Liftoff({
name: 'profile',
configName: '.kalabox',
extensions: {
'.json': null
},
modulePath: path.resolve(__dirname, '../'),
modulePackage: path.resolve(__dirname, '../package.json')
});
// exit with 0 or 1
var failed = false;
process.once('exit', function(code) {
if (code === 0 && failed) {
process.exit(1);
}
});
var cliPackage = require('../package');
var versionFlag = argv.v || argv.version;
var tasksFlag = argv.T || argv.tasks;
var tasks = argv._;
var toRun = tasks.length ? tasks : ['default'];
cli.on('require', function (name) {
console.log('Requiring external module', chalk.magenta(name));
});
cli.on('requireFail', function (name) {
console.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});
cli.launch({
cwd: argv.cwd,
configPath: argv.kalaboxfile,
require: argv.require,
completion: argv.completion,
verbose: argv.verbose,
app: argv.app
}, handleArguments);
function handleArguments(env) {
if (argv.verbose) {
console.log(chalk.yellow('LIFTOFF SETTINGS:'), this);
console.log(chalk.yellow('CLI OPTIONS:'), argv);
console.log(chalk.yellow('CWD:'), env.cwd);
console.log(chalk.red('APP CONFIG LOCATION:'), env.configPath);
console.log(chalk.red('APP CONFIG BASE DIR:'), env.configBase);
console.log(chalk.cyan('KALABOX MODULE LOCATION:'), this.modulePath);
console.log(chalk.cyan('KALABOX PACKAGE.JSON LOCATION:'), this.modulePackage);
console.log(chalk.cyan('KALABOX PACKAGE.JSON'), require('../package'));
}
var workingDir = env.cwd;
var configPath = path.join(env.cwd, '.kalabox', 'profile.json');
if (argv.app) {
var apppath = path.resolve(kconfig.appDataPath, argv.app);
if (!fs.existsSync(apppath) || !fs.existsSync(path.resolve(apppath, 'app.json'))) {
console.log(chalk.red('App config not found.'));
process.exit(1);
}
// Load up the app data from ~/.kalabox/apps/<app>/app.json
var appdata = require(path.resolve(apppath, 'app.json'));
workingDir = appdata.path;
configPath = path.resolve(appdata.profilePath, 'profile.json');
}
if (fs.existsSync(configPath)) {
process.chdir(workingDir);
env.app = new App(manager, workingDir);
}
env.manager = manager;
if (argv.verbose) {
console.log(chalk.red('APP CONFIG:'), env.config);
console.log('Using config file', chalk.magenta(tildify(env.configPath)));
}
try {
// Run the task.
processTask(env);
} catch (err) {
// Log error.
logError(err);
}
}
function logError(err) {
console.log(chalk.red(err.message));
}
function processTask(env) {
// Get dependencies.
deps.call(function(manager) {
// Map taskName to task function.
var taskName = argv._[0];
var task = manager.tasks[taskName];
if (task) {
// Run task function.
task(function(err) {
throw err;
});
} else {
// Task not found.
throw new Error('Command "' + taskName + '" NOT found!');
}
});
}
|
JavaScript
| 0 |
@@ -3468,24 +3468,33 @@
r) %7B%0A
+ if (err)
throw err;
@@ -3492,18 +3492,16 @@
row err;
-
%0A %7D
|
cd6dc7192e543869479cbfcc5cb1eabdf39c4817
|
Remove watchContentBase option (#725)
|
package/environments/development.js
|
package/environments/development.js
|
const Environment = require('../environment')
const { dev_server } = require('../config')
const assetHost = require('../asset_host')
const webpack = require('webpack')
module.exports = class extends Environment {
constructor() {
super()
if (dev_server.hmr) {
this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin())
this.plugins.set('NamedModules', new webpack.NamedModulesPlugin())
}
}
toWebpackConfig() {
const result = super.toWebpackConfig()
if (dev_server.hmr) {
result.output.filename = '[name]-[hash].js'
}
result.output.pathinfo = true
result.devtool = 'cheap-eval-source-map'
result.devServer = {
host: dev_server.host,
port: dev_server.port,
https: dev_server.https,
hot: dev_server.hmr,
contentBase: assetHost.path,
publicPath: assetHost.publicPath,
clientLogLevel: 'none',
compress: true,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': '*'
},
overlay: true,
watchContentBase: true,
watchOptions: {
ignored: /node_modules/
},
stats: {
errorDetails: true
}
}
return result
}
}
|
JavaScript
| 0 |
@@ -1057,38 +1057,8 @@
ue,%0A
- watchContentBase: true,%0A
|
3f436b282bab1a3ec5a7c6c0ff36e01dde05dd6e
|
Remove cache time limits
|
ostrio:neo4jreactivity_collection.js
|
ostrio:neo4jreactivity_collection.js
|
if (!this.neo4j) {
this.neo4j = {};
}
if (!this.neo4j.uids) {
if(Meteor.isClient){
Session.setDefault('neo4juids', [null]);
}
this.neo4j.uids = (Meteor.isServer) ? [] : Session.get('neo4juids');
}
this.Neo4jCacheCollection = new Meteor.Collection('Neo4jCache');
if (Meteor.isServer) {
Neo4jCacheCollection.allow({
insert: function(userId, doc) {
return doc.lastModified = doc.created = new Date();
},
update: function(userId, doc) {
return false;
},
remove: function(userId, doc) {
return false;
}
});
Meteor.publish('Neo4jCacheCollection', function(uids) {
return Neo4jCacheCollection.find(
{
uid: {
'$in': uids
},
created: {
$gte: new Date(new Date() - 24 * 60 * 60000)
}
});
});
}
if (Meteor.isClient) {
Tracker.autorun(function(){
return Meteor.subscribe('Neo4jCacheCollection', Session.get('neo4juids'));
});
}
|
JavaScript
| 0.000001 |
@@ -698,87 +698,8 @@
ids%0A
- %7D,%0A created: %7B%0A $gte: new Date(new Date() - 24 * 60 * 60000)%0A
|
a71d5427611acf44bb775a380c6be94922e606fe
|
fix underscore unit tests
|
packages/patternengine-node-mustache/test/engine_underscore_tests.js
|
packages/patternengine-node-mustache/test/engine_underscore_tests.js
|
(function () {
"use strict";
var path = require('path');
var pa = require('../core/lib/pattern_assembler');
var testPatternsPath = path.resolve(__dirname, 'files', '_underscore-test-patterns');
try {
require('underscore');
} catch (err) {
console.log('underscore renderer not installed; skipping tests');
return;
}
// fake pattern lab constructor:
// sets up a fake patternlab object, which is needed by the pattern processing
// apparatus.
function fakePatternLab() {
var fpl = {
partials: {},
patterns: [],
footer: '',
header: '',
listitems: {},
listItemArray: [],
data: {
link: {}
},
config: require('../patternlab-config.json'),
package: {}
};
// patch the pattern source so the pattern assembler can correctly determine
// the "subdir"
fpl.config.paths.source.patterns = testPatternsPath;
return fpl;
}
exports['engine_underscore'] = {
'hello world underscore pattern renders': function (test) {
test.expect(1);
var patternPath = path.resolve(
testPatternsPath,
'00-atoms',
'00-global',
'00-helloworld.underscore'
);
// do all the normal processing of the pattern
var patternlab = new fakePatternLab();
var assembler = new pa();
var helloWorldPattern = assembler.process_pattern_iterative(patternPath, patternlab);
assembler.process_pattern_recursive(patternPath, patternlab);
test.equals(helloWorldPattern.render(), 'Hello world!\n');
test.done();
},
'underscore partials can render JSON values': function (test) {
test.expect(1);
// pattern paths
var pattern1Path = path.resolve(
testPatternsPath,
'00-atoms',
'00-global',
'00-helloworld-withdata.underscore'
);
// set up environment
var patternlab = new fakePatternLab(); // environment
var assembler = new pa();
// do all the normal processing of the pattern
var helloWorldWithData = assembler.process_pattern_iterative(pattern1Path, patternlab);
assembler.process_pattern_recursive(pattern1Path, patternlab);
// test
test.equals(helloWorldWithData.render(), 'Hello world!\nYeah, we got the subtitle from the JSON.\n');
test.done();
}
};
})();
|
JavaScript
| 0.000009 |
@@ -1185,26 +1185,20 @@
loworld.
-underscore
+html
'%0A
@@ -1835,26 +1835,20 @@
ithdata.
-underscore
+html
'%0A
|
2d4086345cbda50833fd70c3befa68b8498e38ee
|
Fix month aprox of division to more close round
|
lib/dedalo/extras/mdcat/calculation/mdcat.js
|
lib/dedalo/extras/mdcat/calculation/mdcat.js
|
var expressos = new function() {
this.calculate_period = function(options){
const data = options.data
const total_days = data.total_days
const years = Math.floor(total_days / 365)
const years_days = total_days - (years * 365)
const total_months = Math.floor(total_days / 30.42)
let months = Math.floor(years_days / 30.42)
let days = Math.floor(years_days - (months * 30.42))
let period = []
if(years > 0 && options.years === true){
const year_label = years == 1 ? get_label["anyo"] : get_label["anyos"]
const year_value = (options.label===true) ? years + ' ' + year_label : years
period.push(year_value)
}
if(months > 0 && options.months === true){
const months_label = months == 1 ? get_label["mes"] : get_label["meses"]
let months_value = ""
if(options.total === true){
months_value = (options.label===true) ? total_months + ' ' + months_label : total_months
}else{
months_value = (options.label===true) ? months + ' ' + months_label : months
}
period.push(months_value)
}
if(days > 0 && options.days === true){
const days_label = days == 1 ? get_label["dia"] : get_label["dias"]
let days_value = ""
if(options.total === true){
days_value = (options.label===true) ? total_days + ' ' + days_label : total_days
}else{
days_value = (options.label===true) ? days + ' ' + days_label : days
}
period.push(days_value)
}
const result = period.join(', ')
return result
}
this.calculate_import_major = function(options){
const data = options.data
const total_days = data.total_days
if(total_days === 0){
return 0
}
const years = Math.floor(total_days / 365)
const years_days = total_days - (years * 365)
let total_months = Math.floor(total_days / 30.42)
let months = Math.floor(years_days / 30.42)
let days = Math.floor(years_days - (months * 30.42))
let cal_import = 0
if(days > 0){
total_months = total_months + 1
}
if(total_months <= 6){
cal_import = 150000
}else{
cal_import = ((total_months - 6) * 28000) +150000
}
if (cal_import > 1000000) {
cal_import = 1000000
}
const result = cal_import
return result
}
this.calculate_import_minor = function(options){
const data = options.data
const total_days = data.total_days
if(total_days === 0){
return 0
}
const years = Math.floor(total_days / 365)
const years_days = total_days - (years * 365)
let total_months = Math.floor(total_days / 30.42)
let months = Math.floor(years_days / 30.42)
let days = Math.floor(years_days - (months * 30.42))
let cal_import = 0
if(days > 0){
total_months = total_months + 1
}
if(total_months <= 6){
cal_import = 900
}else{
cal_import = ((total_months - 6) * 170) +900
}
if (cal_import > 6010) {
cal_import = 6010
}
const result = cal_import
return result
}
}
|
JavaScript
| 0 |
@@ -282,32 +282,187 @@
_days / 30.42)%0A%0A
+%09%09const check_months = total_days / 30.42%0A%09%09const rest_months = check_months - total_months%0A%09%09%0A%09%09if(rest_months %3E 0.99)%7Btotal_months = total_months + 1%7D%0A%0A%0A
%09%09let months %09=
@@ -1934,32 +1934,186 @@
_days / 30.42)%0A%0A
+%09%09const check_months = total_days / 30.42%0A%09%09const rest_months = check_months - total_months%0A%09%09%0A%09%09if(rest_months %3E 0.99)%7Btotal_months = total_months + 1%7D%0A%0A
%09%09let months %09=
@@ -2191,33 +2191,32 @@
onths * 30.42))%0A
-%0A
%09%09let cal_import
@@ -2809,16 +2809,153 @@
30.42)%0A%0A
+%09%09const check_months = total_days / 30.42%0A%09%09const rest_months = check_months -total_months%0A%09%09%0A%09%09if(rest_months %3E 0.99)%7Btotal_months +1%7D%0A%0A
%09%09let mo
|
48f04cc783125a352a788b2f061558c3021f0131
|
fix buttons on separate line from dashboard
|
website/static/js/home-page/ShareWindowDropzone.js
|
website/static/js/home-page/ShareWindowDropzone.js
|
var m = require('mithril');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');
var AddProject = require('js/addProjectPlugin');
require('css/dropzone-plugin.css');
require('css/quick-project-search-plugin.css');
require('loaders.css/loaders.min.css');
var Dropzone = require('dropzone');
// Don't show dropped content if user drags outside dropzone
window.ondragover = function(e) { e.preventDefault(); };
window.ondrop = function(e) { e.preventDefault(); };
var ShareWindowDropzone = {
controller: function() {
Dropzone.options.shareWindowDropzone = {
// Dropzone is setup to upload multiple files in one request this configuration forces it to do upload file-by-
//file, one request at a time.
clickable: '#shareWindowDropzone',
parallelUploads: 1,
autoProcessQueue: false,
withCredentials: true,
method:'put',
border: '2px dashed #ccc',
maxFilesize: 1,
accept: function(file, done) {
if(this.files.length < 10){
this.options.url = waterbutler.buildUploadUrl(false,'osfstorage',window.contextVars.shareWindowId, file,{});
this.processFile(file);
}else if(this.files.length === 11){
$osf.growl('Error', 'Maximum of 10 files per upload');
}else{}
},
sending: function(file, xhr) {
//Hack to remove webkitheaders
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
};
},
success: function(file, xhr) {
this.processQueue();
file.previewElement.classList.add('dz-success');
},
error: function(file, message) {
file.previewElement.classList.add('dz-error');
},
};
$('#shareWindowDropzone').dropzone({
url:'placeholder',
previewTemplate: '<div class="dz-preview dz-processing dz-file-preview"><div class="dz-details"><div class="dz-filename"><span data-dz-name></span></div>' +
'<div class="dz-size" data-dz-size></div><img data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>' +
'<div class="dz-success-mark"><span>✔</span></div><div class="dz-error-mark"><span>✘</span></div><div class="dz-error-message"><span data-dz-errormessage></span></div></div>',
});
$('#ShareButton').click(function(e) { // disabled briefly to prevent button mashing.
$('#ShareButton').attr('disabled', 'disabled').css('cursor', 'pointer');
setTimeout(function() { $('#ShareButton').removeAttr('disabled'); }, 300);
$('#shareWindowDropzone').slideToggle();
$('#LinkToShareFiles').slideToggle();
$(this).toggleClass('btn-primary');
});
},
view: function(ctrl, args) {
function headerTemplate() {
return [
m('h2.col-xs-4', 'Dashboard'),
m('m-b-lg.col-xs-8.drop-zone-disp', {style: {textAlign: 'right'}},
m('button.btn.btn-primary.f-w-xl #ShareButton', 'Upload Public Files'),
m.component(AddProject,
{buttonTemplate : m('button.btn.btn-success.f-w-xl.[data-toggle="modal"][data-target="#addProjectFromHome"]',
{
onclick: function() {
$osf.trackClick('quickSearch', 'add-project', 'open-add-project-modal');
}
}, 'Create new project'),
modalID : 'addProjectFromHome',
stayCallback : function _stayCallback_inPanel() {
document.location.reload(true);
},
trackingCategory: 'quickSearch',
trackingAction: 'add-project',
templatesFetcher: ctrl.templateNodes
}
)
)
];
};
return m('.col-xs-12', headerTemplate(),
m('div.p-v-xs.text-center.drop-zone-format.drop-zone-invis .pointer .panel #shareWindowDropzone',
m('button.close[aria-label="Close"]',
m('.drop-zone-close','x')
),
m('p#shareWindowDropzone',
m('h1.drop-zone-head', 'Drop files to upload'),
'Having trouble? Click anywhere in this box to manually upload a file.'
)
),
m('.h4.text-center.drop-zone-invis #LinkToShareFiles', 'Or go to your ',
m('a', {href: '/share_window/'}, 'Public Files Project')
)
);
}
};
module.exports = ShareWindowDropzone;
|
JavaScript
| 0.000001 |
@@ -3137,18 +3137,39 @@
('h2
-.col-xs-4'
+', %7Bstyle: %7Bdisplay: 'inline'%7D%7D
, 'D
@@ -3177,16 +3177,17 @@
shboard'
+
),%0A
@@ -3200,17 +3200,17 @@
m('
-m
+p
-b-lg.co
@@ -3230,16 +3230,27 @@
one-disp
+.pull-right
', %7Bstyl
|
01334e779a80ec7d65ca99487afec2194abe9c54
|
Fix l10n extraction on ES2015. (#3963) r=vladikoff
|
grunttasks/l10n-extract.js
|
grunttasks/l10n-extract.js
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// grunt task to extract strings.
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var extract = require('jsxgettext-recursive');
// where to place the pot files.
var messagesOutputPath = path.join(__dirname, '..', 'locale', 'templates', 'LC_MESSAGES');
module.exports = function (grunt) {
grunt.registerTask('l10n-extract', 'Extract strings from templates for localization.', function () {
var done = this.async();
if (! fs.existsSync(messagesOutputPath)) {
mkdirp.sync(messagesOutputPath);
}
var clientWalker = extract({
'input-dir': path.join(__dirname, '..', 'app', 'scripts'),
'join-existing': false,
'keyword': 't',
'output': 'client.pot',
'output-dir': messagesOutputPath,
parsers: {
'.js': 'javascript',
'.mustache': 'handlebars'
}
});
clientWalker.on('end', function () {
var authWalker = extract({
exclude: /pages\/dist/,
'input-dir': path.join(__dirname, '..', 'server'),
'join-existing': true,
'keyword': 't',
'output': 'server.pot',
'output-dir': messagesOutputPath,
parsers: {
'.html': 'handlebars',
'.js': 'javascript',
'.txt': 'handlebars'
}
});
authWalker.on('end', function () {
done();
});
});
});
};
|
JavaScript
| 0.000184 |
@@ -553,13 +553,11 @@
sk('
-l10n-
+jsx
extr
@@ -567,55 +567,46 @@
', '
-Extract strings from templates for localization
+Do not call directly, see l10n-extract
.',
@@ -826,11 +826,12 @@
', '
-app
+.es5
', '
@@ -1569,13 +1569,263 @@
);%0A %7D);
+%0A%0A grunt.registerTask('l10n-extract', 'Extract strings from templates for localization.', %5B%0A // jsxgettext does not support ES2015, only ES5. Run babel to convert%0A // then run the extractor on the ES5 files.%0A 'babel',%0A 'jsxextract'%0A %5D);
%0A%7D;%0A%0A
|
fc174739e87f2641a3b66ee33a21aef2fba90e86
|
Fix typo
|
helpers/schedules.js
|
helpers/schedules.js
|
var hue = require("node-hue-api"),
config = require("config"),
HueApi = hue.HueApi,
schedule = require('node-schedule'),
lightState = hue.lightState;
const DINING_CEILING = 1,
SOFA_CEILING = 2,
CARS_LIGHTS = 3,
BED = 4,
DESK_LAMP = 5,
DINING_UPLIGHT = 6,
TV_LIGHTS = 7,
SOFA_UPLIGHT = 8;
CUPBOARD_TOP = 9,
CUPBOARD_BOTTOM = 10,
var displayResult = function(result) {
console.log(JSON.stringify(result, null, 2));
};
const api = new HueApi(config.hostname, config.username);
const addIdToStatus = (light) => {
return api.lightStatus(light).then((status) =>
new Promise((accept, reject) => {status.id = light; accept(status)})
);
}
// TODO: Replace this with single call to api.lights()
const getState = (lights, data) => {
if (lights.constructor !== Array) {lights = [lights]}
return Promise.all(lights.map((light) => addIdToStatus(light)));
}
const statesToMap = (states) => states.reduce((o,v,i) => {o[v.id] = v; return o}, {});
const setLow = () => {
api.lightStatus(CUPBOARD_TOP).then(conditionalOn).done()
}
const setOff = () => {
api.lightStatus(CUPBOARD_TOP).then(conditionalOff).done()
}
const flashWarn = (lights, colour) => {
getState(lights).then((status) => conditionalWarn(status, colour));
}
const conditionalWarn = (status, colour=[255,0,0]) => {
status = statesToMap(status)
const lights = Object.keys(status)
// Make sure at least one light is on
if (lights.reduce((o,v) => o || status[v].state.on, false)) {
// Return to original state
const resetState = () => {
Promise.all(lights.map((light) => {
const lightState = status[light].state
lightState.alert = 'none'
api.setLightState(light, lightState)
})).then(displayResult)
}
// alert state
const state = lightState.create().on().rgb(colour).alert('lselect')
Promise.all(lights.map((light) => api.setLightState(light, state)))
.then(() => setTimeout(resetState, 5000))
}
}
const conditionalOn = (status) => {
console.log("Conditional on", status.state)
if (!status.state.on) {
console.log("Turning on")
state = {on: true, bri: 50, ct: 350}
api.setLightState(CUPBOARD_TOP, state).then(displayResult).done()
api.setLightState(CUPBOARD_BOTTOM, state).then(displayResult).done()
}
}
const conditionalOff = (status) => {
console.log("Conditional off", status.state)
if (status.state.bri === 50 && status.state.ct === 350 && status.state.colormode === 'ct') {
console.log("Turning off")
state = {on: false}
api.setLightState(CUPBOARD_TOP, state).then(displayResult).done()
api.setLightState(CUPBOARD_BOTTOM, state).then(displayResult).done()
}
}
// Get ready for school alert
schedule.scheduleJob('15 8 * * *', () => flashWarn([DINING_UPLIGHT,SOFA_UPLIGHT,CUPBOARD_BOTTOM,CUPBOARD_TOP], [0,255,0]));
// Bedtime
schedule.scheduleJob('45 19 * * *', () => flashWarn([DINING_UPLIGHT,SOFA_UPLIGHT,CUPBOARD_BOTTOM,CUPBOARD_TOP], [255,0,0]));
// Stop reading
schedule.scheduleJob('30 20 * * *', () => flashWarn([BED], [0, 0, 255]));
// Notify app start
flashWarn([DINING_UPLIGHT], [0,255,0])
module.exports = {
api: api,
flashWarn: flashWarn
}
|
JavaScript
| 0.999999 |
@@ -318,11 +318,9 @@
= 8
-;%09%09
+,
%0A%09
@@ -360,17 +360,17 @@
TOM = 10
-,
+;
%0A%0Avar di
|
248352fa0b4062cd6b194de714d7ec35e6e4277e
|
Update output-modal.js
|
client/app/scripts/liveblog-edit/directives/output-modal.js
|
client/app/scripts/liveblog-edit/directives/output-modal.js
|
import outputModalTpl from 'scripts/liveblog-edit/views/output-modal.html';
/**
* @desc directive to open a modal to create or edit a channel output
* @example <output-modal modal-active="x" outputs="array" output="object" blog="blog"></output-modal>
*/
export default function outputModal() {
return {
restrict: 'E',
scope: {
modalActive: '=',
outputs: '=',
output: '=',
blog: '='
},
templateUrl: outputModalTpl,
controllerAs: 'vm',
controller: outputModalController,
bindToController: true
};
}
outputModalController.$inject = ['$rootScope', 'api', 'urls', 'notify', 'modal', 'upload', 'adsUtilSevice', '$scope'];
function outputModalController($rootScope, api, urls, notify, modal, upload, adsUtilSevice, $scope) {
var vm = this;
vm.collections = [];
vm.readyToSave = false;
vm.disableSave = false;
vm.imageSaved = false;
vm.cancelModal = cancelModal;
vm.saveOutput = saveOutput;
vm.saveOutputImage = saveOutputImage;
vm.removeOutputImage = removeOutputImage;
vm.notValidName = adsUtilSevice.uniqueNameInItems;
initialize().then(function() {
vm.readyToSave = true;
});
function cancelModal() {
vm.modalActive = false;
vm.disableSave = false;
}
function initialize() {
return api('collections').query({where: {deleted: false}})
.then(function(data) {
vm.collections = data._items;
})
.catch(function(data) {
notify.error(gettext('There was an error getting the collections'));
});
}
function saveOutput() {
var newOutput = {
name: vm.output.name,
blog: vm.blog._id,
collection: vm.output.collection,
style: vm.output.style
};
// disable save button
vm.disableSave = true;
// if there is a new image uploaded
if (vm.output.preview && vm.output.preview.img) {
saveOutputImage()
.then(function() {
newOutput.style['background-image'] = vm.output.style['background-image'];
return api('outputs').save(vm.output, newOutput)
.then(handleSuccessSave, handleErrorSave);
})
} else {
return api('outputs').save(vm.output, newOutput)
.then(handleSuccessSave, handleErrorSave);
}
}
function handleSuccessSave() {
notify.info(gettext('Output saved successfully'));
vm.output = {};
vm.modalActive = false;
vm.disableSave = false;
$rootScope.$broadcast('output.saved');
}
function handleErrorSave() {
notify.error(gettext('Something went wrong, please try again later!'), 5000)
}
function saveOutputImage() {
var form = {};
var config = vm.output.preview;
if (config.img) {
form.media = config.img;
} else if (config.url) {
form.URL = config.url;
} else {
return;
}
// return a promise of upload which will call the success/error callback
return urls.resource('archive').then((uploadUrl) => upload.start({
method: 'POST',
url: uploadUrl,
data: form
})
.then((response) => {
if (response.data._status === 'ERR') {
return;
}
var pictureUrl = response.data.renditions.viewImage.href;
vm.output.style['background-image'] = pictureUrl;
vm.imageSaved = true;
}, (error) => {
notify.error(
error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
);
}, (progress) => {
vm.output.progress = {
width: Math.round(progress.loaded / progress.total * 100.0)
}
}));
}
function removeOutputImage() {
modal.confirm(gettext('Are you sure you want to remove the image?'))
.then(() => {
vm.output.preview = {};
vm.output.progress = {width: 0};
vm.imageSaved = false;
vm.output.style['background-image'] = '';
});
}
}
|
JavaScript
| 0.000002 |
@@ -718,18 +718,8 @@
ice'
-, '$scope'
%5D;%0A%0A
@@ -812,16 +812,8 @@
vice
-, $scope
) %7B%0A
@@ -4312,8 +4312,9 @@
%0A %7D%0A%7D
+%0A
|
161fc9ef5943045de69edffbfc01f787c47b74ab
|
Remove properties from tests that do not always show up
|
test/e2e/e2e.spec.js
|
test/e2e/e2e.spec.js
|
var expect = require('chai').expect,
debug = require('debug')('bp:test:e2e'),
browserPerf = require('../../');
var expectedMetrics = {
chrome: [
// ChromeTracingMetrics & RafRenderingMetrics
'mean_frame_time',
'meanFrameTime',
// Network Timings
'firstPaint',
'connectStart',
'domainLookupStart',
'domComplete',
'domInteractive',
'domLoading',
'fetchStart',
'navigationStart',
// RuntimePerfMetrics
'ExpensiveEventHandlers',
'ExpensivePaints',
'GCInsideAnimation',
'Layers',
'NodePerLayout_avg',
'PaintedArea_avg',
'PaintedArea_total',
// TimelineMetrics
'DecodeImage',
'CompositeLayers',
'Layout',
'Paint',
'RecalculateStyles',
'EvaluateScript',
'EventDispatch',
'FireAnimationFrame',
'FunctionCall',
'GCEvent',
'XHRReadyStateChange',
'UpdateLayerTree',
'Rasterize'
],
firefox: [
'meanFrameTime',
// Network Timings
'firstPaint',
'connectStart',
'domainLookupStart',
'domComplete',
'domInteractive',
'domLoading',
'fetchStart',
'navigationStart',
]
};
describe('End To End Test Cases', function() {
it('fails if selenium is not running', function(done) {
browserPerf('http://google.com', function(err, res) {
expect(err).to.not.be.null;
expect(err).to.not.be.empty;
expect(res).to.be.empty;
done();
}, {
selenium: 'nohost:4444'
});
});
describe('gets enough statistics from browsers', function() {
this.timeout(2 * 60 * 1000); // 2 minutes for E2E tests
it('should work for a sample page', function(done) {
var url = 'http://nparashuram.com/perfslides/';
browserPerf(url, function(err, res) {
if (err) {
console.log(err);
}
expect(err).to.be.empty;
expect(res).to.not.be.empty;
res.forEach(function(data) {
expect(data._url).to.equal(url);
debug('Testing', data._browserName);
expect(data).to.include.keys(expectedMetrics[data._browserName]);
});
done();
}, {
selenium: process.env.SELENIUM || 'http://localhost:4444/wd/hub',
username: process.env.USERNAME,
accesskey: process.env.ACCESSKEY,
browsers: [{
browserName: 'chrome',
version: 39,
name: 'Browserperf-E2E Tests'
}, {
browserName: 'firefox',
version: 33,
name: 'Browserperf-E2E Tests'
}]
});
});
});
});
|
JavaScript
| 0 |
@@ -718,16 +718,18 @@
es',%0D%0A%09%09
+//
'Evaluat
@@ -741,16 +741,18 @@
pt',%0D%0A%09%09
+//
'EventDi
@@ -807,16 +807,18 @@
ll',%0D%0A%09%09
+//
'GCEvent
@@ -823,16 +823,18 @@
nt',%0D%0A%09%09
+//
'XHRRead
|
6031c94e1a00ce8dc900ac5eaa69ca6569c9bb4b
|
update molecular-formula to 0.1.3
|
eln/libs/EMDB.js
|
eln/libs/EMDB.js
|
export {
default
} from 'https://www.lactame.com/lib/molecular-formula/0.1.3/emdb.js';
|
JavaScript
| 0.999991 |
@@ -76,12 +76,25 @@
1.3/
-emdb
+molecular-formula
.js'
|
c3a9667a3143ff66b9d1936c241672bfdc3a3e37
|
Add WhiteLabel to Mongoose Schema for Vendors. White Labeled vendors will have special view logic, so we need to add a default value of false to check against. In Mongoose, default values will be set without setting a required validator as well.
|
server/app/models/vendor.js
|
server/app/models/vendor.js
|
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
env = process.env.NODE_ENV || 'development',
config = require('../../config/config')[env],
Schema = mongoose.Schema,
_ = require('lodash');
var customNameSchema = new Schema({
type: Schema.ObjectId,
displayName: String
});
var toolEnabledSchema = new Schema({
"name": String,
"active": Boolean,
"slug": String
});
/**
* Vendor Schema
* @todo refactor tools to be use slug as keys? is this possible?
*/
var VendorSchema = new Schema({
"created": {
type: Date,
"default": Date.now
},
"searchString" : {
type: String,
"default": ''
},
"name": {
type: String,
"default": '',
trim: true
},
"contactPerson": {
"name": {
type: String,
"default": '',
trim: true
},
"email": {
type: String,
"default": '',
trim: true
},
"phone": {
type: String,
"default": '',
trim: true
}
},
"salesRep": {
type: Schema.ObjectId,
ref: 'User'
},
"vendorRep": {
type: Schema.ObjectId,
ref: 'User'
},
"logo": {
"original": {
type: String,
"default": '',
trim: true
}
},
"website": {
type: String,
"default": '',
trim: true
},
"legalTerms": {
type: String,
"default": '',
trim: true
},
"businessPhone": {
type: String,
"default": '',
trim: true
},
"businessAddress": {
"address1": {
type: String,
"default": '',
trim: true
},
"address2": {
type: String,
"default": '',
trim: true
},
"city": {
type: String,
"default": '',
trim: true
},
"state": {
type: String,
"default": '',
trim: true
},
"zip": {
type: String,
"default": '',
trim: true
}
},
"geo": {
"latitude": {
type: Number,
"default": null
},
"longitude": {
type: Number,
"default": null
}
},
"tools": [toolEnabledSchema],
"programs": [{
type: Schema.ObjectId,
ref: 'Program'
}],
"programCustomNames": [customNameSchema],
"customField": {
required: {
type: Boolean,
"default": false
},
enabled: {
type: Boolean,
"default": false
},
displayName: {
type: String,
"default": '',
trim: true
}
}
});
var troop = require('mongoose-troop');
VendorSchema.plugin(troop.merge);
var taggable = require('mongoose-taggable');
VendorSchema.plugin(taggable, {'path':'tags'});
/**
* Statics
*/
VendorSchema.statics = {
// this gets called when a vendorId is present in the req.params
// its a clever way to be able to access req.vendor in the next middlewares
//
load: function(id, cb) {
this.findOne({
_id: id
}).populate('programs salesRep vendorRep').exec(cb);
}
};
/**
* Runs similar to "after get" callback
*
*/
VendorSchema.pre('init', function(next, data) {
// iterate through each program and replace its name with custom name if set
// @todo not the most effecient
// attempts to just "merge" the 2 datasets failed, and replaced all the props
// of programs with custom name
_.each(data.programs, function(item) {
var customName = _.where(data.programCustomNames, {
_id: item._id
});
item.displayName = customName.length ? customName[0].displayName : null;
});
next();
});
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w\-]+/g, '');
}
VendorSchema.pre('save', function(next) {
/**
* Process tags from dashboard
* --------------------------------
*
* @note tags are sent as vendorTags which are then saved into vendor.tags
* @todo refactor with fulltext mondules that @pickle was looking into
* @note when calling addTag() and removeTag() without a callback, it happens in memory
* only and thus will not be refrected in vendor.tags until vendor.save() is complete
*
*/
var vendor = this;
var vendorTags = []; // tags that are currently being passed from the vendor
// create a unified array of current vendor tags
_.each(vendor.vendorTags, function(item) {
vendorTags.push(item.text);
});
var newTags = _.difference(vendorTags, vendor.tags);
var removeTags = _.difference(vendor.tags, vendorTags);
_.each(newTags, function(item) {
vendor.addTag(item, function(err, addedTag) {
console.log('Added: ' + item);
});
});
_.each(removeTags, function(item) {
vendor.removeTag(item, function(err, removedTag) {
console.log('Removed: ' + item);
});
});
/**
* A nice way to create a search string that we can use on the dealer locator
* --------------------------------
*
* @todo refactor with fulltext mondules that @pickle was looking into
* with a fultext search in place, we could just send tag searches as get queries
* and let the server do all the work.
*
*/
vendor.searchString = '';
// will be present when updating from dashboard
if(vendor.vendorTags) {
_.each(vendor.vendorTags, function(tag) {
vendor.searchString += tag.text + ' ';
});
// on seed data
} else {
_.each(vendor.tags, function(tag) {
vendor.searchString += tag + ' ';
});
}
/**
* Standardize tool slugs
*
*/
_.each(vendor.tools, function(item) {
item.slug = convertToSlug(item.name);
});
next();
});
VendorSchema.statics = {
getCurrentReps: function(vendorId, cb) {
// attempt to get the sales rep, which we save with the quote
// for easy geting from the database
return this.findOne({
_id: vendorId
}, function(err, result) {
if (err) return cb(err);
if (result && result._id) {
console.log(result);
return cb(null, result);
} else {
return cb(new Error(vendorId + ' is Not a valid vendor id'));
}
});
},
load: function(id, cb) {
this.findOne({
_id: id
}).populate('programs salesRep vendorRep').exec(cb);
}
};
mongoose.model('Vendor', VendorSchema);
|
JavaScript
| 0 |
@@ -1567,32 +1567,127 @@
im: true%0A %7D,%0A
+ %22whiteLabel%22: %7B%0A type: Boolean,%0A %22default%22: false,%0A trim: true%0A %7D,%0A
%22businessPho
@@ -7098,8 +7098,9 @@
Schema);
+%0A
|
419597b99a83656f3ea9a5494fe5d00cc1e4638b
|
make drop zone clickable
|
website/static/js/home-page/ShareWindowDropzone.js
|
website/static/js/home-page/ShareWindowDropzone.js
|
var m = require('mithril');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');
require('css/quick-project-search-plugin.css');
require('loaders.css/loaders.min.css');
var Dropzone = require('dropzone');
// Don't show dropped content if user drags outside dropzone
window.ondragover = function(e) { e.preventDefault(); };
window.ondrop = function(e) { e.preventDefault(); };
var xhrconfig = function(xhr) {
xhr.withCredentials = true;
};
var ShareWindowDropzone = {
controller: function() {
var shareWindowId;
var url = $osf.apiV2Url('users/me/nodes/', { query : { 'filter[category]' : 'share window'}});
var promise = m.request({method: 'GET', url : url, config : xhrconfig, background: true});
promise.then(function(result) {
shareWindowId = result.data[0].id;
});
Dropzone.options.shareWindowDropzone = {
clickable: '#shareWindowDropzone',
accept: function(file, done) {
this.options.url = waterbutler.buildUploadUrl(false,'osfstorage',shareWindowId, file,{});
done();
},
sending: function(file, xhr) {
//Hack to remove webkitheaders
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
};
}
};
$('#shareWindowDropzone').dropzone({
withCredentials: true,
url:'placeholder',
method:'put',
previewTemplate: '<div class="text-center dz-filename"><span data-dz-name></span> has been uploaded to your Share Window</div>'
});
},
view: function(ctrl, args) {
return m('h1.p-v-xl.text-center .pointer .panel #shareWindowDropzone', 'Drag and drop files to upload them')
}
};
module.exports = ShareWindowDropzone;
|
JavaScript
| 0.000001 |
@@ -1700,17 +1700,16 @@
%3C/div%3E'%0A
-%0A
@@ -1796,10 +1796,11 @@
m('
-h1
+div
.p-v
@@ -1853,16 +1853,29 @@
opzone',
+m('p',m('h1',
'Drag
@@ -1905,16 +1905,90 @@
d them')
+), %22Having trouble click anywhere in this box to manually upload a file%22);
%0A %7D%0A%7D;%0A
|
fd942ab58761ff09cd5cd12040cb71fbf54f300d
|
reformat parser spec
|
spec/parser_spec.js
|
spec/parser_spec.js
|
'use strict';
var Parser = require('../parser.js');
describe('#consumeTo', function(){
var parser;
beforeEach(function(){
parser = new Parser('first this# then this.');
});
context('FINISHED', function(){
beforeEach(function(){
parser.consumeTo('then this.');
});
it('returns null', function(){
expect(parser.consumeTo('a')).toBeNull();
});
});
context('single character', function(){
it('returns a string through the character', function(){
var first = parser.consumeTo('#');
var second = parser.consumeTo('.');
expect(first).toBe('first this#');
expect(second).toBe(' then this.');
});
});
context('longer string', function(){
it('returns a string through the test string', function(){
var first = parser.consumeTo('this');
var second = parser.consumeTo('this.');
expect(first).toBe('first this');
expect(second).toBe('# then this.');
});
});
context('regex', function(){
it('returns a string through the regex', function(){
var first = parser.consumeTo(/this[\.#]{1}/);
var second = parser.consumeTo(/this[\.#]{1}/);
expect(first).toBe('first this#');
expect(second).toBe(' then this.');
});
});
});
|
JavaScript
| 0.000003 |
@@ -47,16 +47,49 @@
.js');%0A%0A
+describe('Parser', function()%7B%0A
describe
@@ -115,16 +115,18 @@
tion()%7B%0A
+
var pa
@@ -132,16 +132,18 @@
arser;%0A%0A
+
before
@@ -155,24 +155,26 @@
function()%7B%0A
+
parser =
@@ -212,16 +212,18 @@
his.');%0A
+
%7D);%0A%0A
@@ -215,32 +215,34 @@
.');%0A %7D);%0A%0A
+
+
context('FINISHE
@@ -257,24 +257,26 @@
tion()%7B%0A
+
beforeEach(f
@@ -287,24 +287,27 @@
ion()%7B%0A
+
+
parser.consu
@@ -326,29 +326,33 @@
his.');%0A
+
+
%7D);%0A%0A
+
it('retu
@@ -370,24 +370,26 @@
function()%7B%0A
+
expect
@@ -424,24 +424,26 @@
Null();%0A
+
%7D);%0A
%7D);%0A%0A
@@ -426,39 +426,43 @@
ll();%0A %7D);%0A
+
%7D);%0A%0A
+
context('singl
@@ -479,32 +479,34 @@
r', function()%7B%0A
+
it('returns
@@ -548,32 +548,34 @@
nction()%7B%0A
+
+
var first = pars
@@ -589,24 +589,26 @@
umeTo('#');%0A
+
var se
@@ -636,32 +636,34 @@
To('.');%0A%0A
+
+
expect(first).to
@@ -673,32 +673,34 @@
'first this#');%0A
+
expect(sec
@@ -725,35 +725,41 @@
his.');%0A
+
%7D);%0A
+
+
%7D);%0A%0A
+
context('l
@@ -781,32 +781,34 @@
function()%7B%0A
+
+
it('returns a st
@@ -848,32 +848,34 @@
nction()%7B%0A
+
var first = pars
@@ -894,32 +894,34 @@
('this');%0A
+
+
var second = par
@@ -941,24 +941,26 @@
('this.');%0A%0A
+
expect
@@ -985,32 +985,34 @@
t this');%0A
+
expect(second).t
@@ -1040,21 +1040,27 @@
+
%7D);%0A
+
+
%7D);%0A%0A
+
+
cont
@@ -1080,24 +1080,26 @@
function()%7B%0A
+
it('retu
@@ -1145,24 +1145,26 @@
on()%7B%0A
+
+
var first =
@@ -1197,16 +1197,18 @@
%5D%7B1%7D/);%0A
+
va
@@ -1255,24 +1255,26 @@
%7D/);%0A%0A
+
expect(first
@@ -1298,24 +1298,26 @@
s#');%0A
+
expect(secon
@@ -1332,32 +1332,42 @@
' then this.');%0A
+ %7D);%0A
%7D);%0A %7D);%0A%7D)
@@ -1364,13 +1364,14 @@
;%0A %7D);%0A
+%0A%0A
%7D);%0A
-%0A
|
797eaf829b56c9937f023b218378a33b64c776ed
|
Fix rejection of signature
|
src/services/authentication/index.js
|
src/services/authentication/index.js
|
'use strict';
const auth = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
const local = require('feathers-authentication-local');
const logger = require('winston');
const system = require('./strategies/system');
const hooks = require('./hooks');
let authenticationSecret = null;
try {
authenticationSecret = require("../../../config/secrets.json").authentication;
} catch (e) {
logger.log('warn', 'Could not read authentication secret, using insecure default value.');
}
module.exports = function() {
const app = this;
const authConfig = Object.assign({}, app.get('auth'), {
header: 'Authorization',
entity: 'account',
service: 'accounts',
jwt: {
header: { typ: 'access' },
audience: 'https://schul-cloud.org',
subject: 'anonymous',
issuer: 'feathers',
algorithm: 'HS256',
expiresIn: '30d'
},
});
const localConfig = {
name: 'local',
entity: 'account',
service: 'accounts',
// TODO: change username to unique identifier as multiple
// users can have same username in different services
usernameField: 'username',
passwordField: 'password'
};
const jwtConfig = {
name: 'jwt',
entity: 'account',
service: 'accounts',
header: 'Authorization'
};
if(authenticationSecret) {
Object.assign(jwtConfig, {secretOrKey: authenticationSecret});
}
// Configure feathers-authentication
app.configure(auth(authConfig));
app.configure(jwt(jwtConfig));
app.configure(local(localConfig));
app.configure(system({
name: 'moodle',
loginStrategy: require('../account/strategies/moodle')
}));
app.configure(system({
name: 'lernsax',
loginStrategy: require('../account/strategies/lernsax')
}));
app.configure(system({
name: 'itslearning',
loginStrategy: require('../account/strategies/itslearning')
}));
const authenticationService = app.service('authentication');
// TODO: feathers-swagger
/*
authenticationService.docs = {
description: 'A service to send and receive messages',
create: {
//type: 'Example',
parameters: [{
description: 'username or email',
//in: 'path',
required: true,
name: 'username',
type: 'string'
},
{
description: 'password',
//in: 'path',
required: false,
name: 'password',
type: 'string'
},
{
description: 'ID of the system that acts as a login provider. Required for new accounts or accounts with non-unique usernames.',
//in: 'path',
required: false,
name: 'systemId',
type: 'string'
}],
summary: 'Log in with or create a new account',
notes: 'Returns a JSON Web Token for the associated user in case of success.'
//errorResponses: []
}
};*/
// Set up our hooks
authenticationService.hooks({
before: hooks.before,
after: hooks.after
});
};
|
JavaScript
| 0.000009 |
@@ -867,16 +867,47 @@
d'%0A%09%09%7D,%0A
+%09%09secret: authenticationSecret%0A
%09%7D);%0A%0A%0A%09
|
d1d0bafac967cc2f368ef8058a0a9810068ddc04
|
fix typo
|
client/opencps-pki.js
|
client/opencps-pki.js
|
/*!
* OpenCPS PKI; version: 1.0.0
* https://github.com/VietOpenCPS/pki
* Copyright (c) 2016 OpenCPS Community;
* Licensed under the AGPL V3+.
* https://www.gnu.org/licenses/agpl-3.0.html
*/
(function($) {
"use strict";
function hex2Array(hex) {
if(typeof hex == 'string') {
var len = Math.floor(hex.length / 2);
var ret = new Uint8Array(len);
for (var i = 0; i < len; i++) {
ret[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return ret;
}
}
function hasPlugin(mime) {
if(navigator.mimeTypes && mime in navigator.mimeTypes) {
return true;
}
return false;
}
function loadBcyPlugin() {
var mime = 'application/x-cryptolib05plugin';
var element = "bcy" + mime.replace('/', '').replace('-', '');
if(document.getElementById(element)) {
return document.getElementById(element);
}
var objectTag = '<object id="' + element + '" type="' + mime + '" style="width: 1px; height: 1px; position: absolute; visibility: hidden;"></object>';
var div = document.createElement("div");
div.setAttribute("id", 'plugin' + element);
document.body.appendChild(div);
document.getElementById('plugin' + element).innerHTML = objectTag;
return document.getElementById(element);
}
function signBcy(signer) {
var plugin = loadBcyPlugin();
if (plugin.valid) {
var code = plugin.Sign(hex2Array(signer.options.hash.hex));
if (code === 0 || code === 7) {
var sign = plugin.Signature;
signer.options.signature.value = sign;
if (signer.options.afterSign) {
signer.options.afterSign(signer, signer.options.signature);
}
}
else {
if (signer.options.onError) {
signer.options.onError(signer, 'sign() failed');
}
}
}
}
if (window.hwcrypto) {
window.hwcrypto.use('auto');
window.hwcrypto.debug().then(function(response) {
console.log('Debug: ' + response);
}, function(err) {
console.log('debug() failed: ' + err);
return;
});
}
function signHwCrypto(signer) {
window.hwcrypto.getCertificate({lang: 'en'}).then(function(certificate) {
window.hwcrypto.sign(certificate, {type: signer.options.hash.type, hex: signer.options.hash.hex}, {lang: 'en'}).then(function(signature) {
signer.options.signature.certificate = certificate.hex;
signer.options.signature.value = signature.hex;
if (signer.options.afterSign) {
signer.options.afterSign(signer, signer.options.signature);
}
}, function(err) {
if (signer.options.onError) {
signer.options.onError(signer, err);
}
console.log("sign() failed: " + err);
});
}, function(err) {
console.log("getCertificate() failed: " + err);
if (signer.options.onError) {
signer.options.onError(signer, err);
}
});
}
$.signer = $.signer || {};
$.extend($.signer, {
options: {
hash: {
type: 'sha256',
hex: false,
value: false
},
signature: {
certificate: false,
value: false
},
document: false,
beforeSign: false,
afterSign: false,
onError: false
},
sign: function(options) {
var signer = this;
$.extend(signer.options, options);
if (signer.options.beforeSign) {
signer.options.beforeSign(signer, signer.options.hash);
}
if (hasPlugin('application/x-cryptolib05plugin')) {
signBcy(signer);
}
else if (window.hwcrypto) {
signHwCrypto(signer);
}
return signer;
}
});
$.extend({
getCertificate: function(){
var cert = null;
if (window.hwcrypto) {
window.hwcrypto.getCertificate({lang: 'en'}).then(function(response) {
cert = response.hex;
}, function(err) {
console.log("getCertificate() failed: " + err);
});
}
return cert;
},
sign: function(options) {
return $.signer.sign(options);
}
});
})(jQuery);
|
JavaScript
| 0.999991 |
@@ -1971,32 +1971,34 @@
sponse) %7B%0A
+
console.log('Deb
@@ -2041,24 +2041,26 @@
rr) %7B%0A
+
console.log(
@@ -2082,24 +2082,26 @@
: ' + err);%0A
+
return
|
f5a1c6feddc4d06c3ca4db3a840d81e0885c46a5
|
manage defaultSensor if it’s available for comfort
|
server/consumptions-yearly-aggregates/publications.js
|
server/consumptions-yearly-aggregates/publications.js
|
import {getUserObjectsIds} from "../publications-commons";
function getId (sensorId, year, source, measurementType) {
return `${sensorId}-${year}-${source}-${measurementType}`;
}
Meteor.publish("yearlyConsumptions", (sensorId, year, source, measurementType) => {
check(sensorId, String);
check(year, String);
check(source, String);
check(measurementType, String);
return ConsumptionsYearlyAggregates.find({
_id: getId(sensorId, year, source, measurementType)
});
});
Meteor.publish("dashboardYearlyConsumptions", function () {
const user = Meteor.users.findOne({
_id: this.userId
});
if (user) {
const sitesIds = getUserObjectsIds(user, "view-all-sites", Sites, "sites");
const currentYear = moment().format("YYYY");
const ids = sitesIds.reduce((state, id) => {
//Check if default sensor Exist
const site = Sites.findOne({
_id: id
});
const sensorIds = site.defaultSensor || id;
return [
...state,
`${sensorIds}-${currentYear}-reading-activeEnergy`,
`${sensorIds}-${currentYear}-reading-comfort`,
`${sensorIds}-${currentYear}-reference-activeEnergy`
];
}, []);
return ConsumptionsYearlyAggregates.find({
_id: {
$in: ids
}
});
}
});
|
JavaScript
| 0 |
@@ -971,63 +971,416 @@
%7D);%0A
- const sensorIds = site.defaultSensor %7C%7C id;
+%0A const sensors = Sensors.find(%7B%0A _id: %7B%0A $in: site.sensorsIds%0A %7D%0A %7D).fetch();%0A%0A const comfort = sensors.find(x =%3E %7B%0A return _.contains(x.measurementsType, %22comfort%22);%0A %7D);%0A%0A const sensorIds = site.defaultSensor %7C%7C id;%0A const comfortId = comfort ? comfort._id : id;%0A
%0A
@@ -1542,21 +1542,28 @@
%7D-re
-ading-comfort
+ference-activeEnergy
%60,%0A
@@ -1576,33 +1576,33 @@
%60$%7B
-sens
+comf
or
+t
Id
-s
%7D-$%7BcurrentY
@@ -1608,36 +1608,29 @@
Year%7D-re
-ference-activeEnergy
+ading-comfort
%60%0A
|
cab08c464f53f22d62ddc2e19eda61d50ef87714
|
Fix missing webp support in create command
|
packages/cli/lib/commands/create.js
|
packages/cli/lib/commands/create.js
|
const ora = require('ora');
const glob = require('glob');
const gittar = require('gittar');
const fs = require('fs.promised');
const copy = require('ncp');
const { green } = require('chalk');
const { resolve, join } = require('path');
const { prompt } = require('inquirer');
const { promisify } = require('bluebird');
const isValidName = require('validate-npm-package-name');
const { info, isDir, hasCommand, error, trim, warn } = require('../util');
const { addScripts, install, initGit, isMissing } = require('../lib/setup');
const ORG = 'preactjs-templates';
const RGX = /\.(woff2?|ttf|eot|jpe?g|ico|png|gif|mp4|mov|ogg|webm)(\?.*)?$/i;
const isMedia = str => RGX.test(str);
const capitalize = str => str.charAt(0).toUpperCase() + str.substring(1);
module.exports = async function(repo, dest, argv) {
// Prompt if incomplete data
if (!repo || !dest) {
warn('Insufficient arguments! Prompting...');
info('Alternatively, run `preact create --help` for usage info.');
let questions = isMissing(argv);
let response = await prompt(questions);
Object.assign(argv, response);
repo = repo || response.template;
dest = dest || response.dest;
}
let cwd = resolve(argv.cwd);
let target = resolve(cwd, dest);
let isYarn = argv.yarn && hasCommand('yarn');
let exists = isDir(target);
if (exists && !argv.force) {
return error(
'Refusing to overwrite current directory! Please specify a different destination or use the `--force` flag',
1
);
}
if (exists && argv.force) {
let { enableForce } = await prompt({
type: 'confirm',
name: 'enableForce',
message: `You are using '--force'. Do you wish to continue?`,
default: false,
});
if (enableForce) {
info('Initializing project in the current directory!');
} else {
return error('Refusing to overwrite current directory!', 1);
}
}
// Use `--name` value or `dest` dir's name
argv.name = argv.name || dest;
let { errors } = isValidName(argv.name);
if (errors) {
errors.unshift(`Invalid package name: ${argv.name}`);
return error(errors.map(capitalize).join('\n ~ '), 1);
}
if (!repo.includes('/')) {
repo = `${ORG}/${repo}`;
info(`Assuming you meant ${repo}...`);
}
// Attempt to fetch the `template`
let archive = await gittar.fetch(repo).catch(err => {
err = err || { message: 'An error occured while fetching template.' };
return error(
err.code === 404
? `Could not find repository: ${repo}`
: (argv.verbose && err.stack) || err.message,
1
);
});
let spinner = ora({
text: 'Creating project',
color: 'magenta',
}).start();
// Extract files from `archive` to `target`
// TODO: read & respond to meta/hooks
let keeps = [];
await gittar.extract(archive, target, {
strip: 2,
filter(path, obj) {
if (path.includes('/template/')) {
obj.on('end', () => {
if (obj.type === 'File' && !isMedia(obj.path)) {
keeps.push(obj.absolute);
}
});
return true;
}
},
});
if (keeps.length) {
// eslint-disable-next-line
let dict = new Map();
// TODO: concat author-driven patterns
['name'].forEach(str => {
// if value is defined
if (argv[str] !== void 0) {
dict.set(new RegExp(`{{\\s?${str}\\s}}`, 'g'), argv[str]);
}
});
// Update each file's contents
let buf,
entry,
enc = 'utf8';
for (entry of keeps) {
buf = await fs.readFile(entry, enc);
dict.forEach((v, k) => {
buf = buf.replace(k, v);
});
await fs.writeFile(entry, buf, enc);
}
} else {
return error(`No \`template\` directory found within ${repo}!`, 1);
}
spinner.text = 'Parsing `package.json` file';
// Validate user's `package.json` file
let pkgData,
pkgFile = resolve(target, 'package.json');
if (pkgFile) {
pkgData = JSON.parse(await fs.readFile(pkgFile));
// Write default "scripts" if none found
pkgData.scripts =
pkgData.scripts || (await addScripts(pkgData, target, isYarn));
} else {
warn('Could not locate `package.json` file!');
}
// Update `package.json` key
if (pkgData) {
spinner.text = 'Updating `name` within `package.json` file';
pkgData.name = argv.name.toLowerCase().replace(/\s+/g, '_');
}
// Find a `manifest.json`; use the first match, if any
let files = await promisify(glob)(target + '/**/manifest.json');
let manifest = files[0] && JSON.parse(await fs.readFile(files[0]));
if (manifest) {
spinner.text = 'Updating `name` within `manifest.json` file';
manifest.name = manifest.short_name = argv.name;
// Write changes to `manifest.json`
await fs.writeFile(files[0], JSON.stringify(manifest, null, 2));
if (argv.name.length > 12) {
// @see https://developer.chrome.com/extensions/manifest/name#short_name
process.stdout.write('\n');
warn('Your `short_name` should be fewer than 12 characters.');
}
}
if (pkgData) {
// Assume changes were made ¯\_(ツ)_/¯
await fs.writeFile(pkgFile, JSON.stringify(pkgData, null, 2));
}
// Copy over template.html
const templateSrc = resolve(__dirname, '../resources/template.html');
await promisify(copy)(templateSrc, join(resolve(cwd, dest), 'template.html'));
if (argv.install) {
spinner.text = 'Installing dependencies';
await install(target, isYarn);
}
spinner.succeed('Done!\n');
if (argv.git) {
await initGit(target);
}
let pfx = isYarn ? 'yarn' : 'npm run';
return (
trim(`
To get started, cd into the new directory:
${green('cd ' + dest)}
To start a development live-reload server:
${green(pfx + ' start')}
To create a production build (in ./build):
${green(pfx + ' build')}
To start a production HTTP/2 server:
${green(pfx + ' serve')}
`) + '\n'
);
};
|
JavaScript
| 0.000001 |
@@ -605,16 +605,21 @@
png%7Cgif%7C
+webp%7C
mp4%7Cmov%7C
|
0ff7e3557804006f90ffee7ca6922df910df8954
|
Update failure.js
|
empty/failure.js
|
empty/failure.js
|
use "strict";
function no_close_bracket() {
} // comment for failure
|
JavaScript
| 0.000001 |
@@ -1,18 +1,4 @@
-use %22strict%22;%0A
func
|
90a914f03f279115731d8014dc193418b7f1f669
|
add category only in the event of a two word message resolves issue #3
|
client/src/app/app.js
|
client/src/app/app.js
|
(function() {
'use strict';
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
function config($stateProvider, $urlRouterProvider, $logProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
//$logProvider.debugEnabled(true);
$httpProvider.interceptors.push('httpInterceptor');
$stateProvider
.state('home',{
url: '/',
templateUrl: 'src/app/charlie/chat.tpl.html',
controller: 'MainCtrl as vm'
}
);
}
function MainCtrl($firebaseObject, $log, Auth, $firebaseArray, Users, messages, brain) {
var vm = this;
vm.message = '';
vm.needPlot = false;
vm.addUserMessage = function(uid, message){
vm.message='';
return messages.addUserMessage(uid,message);
};
vm.respond = function(messageRef){
var messageBodyRef = messageRef.child('body');
var messageBodyObject = $firebaseObject(messageBodyRef);
messageBodyObject.$loaded().then(function(data){
vm.needPlot = false;
if (data.$value.includes('add')){
var category = data.$value.replace('add ','');
return Users.addTimestamp(vm.uid, category).then(function(){
return messages.addZeeMessage(vm.uid, category +' added');
});
}
else if (data.$value.includes('today')){
var otherCategory = data.$value.replace(' today','');
Users.sumTimestampTypes(vm.uid, otherCategory, brain.getDate(Date.now())).then(function(value){
messages.addZeeMessage(vm.uid, value +' '+ otherCategory);
});
}
else if (data.$value.includes('yesterday')){
var thirdCategory = data.$value.replace(' yesterday','');
Users.sumTimestampTypes(vm.uid, thirdCategory, brain.getDate(brain.getYesterday())).then(function(value){
messages.addZeeMessage(vm.uid, value +' '+ thirdCategory);
});
}
else if(data.$value.includes('plot')){
vm.needPlot = true;
if(data.$value.includes('daily')){
var TESTER = document.getElementById('tester');
var keyWord = data.$value.replace('plot daily ','');
Users.getDailyData(vm.uid, keyWord, 20160128, 20160130).then(function(xy){
Plotly.plot( TESTER, [xy], {
margin: { t: 0 }
} );
});
}
if(data.$value.includes('cumulative')){
var LESTER = document.getElementById('tester');
var keyWordTwo = data.$value.replace('plot cumulative ','');
Users.getCumulativeDailyData(vm.uid, keyWordTwo, 20160128, 20160130).then(function(xy){
Plotly.plot( LESTER, [xy], {
margin: { t: 0 }
} );
});
}
}
else{
messages.addZeeMessage(vm.uid, 'I am at a loss for words');
}
});
};
vm.submitter = function(uid, message){
return vm.addUserMessage(uid, message).then(function(messageRef){
return vm.respond(messageRef);
});
};
Auth.login().then(function(loginInfo){
vm.messageString = loginInfo[0];
vm.uid = loginInfo[1];
vm.messagesList = $firebaseArray(vm.messageString);
});
}
function run($log) {
$log.debug('App is running!');
}
angular.module('app', [
'ui.router',
'ngMaterial',
'firebase',
'getting-started',
'common.header',
'common.footer',
'common.services.data',
'common.directives.version',
'common.filters.uppercase',
'common.interceptors.http',
'templates',
/*--YEOMAN-HOOK--*/
'common.factories.brain',
'common.factories.messages',
'common.factories.users',
'common.factories.view',
'common.factories.auth',
'common.factories.isAnonymousService',
'common.factories.tester',
'common.directives.firstComponent',
'common.controllers.FirstComponentDirectiveController',
])
.config(config)
.run(run)
.controller('MainCtrl', MainCtrl)
.constant('FirebaseUrl', 'http://zee.firebaseio.com/')
.value('version', '1.1.4');
})();
|
JavaScript
| 0.000001 |
@@ -1059,30 +1059,181 @@
-if (data.$valu
+var lastUserMessage = data.$value;%0A var numberOfWordsInMessage = lastUserMessage.split(' ').length;%0A if (numberOfWordsInMessage === 2 && lastUserMessag
e.includ
|
7f25781bfcdc5d9704e733906fc948118ab3e096
|
Update common error logger
|
gulp/util/compileLogger.js
|
gulp/util/compileLogger.js
|
import gulpUtil from 'gulp-util';
import prettifyTime from './prettifyTime';
import handleErrors from './handleErrors';
export default ( err, stats ) => {
if ( err ) throw new gulpUtil.PluginError( 'webpack', err );
let statColor = stats.compilation.warnings.length < 1 ? 'green' : 'yellow';
if ( stats.compilation.errors.length > 0 ) {
stats.compilation.errors.forEach(( error ) => {
handleErrors( error );
statColor = 'red';
});
} else {
const compileTime = prettifyTime( stats.endTime - stats.startTime );
gulpUtil.log( gulpUtil.colors[ statColor ]( stats ));
gulpUtil.log( 'Compiled with', gulpUtil.colors.cyan( 'webpack:development' ), 'in', gulpUtil.colors.magenta( compileTime ));
}
};
export function commonError( callback, err ) {
handleErrors( `Error in plugin [${ err.plugin || 'gulp-postcss' }]` );
gulpUtil.log( gulpUtil.colors.red( err.message ));
return callback();
}
|
JavaScript
| 0 |
@@ -905,16 +905,94 @@
age ));%0A
+ if ( err.stack ) %7B%0A gulpUtil.log( gulpUtil.colors.red( err.stack ));%0A %7D%0A
return
|
d92fda5e9630a8fe9648874b4c360b3ed64e592f
|
Correct codekit include example
|
inc/js/plugins.js
|
inc/js/plugins.js
|
// https://incident57.com/codekit/help.html#javascript
// e.g. // @codekit-prepend plugins/jquery.js
|
JavaScript
| 0.000001 |
@@ -76,16 +76,17 @@
prepend
+%22
plugins/
@@ -94,9 +94,10 @@
query.js
+%22
%0A
|
2c8a923851402afef5af304063d22fdeeb4904ab
|
comment typo fix
|
example/index.js
|
example/index.js
|
const startsWithEmoji = require("../lib");
console.log(startsWithEmoji(":house: sweet home!"));
// => { startsWithEmoji: true, emoji: ':house:' }
console.log(startsWithEmoji("What a nice :gift:!"));
// => { startsWithEmoji: false, emoji: undefined }
|
JavaScript
| 0 |
@@ -99,40 +99,8 @@
/ =%3E
- %7B startsWithEmoji: true, emoji:
':h
@@ -105,18 +105,16 @@
:house:'
- %7D
%0A%0Aconsol
@@ -169,41 +169,8 @@
/ =%3E
- %7B startsWithEmoji: false, emoji:
und
@@ -179,7 +179,5 @@
ined
- %7D
%0A
|
a79fdba9ef6da083fe8c7f3455bd1a031afada09
|
Use octokit/rest
|
bin/todo.js
|
bin/todo.js
|
#!/usr/bin/env node
const program = require('commander')
const chalk = require('chalk')
const GitHubAPI = require('github')
const pushHandler = require('../src/push-handler')
const fs = require('fs')
const path = require('path')
program
.option('-o, --owner <owner>', 'owner')
.option('-r, --repo <repo>', 'repo')
.option('-s, --sha <sha>', 'sha')
.option('-f, --file <file>', 'file')
.parse(process.argv)
const issues = []
const { owner, repo, file } = program
const github = new GitHubAPI({})
if (file) {
github.repos.getCommit = () => ({ data: fs.readFileSync(path.resolve(file), 'utf8') })
github.gitdata.getCommit = () => ({ data: { parents: [] } })
}
github.issues.create = issue => issues.push(issue)
github.search.issues = () => ({ data: { total_count: 0 } })
const context = {
event: 'push',
id: 1,
log: () => {},
config: (_, obj) => obj,
repo: (o) => ({ owner, repo, ...o }),
payload: {
ref: 'refs/heads/master',
repository: {
owner,
name: repo,
master_branch: 'master'
},
head_commit: {
id: program.sha || 1,
author: {
username: owner
}
}
},
github
}
pushHandler(context)
.then(() => {
issues.forEach(issue => {
console.log(chalk.gray('---'))
console.log(chalk.gray('Title:'), chalk.bold(issue.title))
console.log(chalk.gray('Body:\n'), issue.body)
console.log(chalk.gray('---'))
})
})
.catch(e => {
if (e.code === 404) {
console.error('That combination of owner/repo/sha could not be found.')
} else {
console.error(e)
}
})
|
JavaScript
| 0 |
@@ -88,25 +88,23 @@
)%0Aconst
-GitHubAPI
+octokit
= requi
@@ -111,15 +111,24 @@
re('
-github'
+@octokit/rest')(
)%0Aco
@@ -480,41 +480,8 @@
am%0A%0A
-const github = new GitHubAPI(%7B%7D)%0A
if (
@@ -490,22 +490,23 @@
le) %7B%0A
-github
+octokit
.repos.g
@@ -580,22 +580,23 @@
') %7D)%0A
-github
+octokit
.gitdata
@@ -644,22 +644,23 @@
%7D %7D)%0A%7D%0A
-github
+octokit
.issues.
@@ -696,22 +696,23 @@
(issue)%0A
-github
+octokit
.search.
@@ -1129,16 +1129,25 @@
github
+: octokit
%0A%7D%0A%0Apush
|
ab860c8b09b17ef49bc584716f8235b898f05dde
|
clear code
|
source/jquery.autoload.js
|
source/jquery.autoload.js
|
/**
* Autoload
*/
(function($) {
// Autoload namespace: private properties and methods
var Autoload = {
/**
* Include necessary CSS file
*/
css: function(file, options) {
var collection = $("link[rel=stylesheet]");
var path = options.basePath + options.cssPath + file;
for (var i in collection) {
if (path == collection[i].href) {
// is loaded
return true;
}
}
var element = $("<link/>");
element.attr({
"href": path,
"media": "all",
"rel": "stylesheet",
"type": "text/css"
});
$("head").append(element);
return true;
},
/**
* Search path to js file
*/
findPath: function(baseFile) {
baseFile = baseFile.replace(/\./g, "\\.");
var collection = $("script");
var reg = eval("/^(.*)" + baseFile + "$/");
var path = null;
for (var i in collection) {
if (null === path) {
var p = reg.exec(collection[i].src);
if (null !== p) {
return p[1];
}
}
}
return path;
},
/**
* Include necessary JavaScript file
*/
js: function(file, options) {
var collection = $("script");
var path = options.basePath + options.jsPath + file;
for (var i = 0; i < collection.length; i++) {
if (path == collection[i].src) {
// is loaded
return true;
}
}
// When local used in Firefox got [Exception... "Access to restricted URI denied" code: "1012"]
$.ajax({
url: path,
dataType: "script",
success: function(data, textStatus, XMLHttpRequest) {
if (options.success) {
options.success;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest, textStatus, errorThrown);
}
});
return true;
}
};
/*
* Autoload namespace: public properties and methods
*/
$.autoload = {
css: function(names, options) {
var basePath = Autoload.findPath(options.baseFile);
var cssPath = (undefined === options.cssPath) ? "css/" : options.cssPath;
options = {"basePath": basePath, "cssPath": cssPath};
if ("string" === typeof names) {
names = [names];
}
for (i in names) {
Autoload.css(names[i], options);
}
},
js: function(names, options) {
var basePath = Autoload.findPath(options.baseFile);
var jsPath = (undefined === options.jsPath) ? "plugins/" : options.jsPath;
options = {"basePath": basePath, "jsPath": jsPath};
if ("string" === typeof names) {
names = [names];
}
for (var i in names) {
Autoload.js(names[i], options);
}
}
};
//$.wysiwyg.autoload.init();
})(jQuery);
|
JavaScript
| 0.000081 |
@@ -311,32 +311,33 @@
%7B%0A%09%09%09if (path ==
+=
collection%5Bi%5D.h
@@ -339,24 +339,24 @@
%5Bi%5D.href) %7B%0A
-
%09%09%09%09// is lo
@@ -1140,16 +1140,10 @@
r i
-= 0; i %3C
+in
col
@@ -1153,20 +1153,8 @@
tion
-.length; i++
) %7B%0A
@@ -1167,16 +1167,17 @@
(path ==
+=
collect
@@ -2013,26 +2013,48 @@
%0A%09%09for (
-i in names
+var i = 0; i %3C names.length; i++
) %7B%0A%09%09%09A
@@ -2389,16 +2389,34 @@
r i
-in names
+= 0; i %3C names.length; i++
) %7B%0A
|
67f2aaf0407eb22d8d8b8b55a941c311ab7359be
|
Update employment-support-allowance.js
|
lib/projects/employment-support-allowance.js
|
lib/projects/employment-support-allowance.js
|
{
"id":3,
"name":"Apply for Employment Support Allowance (ESA)",
"description": "",
"theme": "Health & Disability",
"location": "Leeds",
"phase":"discovery",
"sro":"Justin Russell",
"service_man":"Adam Tostevin",
"phase-history":{
"discovery": [
{"label":"Started", "date": "Nov 2015"}
]
},
"priority":"Top"
}
|
JavaScript
| 0 |
@@ -80,19 +80,127 @@
tion%22: %22
+Discovery is looking at how we can engage better with new ESA customers and allow users to claim ESA online.
%22,%0A
-
%22theme
@@ -420,16 +420,284 @@
%22%7D%0A %5D
+,%0A %22alpha%22: %5B%0A %7B%22label%22:%22Predicted%22, %22date%22: %22Jan 2016%22%7D%0A %5D,%0A %22beta%22: %5B%0A %7B%22label%22:%22Predicted%22, %22date%22: %22March 2016%22%7D,%0A %7B%22label%22:%22Private Beta Predicted%22, %22date%22: %22April 2016%22%7D,%0A %7B%22label%22:%22Public Beta Predicted%22, %22date%22: %22June 2016%22%7D %0A %5D,
%0A %7D,%0A
@@ -713,9 +713,10 @@
%22:%22Top%22%0A
-
%7D
+%0A
|
9abc8fc165714929d76a1780b9e31f56225f5d4e
|
Allow listeners to be added for end of queue event
|
app/utils/asyncQueueStructures.js
|
app/utils/asyncQueueStructures.js
|
class Stack {
constructor() {
this.storage = [];
this.size = 0;
}
push(val) {
this.storage[this.size++] = val;
}
pop() {
if (this.size) {
return this.storage.splice(--this.size, 1)[0];
}
}
}
class Queue {
constructor() {
this.inbox = new Stack();
this.outbox = new Stack();
}
enqueue(val) {
this.inbox.push(val);
}
dequeue() {
if (this.outbox.size === 0) {
while (this.inbox.size) {
this.outbox.push(this.inbox.pop());
}
}
return this.outbox.pop();
}
getSize() {
return this.inbox.size + this.outbox.size;
}
}
class AsyncQueue {
constructor() {
this._queue = new Queue();
this.active = false;
this.size = 0;
}
add(action, delay, ...args) {
this._queue.enqueue([action, delay, args]);
this.size++;
if (!this.active) {
this.active = true;
setTimeout(() => this.runQueue(), delay);
}
return this.size;
}
runQueue() {
if (!this.size) {
return false;
} else {
this.size--;
let [action, delay, args] = this._queue.dequeue();
if (this.size) {
setTimeout(() => this.runQueue(), delay);
} else {
this.active = false;
}
action.apply(action, args);
}
}
}
export default AsyncQueue;
|
JavaScript
| 0 |
@@ -715,24 +715,62 @@
s.size = 0;%0A
+ this._endListeners = new Queue();%0A
%7D%0A add(ac
@@ -1217,85 +1217,389 @@
-%7D else %7B%0A this.active = false;%0A %7D%0A action.apply(action, args
+ action.apply(action, args);%0A %7D else %7B%0A action.apply(action, args);%0A let listener;%0A while (this._endListeners.getSize()) %7B%0A listener = this._endListeners.dequeue();%0A listener();%0A %7D%0A this.active = false;%0A %7D%0A %7D%0A %7D%0A listenForEnd(endFn) %7B%0A if (typeof endFn === 'function') %7B%0A this._endListeners.enqueue(endFn
);%0A
|
bb816d369325b02f2c0fc22956918147e8c09a0d
|
Improve handling to multipel concurrent diffs
|
js/components/WindowManager.js
|
js/components/WindowManager.js
|
import React from "react";
import PropTypes from "prop-types";
import {
snapDiffManyToMany,
boundingBox,
snapWithinDiff,
snap,
traceConnection
} from "../snapUtils";
const WINDOW_HEIGHT = 116;
const WINDOW_WIDTH = 275;
const abuts = (a, b) => {
const wouldMoveTo = snap(a, b);
return wouldMoveTo.x !== undefined || wouldMoveTo.y !== undefined;
};
const applyDiff = (a, b) => ({
x: a.x + b.x,
y: a.y + b.y
});
const applyMultipleDiffs = (initial, ...diffs) =>
diffs.reduce(applyDiff, initial);
class WindowManager extends React.Component {
constructor(props) {
super(props);
this.windowNodes = {};
this.state = {};
this.getRef = this.getRef.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.centerWindows = this.centerWindows.bind(this);
}
componentDidMount() {
window.addEventListener("resize", this.centerWindows);
const { innerHeight, innerWidth } = window;
if (innerHeight || innerWidth) {
this.centerWindows();
}
}
componentWillUnmount() {
window.removeEventListener("resize", this.centerWindows);
}
centerWindows() {
const { innerHeight, innerWidth } = window;
const state = {};
const keys = this.windowKeys();
const totalHeight = keys.length * WINDOW_HEIGHT;
keys.forEach((key, i) => {
const offset = WINDOW_HEIGHT * i;
state[key] = {
left: innerWidth / 2 - WINDOW_WIDTH / 2,
top: innerHeight / 2 - totalHeight / 2 + offset
};
});
this.setState(state);
}
getRef(key, node) {
// If we are unmounting, the node might be null;
this.windowNodes[key] = node;
}
//
getWindowNodes() {
return this.windowKeys()
.map(key => {
const node = this.windowNodes[key];
return node && this.nodeInfo(node, key);
})
.filter(Boolean);
}
nodeInfo(node, key) {
const child = node.childNodes[0];
const { height, width } = child.getBoundingClientRect();
const { offsetLeft, offsetTop } = node;
return { key, x: offsetLeft, y: offsetTop, height, width };
}
movingAndStationaryNodes(key) {
const windows = this.getWindowNodes();
const targetNode = windows.find(node => node.key === key);
let movingSet = new Set([targetNode]);
// Only the main window brings other windows along.
if (key === "main") {
const findAllConnected = traceConnection(abuts);
movingSet = findAllConnected(windows, targetNode);
}
const stationary = windows.filter(w => !movingSet.has(w));
const moving = Array.from(movingSet);
return [moving, stationary];
}
handleMouseDown(key, e) {
if (!e.target.classList.contains("draggable")) {
return;
}
// Prevent dragging from highlighting text.
e.preventDefault();
const [moving, stationary] = this.movingAndStationaryNodes(key);
const mouseStart = { x: e.clientX, y: e.clientY };
const browserSize = {
width: window.innerWidth,
height: window.innerHeight
};
const box = boundingBox(moving);
const handleMouseMove = ee => {
const proposedDiff = {
x: ee.clientX - mouseStart.x,
y: ee.clientY - mouseStart.y
};
const proposedWindows = moving.map(node => ({
...node,
...applyDiff(node, proposedDiff)
}));
const proposedBox = {
...box,
...applyDiff(box, proposedDiff)
};
const snapDiff = snapDiffManyToMany(proposedWindows, stationary);
const withinDiff = snapWithinDiff(proposedBox, browserSize);
const finalDiff = applyMultipleDiffs(proposedDiff, snapDiff, withinDiff);
const stateDiff = moving.reduce((diff, window) => {
const newWindowLocation = applyDiff(window, finalDiff);
diff[window.key] = {
top: newWindowLocation.y,
left: newWindowLocation.x
};
return diff;
}, {});
this.setState(stateDiff);
};
window.addEventListener("mouseup", () => {
window.removeEventListener("mousemove", handleMouseMove);
});
window.addEventListener("mousemove", handleMouseMove);
}
// Keys for the visible windows
windowKeys() {
// TODO: Iterables can probably do this better.
return Object.keys(this.props.windows).filter(
key => !!this.props.windows[key]
);
}
render() {
const style = {
position: "absolute"
};
const parentStyle = {
position: "absolute",
width: 0,
height: 0,
top: 0,
left: 0
};
return (
<div style={parentStyle}>
{this.windowKeys().map(key => {
const position = this.state[key];
return (
position && (
<div
onMouseDown={e => this.handleMouseDown(key, e)}
ref={node => this.getRef(key, node)}
style={{ ...style, ...position }}
key={key}
>
{this.props.windows[key]}
</div>
)
);
})}
</div>
);
}
}
WindowManager.propTypes = {
windows: PropTypes.object.isRequired
};
export default WindowManager;
|
JavaScript
| 0 |
@@ -425,16 +425,41 @@
.y%0A%7D);%0A%0A
+// TODO: This should not%0A
const ap
@@ -503,24 +503,244 @@
) =%3E
+ %7B
%0A
-diffs.reduce(
+const metaDiff = diffs.reduce((meta, diff) =%3E (%7B%0A // Use the smallest non-zero diff for each axis.%0A x: meta.x === 0 ? diff.x : Math.min(meta.x, diff.x),%0A y: meta.y === 0 ? diff.y : Math.min(meta.y, diff.y)%0A %7D));%0A return
appl
@@ -748,18 +748,30 @@
Diff
-,
+(
initial
-)
+, metaDiff);%0A%7D
;%0A%0Ac
|
df9842ce1be11165aa98a179e14b6e1836d7c842
|
Stop overwriting mode commands.
|
app/js/modes.js
|
app/js/modes.js
|
/*global define, _, zed */
define(function(require, exports, module) {
"use strict";
plugin.consumes = ["eventbus", "command"];
plugin.provides = ["modes"];
return plugin;
function longestFirst(a, b) {
return b.length - a.length;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function plugin(options, imports, register) {
var path = require("./lib/path");
var eventbus = imports.eventbus;
var command = imports.command;
eventbus.declare("modesloaded");
eventbus.declare("modeset");
var modes = {};
// Mappings from file extension to mode name, e.g. "js" -> "javascript"
var extensionMapping = {};
var extensionsByLength = [];
// Mappings from particular file names to mode name, e.g. "Makefile" -> "makefile"
var filenameMapping = {};
// Mappings from shebang lines to mode name, e.g. "python3" -> "python"
var shebangMapping = {};
// Mode to use if all else fails
var fallbackMode = {
language: "text",
name: "Plain Text",
highlighter: "ace/mode/text",
handlers: {},
commands: {},
preferences: {},
keys: {},
isFallback: true
};
var api = {
hook: function() {
eventbus.on("configchanged", function(config) {
modes = config.getModes();
updateAllModes();
});
},
allModes: function() {
return Object.keys(modes);
},
get: function(language) {
return modes[language];
},
getModeForSession: function(session) {
var filename = path.filename(session.filename);
if (filenameMapping[filename]) {
return api.get(filenameMapping[filename]);
}
if (filename.indexOf(".") > -1) {
for (var i = 0; i < extensionsByLength.length; ++i) {
var ext = extensionsByLength[i];
if (endsWith(filename, "." + ext)) {
return api.get(extensionMapping[ext]);
}
}
}
var shebang_line = session.getLine(0);
if (shebang_line.slice(0, 2) == "#!") {
for (var shebang in shebangMapping) {
if (shebang_line.indexOf(shebang) > 0) {
return api.get(shebangMapping[shebang]);
}
}
}
return fallbackMode;
},
setSessionMode: function(session, mode) {
if (typeof mode === "string") {
mode = api.get(mode);
}
if (mode) {
session.mode = mode;
session.setMode(mode.highlighter);
session.clearAnnotations();
eventbus.emit("modeset", session, mode);
}
}
};
function normalizeModes() {
_.each(modes, function(mode, name) {
mode.language = name;
// Normalize
if (!mode.events) {
mode.events = {};
}
if (!mode.commands) {
mode.commands = {};
}
if (!mode.keys) {
mode.keys = {};
}
if (!mode.preferences) {
mode.preferences = {};
}
if (!mode.handlers) {
mode.handlers = {};
}
});
}
function updateAllModes() {
console.log("Updating modes...");
normalizeModes();
updateMappings();
eventbus.emit("modesloaded", api);
declareAllModeCommands();
}
function updateMappings() {
extensionMapping = {};
filenameMapping = {};
shebangMapping = {};
_.each(modes, function(mode) {
if (mode.extensions) {
mode.extensions.forEach(function(ext) {
extensionMapping[ext] = mode.language;
});
}
if (mode.filenames) {
mode.filenames.forEach(function(filename) {
filenameMapping[filename] = mode.language;
});
}
shebangMapping[mode.language] = mode.language;
if (mode.shebangs) {
mode.shebangs.forEach(function(shebang) {
shebangMapping[shebang] = mode.language;
});
}
});
extensionsByLength = Object.keys(extensionMapping).sort(longestFirst);
}
function declareAllModeCommands() {
_.each(api.allModes(), function(modeName) {
declareModeCommands(api.get(modeName));
});
eventbus.emit("commandsloaded");
}
function declareModeCommands(mode) {
command.define("Configuration:Mode:" + mode.name, {
doc: "Begin using this mode for the current document.",
exec: function(edit, session) {
api.setSessionMode(session, mode);
},
readOnly: true
});
_.each(mode.commands, function(cmd, name) {
var existingCommand = command.lookup(name);
if (!existingCommand) {
// Declare it as a special mode command, with an implementation
// specific to the mode
var modeCommands = {};
modeCommands[mode.language] = cmd;
var commandSpec = {
doc: "Begin using this mode for the current document.",
exec: function(edit, session, callback) {
var cmd = commandSpec.modeCommand[session.mode.language];
if (cmd) {
zed.getService("sandbox").execCommand(name, cmd, session, function(err, result) {
if (err) {
return console.error(err);
}
_.isFunction(callback) && callback(err, result);
});
} else {
if (_.isFunction(callback)) {
callback("not-supported");
} else {
eventbus.emit("sessionactivityfailed", session, "Command " + name + " not supported for this mode");
}
}
},
readOnly: true,
modeCommand: modeCommands
};
command.define(name, commandSpec);
} else {
existingCommand.modeCommand[mode.language] = cmd;
}
});
}
register(null, {
modes: api
});
}
});
|
JavaScript
| 0 |
@@ -6140,88 +6140,8 @@
= %7B%0A
- doc: %22Begin using this mode for the current document.%22,%0A
|
5a8db2173a6caeb37de5cf84c5f56ecdb3d68a3d
|
fix bad reference to pockets.
|
js/frontend/providers/watch.js
|
js/frontend/providers/watch.js
|
'use strict';
define(['./module', 'darkwallet'], function (providers, DarkWallet) {
providers.factory('watch', ['$wallet', function($wallet) {
// - start provider
/**
* Watch / ReadOnly Pockets from contact
*/
function WatchProvider() {
}
// Remove a watch only pocket from a contact
WatchProvider.prototype.removePocket = function(contact) {
var identity = DarkWallet.getIdentity();
var pocketId = contact.data.name;
var pocket = identity.wallet.pockets.pockets.readonly[pocketId];
if (pocket) {
var removed = pocket.destroy();
removed.forEach(function(walletAddress) {
$wallet.removeAddress(walletAddress);
});
}
};
// Add a watch only pocket from a contact
WatchProvider.prototype.initPocket = function(contact) {
var identity = DarkWallet.getIdentity();
var pocketId = contact.data.name;
// Create the pocket and addreses
var pocket = identity.wallet.pockets.initPocketWallet('readonly', pocketId);
var addresses = pocket.fromContact(contact);
// Load addresses into scope
addresses.forEach(function(walletAddress) {
// Init address
$wallet.initAddress(walletAddress);
});
};
// Rename a pocket linked to some contact
WatchProvider.prototype.renamePocket = function(newName, prevName) {
var identity = DarkWallet.getIdentity();
var pockets = identity.wallet.pockets.getPockets('readonly');
if (prevName && prevName !== newName && pockets[prevName]) {
var newIndex = 'readonly'+newName;
var pocket = pockets[prevName];
// Save the name in the pocket
pocket.name = newName;
pocket.data.id = newName;
// Reindex with the new pocketId
pockets[newName] = pocket;
delete pockets[prevName];
// If any addresses are using the old index reindex them
var reindexed = [];
identity.wallet.pubKeys.forEach(function(walletAddress) {
if (walletAddress.index[0] === ('readonly:'+prevName)) {
// Save the index before changing it
reindexed.push(walletAddress.index.slice());
// Change the index to the new name
walletAddress.index[0] = newIndex;
identity.wallet.pubKeys[newIndex] = walletAddress;
}
});
// Now delete all reindexed
reindexed.forEach(function(seq) {
delete identity.wallet.pubKeys[seq];
});
}
};
// Remove watched contact key
WatchProvider.prototype.removeKey = function(contact, key) {
var identity = DarkWallet.getIdentity();
if (key && key.address && key.type !== 'stealth') {
var pocket = identity.wallet.pockets.getPocket(contact.data.name, 'readonly');
var walletAddress = pocket.removeAddress(key.address);
if (walletAddress) {
$wallet.removeAddress(walletAddress);
}
}
};
// Add watched contact key
WatchProvider.prototype.addKey = function(contact, key) {
var identity = DarkWallet.getIdentity();
var pocket = identity.pockets.getPocket(contact.data.name, 'readonly');
var walletAddress = pocket.createAddress(key);
if (walletAddress) {
$wallet.initAddress(walletAddress);
}
};
// Rename watched contact key
WatchProvider.prototype.renameKey = function(contact, key) {
var identity = DarkWallet.getIdentity();
var pocket = identity.pockets.getPocket(contact.data.name, 'readonly');
if (key && key.address && key.type !== 'stealth') {
var seq = ['readonly:'+contact.data.name, key.address];
var walletAddress = identity.wallet.pubKeys[seq];
if (walletAddress) {
walletAddress.label = key.label;
}
}
};
// - end provider
return new WatchProvider($wallet);
}]);
});
|
JavaScript
| 0.000001 |
@@ -3091,32 +3091,39 @@
cket = identity.
+wallet.
pockets.getPocke
@@ -3454,16 +3454,23 @@
dentity.
+wallet.
pockets.
|
24b867ea19647e149929cc0ec7ede97d6a7d530d
|
Make modal contents scrollable
|
client/utils/Modal.js
|
client/utils/Modal.js
|
import React from "react";
import Modal from "react-modal";
export const modalStyles = {
overlay: {
backgroundColor: "rgba(238, 238, 238, 0.98)"
},
content: {
backgroundColor: "transparent",
border: "none",
maxWidth: "800px",
top: "50%",
left: "50%",
right: "auto",
bottom: "auto",
marginRight: "-50%",
marginBottom: "-50%",
transform: "translate(-50%, -50%)",
padding: "0"
}
};
export default props => <Modal style={modalStyles} {...props} />;
|
JavaScript
| 0.000001 |
@@ -144,17 +144,90 @@
, 0.98)%22
+,%0A overflow: %22auto%22,%0A display: %22flex%22,%0A justifyContent: %22center%22
%0A
-
%7D,%0A c
@@ -324,21 +324,17 @@
top:
-%2250%25%22
+0
,%0A le
@@ -341,13 +341,9 @@
ft:
-%2250%25%22
+0
,%0A
@@ -351,22 +351,17 @@
right:
-%22auto%22
+0
,%0A bo
@@ -366,22 +366,17 @@
bottom:
-%22auto%22
+0
,%0A ma
@@ -383,20 +383,18 @@
rgin
-Right: %22-50%25
+Top: %22auto
%22,%0A
@@ -415,52 +415,63 @@
m: %22
--50%25
+auto
%22,%0A
-transform: %22translate(-50%25, -50%25)
+position: %22relative%22,%0A overflow: %22visible
%22,%0A
|
b644515b3ebb82593c6303cd102d3920ebfc72bb
|
populate a contact email address
|
js/routes/application_route.js
|
js/routes/application_route.js
|
/**
*
*/
App.ApplicationRoute = Ember.Route.extend(
{
actions:
{
error: function(reason, transition)
{
console.log('--------------------------------------- error ---------------------------------------------------');
console.log(reason);
console.log(transition);
if (typeof reason.status !== 'undefined')
{
console.log('error status: ' + reason.status + ', transition: ' + transition);
if (parseInt(reason.status) == 403)
{
this.controllerFor('application').set('previousTransition', transition);
this.controllerFor('application').send('connect');
}
}
console.log('-------------------------------------------------------------------------------------------------');
}
},
beforeModel: function(transition)
{
var self = this, promise, glomeid = window.localStorage.getItem('glomeid');
// check our session
if (glomeid)
{
promise = this.store.find('user', glomeid).then(function(data)
{
self.controllerFor('application').send('loadCategories', transition.params.category);
});
}
else
{
promise = this.store.find('user');
}
return promise;
},
model: function(params, transition)
{
console.log('ApplicationRoute::model');
},
setupController: function(controller, model)
{
console.log('ApplicationRoute::setupController');
controller.get('controllers.application').send('setGlobals');
if (App.glomeid && App.glomeid != '')
{
this.store.find('user', App.glomeid).then(function(data)
{
window.localStorage.setItem('loggedin', true);
controller.get('controllers.application').set('loggedin', true);
});
}
controller.set('title', "Catalogue");
controller.set('categories', this.get('categories'));
}
});
|
JavaScript
| 0.999992 |
@@ -1781,17 +1781,24 @@
', %22
+Cashback
Catalog
-ue
%22);%0A
@@ -1855,15 +1855,170 @@
ies'));%0A
+ controller.set('contact', App.contact.email);%0A controller.set('contactMailto', 'mailto: ' + App.contact.email + '?subject=' + App.contact.subject);%0A
%7D%0A%7D);
|
64481ec868c515c4591a0bbe1a19687081eb97ad
|
stop travis failing on gdax trade timestamps
|
js/test/Exchange/test.trade.js
|
js/test/Exchange/test.trade.js
|
'use strict'
// ----------------------------------------------------------------------------
const log = require ('ololog')
, ansi = require ('ansicolor').nice
, chai = require ('chai')
, expect = chai.expect
, assert = chai.assert
/* ------------------------------------------------------------------------ */
module.exports = (exchange, trade, symbol, now) => {
assert.isOk (trade)
assert (typeof trade.id === 'undefined' || typeof trade.id === 'string')
assert (typeof trade.timestamp === 'number')
assert (trade.timestamp > 1230940800000) // 03 Jan 2009 - first block
//------------------------------------------------------------------
// console.log (exchange.iso8601 (trade.timestamp), exchange.iso8601 (now))
// The next assertion line breaks Kraken. They report trades that are
// approximately 500ms ahead of `now`. Tried synching system clock against
// different servers. Apparently, Kraken's own clock drifts by up to 10 (!) seconds.
const isExchangeTimeDrifting = [
'bitfinex',
'bitfinex2',
'kraken', // override for kraken and possibly other exchanges as well
].includes (exchange.id)
const adjustedNow = now + (isExchangeTimeDrifting ? 10000 : 0)
assert (trade.timestamp < adjustedNow, 'trade.timestamp is greater than or equal to current time: trade: ' + exchange.iso8601 (trade.timestamp) + ' now: ' + exchange.iso8601 (now))
//------------------------------------------------------------------
assert (trade.datetime === exchange.iso8601 (trade.timestamp))
const isExchangeLackingFilteringTradesBySymbol = [
'kraken', // override for kraken and possibly other exchanges as well, can't return private trades per symbol at all
].includes (exchange.id)
if (!isExchangeLackingFilteringTradesBySymbol)
assert (trade.symbol === symbol, 'trade symbol is not equal to requested symbol: trade: ' + trade.symbol + ' reqeusted: ' + symbol)
assert (typeof trade.type === 'undefined' || typeof trade.type === 'string')
assert (typeof trade.side === 'undefined' || trade.side === 'buy' || trade.side === 'sell')
assert (typeof trade.order === 'undefined' || typeof trade.order === 'string')
assert (typeof trade.price === 'number', 'trade.price is not a number')
assert (trade.price > 0)
assert (typeof trade.amount === 'number', 'trade.amount is not a number')
assert (trade.amount >= 0)
assert.isOk (trade.info)
}
|
JavaScript
| 0 |
@@ -1276,16 +1276,162 @@
0 : 0)%0A%0A
+ const exchangesExcludedFromTimestampCheck = %5B%0A 'gdax',%0A %5D%0A%0A if (!exchangesExcludedFromTimestampCheck.includes (exchange.id))%0A
asse
@@ -1607,16 +1607,17 @@
(now))%0A
+%0A
//--
|
79c2d22c2598aa61cee20db34078313a74d12dc1
|
remove assert require
|
spec/api-debugger-spec.js
|
spec/api-debugger-spec.js
|
const chai = require('chai')
const assert = require('assert')
const dirtyChai = require('dirty-chai')
const http = require('http')
const path = require('path')
const {closeWindow} = require('./window-helpers')
const BrowserWindow = require('electron').remote.BrowserWindow
const {expect} = chai
chai.use(dirtyChai)
describe('debugger module', () => {
const fixtures = path.resolve(__dirname, 'fixtures')
let w = null
beforeEach(() => {
w = new BrowserWindow({
show: false,
width: 400,
height: 400
})
})
afterEach(() => closeWindow(w).then(() => { w = null }))
describe('debugger.attach', () => {
it('fails when devtools is already open', done => {
w.webContents.on('did-finish-load', () => {
w.webContents.openDevTools()
try {
w.webContents.debugger.attach()
} catch (err) {
expect(w.webContents.debugger.isAttached()).to.be.true()
done()
}
})
w.webContents.loadURL(`file://${path.join(fixtures, 'pages', 'a.html')}`)
})
it('fails when protocol version is not supported', done => {
try {
w.webContents.debugger.attach('2.0')
} catch (err) {
expect(w.webContents.debugger.isAttached()).to.be.false()
done()
}
})
it('attaches when no protocol version is specified', done => {
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
expect(w.webContents.debugger.isAttached()).to.be.true()
done()
})
})
describe('debugger.detach', () => {
it('fires detach event', (done) => {
w.webContents.debugger.on('detach', (e, reason) => {
expect(reason).to.equal('target closed')
expect(w.webContents.debugger.isAttached()).to.be.false()
done()
})
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.detach()
})
})
describe('debugger.sendCommand', () => {
let server
afterEach(() => {
if (server != null) {
server.close()
server = null
}
})
it('returns response', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
return done(`unexpected error : ${err}`)
}
const callback = (err, res) => {
expect(err.message).to.not.exist()
expect(res.wasThrown).to.be.undefined()
expect(res.result.value).to.equal(6)
w.webContents.debugger.detach()
done()
}
const params = {'expression': '4+2'}
w.webContents.debugger.sendCommand('Runtime.evaluate', params, callback)
})
it('fires message event', done => {
const url = process.platform !== 'win32'
? `file://${path.join(fixtures, 'pages', 'a.html')}`
: `file:///${path.join(fixtures, 'pages', 'a.html').replace(/\\/g, '/')}`
w.webContents.loadURL(url)
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.on('message', (e, method, params) => {
if (method === 'Console.messageAdded') {
expect(params.message.level).to.equal('log')
expect(params.message.url).to.equal(url)
expect(params.message.text).to.equal('a')
w.webContents.debugger.detach()
done()
}
})
w.webContents.debugger.sendCommand('Console.enable')
})
it('returns error message when command fails', done => {
w.webContents.loadURL('about:blank')
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.sendCommand('Test', err => {
expect(err.message).to.equal("'Test' wasn't found")
w.webContents.debugger.detach()
done()
})
})
it('handles valid unicode characters in message', (done) => {
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.on('message', (event, method, params) => {
if (method === 'Network.loadingFinished') {
w.webContents.debugger.sendCommand('Network.getResponseBody', {
requestId: params.requestId
}, (_, data) => {
expect(data.body).to.equal('\u0024')
done()
})
}
})
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('\u0024')
})
server.listen(0, '127.0.0.1', () => {
w.webContents.debugger.sendCommand('Network.enable')
w.loadURL(`http://127.0.0.1:${server.address().port}`)
})
})
it('does not crash for invalid unicode characters in message', done => {
try {
w.webContents.debugger.attach()
} catch (err) {
done(`unexpected error : ${err}`)
}
w.webContents.debugger.on('message', (event, method, params) => {
// loadingFinished indicates that page has been loaded and it did not
// crash because of invalid UTF-8 data
if (method === 'Network.loadingFinished') {
done()
}
})
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('\uFFFF')
})
server.listen(0, '127.0.0.1', () => {
w.webContents.debugger.sendCommand('Network.enable')
w.loadURL(`http://127.0.0.1:${server.address().port}`)
})
})
})
})
|
JavaScript
| 0.000004 |
@@ -26,41 +26,8 @@
i')%0A
-const assert = require('assert')%0A
cons
|
697a67cf15ebbc563cfb76194bd80a2c7dbcd67f
|
resolve conflicts
|
src/themes/default/webpack.config.js
|
src/themes/default/webpack.config.js
|
// You can extend default webpack build here. Read more on docs: https://github.com/DivanteLtd/vue-storefront/blob/master/doc/Working%20with%20webpack.md
module.exports = function (config, { isClient, isDev }) {
return config
}
|
JavaScript
| 0.00004 |
@@ -122,26 +122,28 @@
/doc
-/Working%2520with%2520
+s/guide/core-themes/
webp
|
ad2927b3b22310909672ce51bf9a7b5d575a52a1
|
Add remote initialisation support
|
source/node/system/archiveManagement/ArchiveSource.js
|
source/node/system/archiveManagement/ArchiveSource.js
|
const VError = require("verror");
const AsyncEventEmitter = require("../events/AsyncEventEmitter.js");
const getUniqueID = require("../../tools/encoding.js").getUniqueID;
const createCredentials = require("../credentials.js");
const credentialsToSource = require("./marshalling.js").credentialsToSource;
const DefaultColour = "#000000";
const DefaultOrder = 1000;
const Status = {
LOCKED: "locked",
UNLOCKED: "unlocked",
PENDING: "pending"
};
function rehydrate(dehydratedString) {
const { name, id, sourceCredentials, archiveCredentials, type, colour } = JSON.parse(dehydratedString);
const source = new ArchiveSource(name, sourceCredentials, archiveCredentials, id);
source.type = type;
if (colour) {
source.colour = colour;
}
return source;
}
class ArchiveSource extends AsyncEventEmitter {
constructor(name, sourceCredentials, archiveCredentials, id = getUniqueID()) {
super();
if (createCredentials.isSecureString(sourceCredentials) !== true) {
throw new VError("Failed constructing archive source: Source credentials not in encrypted form");
}
if (createCredentials.isSecureString(archiveCredentials) !== true) {
throw new VError("Failed constructing archive source: Archive credentials not in encrypted form");
}
this._name = name;
this._id = id;
this._status = Status.LOCKED;
this._sourceCredentials = sourceCredentials;
this._archiveCredentials = archiveCredentials;
this._workspace = null;
this._colour = DefaultColour;
this.type = "";
this.order = DefaultOrder;
}
get colour() {
return this._colour;
}
get description() {
return {
name: this.name,
id: this.id,
status: this.status,
type: this.type,
colour: this.colour
};
}
get id() {
return this._id;
}
get name() {
return this._name;
}
get status() {
return this._status;
}
get workspace() {
return this._workspace;
}
set colour(newColour) {
if (/^$/.test(newColour) !== true) {
throw new VError(`Failed setting colour: Invalid format (expected hex): ${newColour}`);
}
this._colour = newColour;
this.emit("sourceColourUpdated", this.description);
}
dehydrate() {
if (this.status === Status.PENDING) {
return Promise.reject(new VError(`Failed dehydrating source: Source in pending state: ${this.id}`));
}
return Promise.resolve()
.then(() => {
const payload = {
id: this.id,
name: this.name,
type: this.type,
status: Status.LOCKED
};
if (this.status === Status.LOCKED) {
payload.sourceCredentials = this._sourceCredentials;
payload.archiveCredentials = this._archiveCredentials;
return payload;
}
return Promise.all([
this._sourceCredentials.toSecureString(this._archiveCredentials.password),
this._archiveCredentials.toSecureString(this._archiveCredentials.password)
]).then(([encSourceCredentials, encArchiveCredentials]) => {
payload.sourceCredentials = encSourceCredentials;
payload.archiveCredentials = encArchiveCredentials;
return payload;
});
})
.then(payload => JSON.stringify(payload))
.catch(err => {
throw new VError(err, `Failed dehydrating source: ${this.id}`);
});
}
lock() {
if (this.status !== Status.UNLOCKED) {
return Promise.reject(
new VError(`Failed locking source: Source in invalid state (${this.status}): ${this.id}`)
);
}
this._status = Status.PENDING;
return Promise.all([
this._sourceCredentials.toSecureString(this._archiveCredentials.password),
this._archiveCredentials.toSecureString(this._archiveCredentials.password)
])
.then(([encSourceCredentials, encArchiveCredentials]) => {
this._status = Status.LOCKED;
this._workspace = null;
this._sourceCredentials = encSourceCredentials;
this._archiveCredentials = encArchiveCredentials;
return this.dehydrate();
})
.then(() => {
this.emit("sourceLocked", this.description);
})
.catch(err => {
throw new VError(err, `Failed locking source: ${this.id}`);
});
}
unlock(masterPassword) {
if (this.status !== Status.LOCKED) {
return Promise.reject(
new VError(`Failed unlocking source: Source in invalid state (${this.status}): ${this.id}`)
);
}
this._status = Status.PENDING;
return Promise.all([
createCredentials.fromSecureString(this._sourceCredentials, masterPassword),
createCredentials.fromSecureString(this._archiveCredentials, masterPassword)
])
.then(([sourceCredentials, archiveCredentials] = []) => {
return credentialsToSource(sourceCredentials, archiveCredentials, /* initialise */ false)
.then(sourceInfo => {
const { workspace, sourceCredentials, archiveCredentials } = sourceInfo;
this._workspace = workspace;
this._sourceCredentials = sourceCredentials;
this._archiveCredentials = archiveCredentials;
this._status = Status.UNLOCKED;
this.type = sourceCredentials.type;
})
.catch(err => {
throw new VError(err, "Failed mapping credentials to a source");
});
})
.then(() => {
this.emit("sourceUnlocked", this.description);
})
.catch(err => {
this._status = Status.LOCKED;
throw new VError(err, `Failed unlocking source: ${this.id}`);
});
}
updateArchiveCredentials(masterPassword) {
if (this.status !== SourceStatus.UNLOCKED) {
return Promise.reject(
new VError(`Failed updating archive credentials: Source is not unlocked: ${this.id}`)
);
}
const credentials = createCredentials.fromPassword(masterPassword);
// First update the credentials stored here
this._archiveCredentials = credentials;
// Then update the credentials in the workspace
this.workspace.updatePrimaryCredentials(credentials);
// Finally, dehydrate the source to save changes in the manager
return (
this.dehydrateSource(sourceID)
// Save the workspace to push the new password to file
.then(() => this.workspace.save())
);
}
}
ArchiveSource.Status = Status;
ArchiveSource.rehydrate = rehydrate;
module.exports = ArchiveSource;
|
JavaScript
| 0 |
@@ -4893,32 +4893,58 @@
k(masterPassword
+, initialiseRemote = false
) %7B%0A if (
@@ -5556,11 +5556,8 @@
als,
- /*
ini
@@ -5567,16 +5567,13 @@
lise
- */ fals
+Remot
e)%0A
|
d9724eef0316f5488b2125e4232c2b6a11a1a31a
|
Allow instance deletion to be called independently of addSnapshot.
|
src/tracing/model/object_instance.js
|
src/tracing/model/object_instance.js
|
// Copyright (c) 2013 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.
'use strict';
/**
* @fileoverview Provides the ObjectSnapshot and ObjectHistory classes.
*/
base.require('base.range');
base.require('base.sorted_array_utils');
base.exportTo('tracing.model', function() {
/**
* A snapshot of an object instance, at a given moment in time.
*
* @constructor
*/
function ObjectSnapshot(objectInstance, ts, args) {
this.objectInstance = objectInstance;
this.ts = ts;
this.args = args;
this.selected = false;
}
ObjectSnapshot.prototype = {
__proto__: Object.prototype,
};
/**
* An object with a specific id, whose state has been snapshotted several
* times.
*
* @constructor
*/
function ObjectInstance(parent, id, category, name, creationTs) {
this.parent = parent;
this.id = id;
this.category = category;
this.name = name;
this.creationTs = creationTs;
this.deletionTs = Number.MAX_VALUE;
this.selected = false;
this.colorId = 0;
this.bounds = new base.Range();
this.snapshots = [];
}
ObjectInstance.prototype = {
__proto__: Object.prototype,
get typeName() {
return this.name;
},
/**
* Creates a snapshot for the current instance.
* Override to have custom snapshot subtypes.
*/
createSnapshot: function(ts, args) {
return new ObjectSnapshot(this, ts, args);
},
addSnapshot: function(ts, args) {
if (ts < this.creationTs)
throw new Error('Snapshots must be >= instance.creationTs');
if (this.deletionTs != Number.MAX_VALUE)
throw new Error('The instance has been deleted. ' +
'No more snapshots can be added.');
var lastSnapshot;
if (this.snapshots.length > 0) {
lastSnapshot = this.snapshots[this.snapshots.length - 1];
if (lastSnapshot.ts == ts)
throw new Error('Snapshots already exists at this time!');
if (ts < lastSnapshot.ts) {
throw new Error(
'Snapshots must be added in increasing timestamp order');
}
}
var snapshot = this.createSnapshot(ts, args);
this.snapshots.push(snapshot);
return snapshot;
},
wasDeleted: function(ts) {
var lastSnapshot;
if (this.snapshots.length > 0) {
lastSnapshot = this.snapshots[this.snapshots.length - 1];
if (lastSnapshot.ts > ts)
throw new Error(
'Instance cannot be deleted at ts=' +
ts + '. A snapshot exists that is older.');
}
this.deletionTs = ts;
},
getSnapshotAt: function(ts) {
if (ts < this.creationTs || ts > this.deletionTs)
throw new Error('ts must be within lifetime of this instance');
var snapshots = this.snapshots;
var i = base.findLowIndexInSortedIntervals(
snapshots,
function(snapshot) { return snapshot.ts; },
function(snapshot, i) {
if (i == snapshots.length - 1)
return snapshots[i].objectInstance.deletionTs;
return snapshots[i + 1].ts - snapshots[i].ts;
},
ts);
if (i < 0 || i >= this.snapshots.length)
return undefined;
return this.snapshots[i];
},
updateBounds: function() {
this.bounds.reset();
this.bounds.addValue(this.creationTs);
if (this.deletionTs != Number.MAX_VALUE)
this.bounds.addValue(this.deletionTs);
else if (this.snapshots.length > 0)
this.bounds.addValue(this.snapshots[this.snapshots.length - 1].ts);
},
shiftTimestampsForward: function(amount) {
this.creationTs += amount;
if (this.deletionTs != Number.MAX_VALUE)
this.deletionTs += amount;
this.snapshots.forEach(function(snapshot) {
snapshot.ts += amount;
});
}
};
ObjectInstance.categoryToConstructorMap = {};
ObjectInstance.register = function(name, constructor) {
if (ObjectInstance.categoryToConstructorMap[name])
throw new Error('Constructor already registerd for ' + name);
ObjectInstance.categoryToConstructorMap[name] = constructor;
};
ObjectInstance.unregister = function(name) {
ObjectInstance.categoryToConstructorMap[name] = undefined;
};
ObjectInstance.getConstructor = function(name) {
if (ObjectInstance.categoryToConstructorMap[name])
return ObjectInstance.categoryToConstructorMap[name];
return ObjectInstance;
};
return {
ObjectSnapshot: ObjectSnapshot,
ObjectInstance: ObjectInstance,
};
});
|
JavaScript
| 0.00025 |
@@ -1663,32 +1663,38 @@
Ts');%0A if (
+ts %3E=
this.deletionTs
@@ -1692,36 +1692,16 @@
letionTs
- != Number.MAX_VALUE
)%0A
@@ -1723,98 +1723,98 @@
or('
-The instance has been deleted. ' +%0A 'No more snapshots can be added
+Snapshots cannot be added after ' +%0A 'an objects deletion timestamp
.');
|
e622d7cfb075e8a3e567b8a5bdfb59f451e70493
|
Return 415 in case an image media type is not supported
|
routes/attachments.js
|
routes/attachments.js
|
"use strict";
var Page = require("../models/page");
var parse = require("url").parse;
var moveFiles = require("../lib/move-files");
var supportedMediaTypes = require("../config").supportedMediaTypes;
var fs = require("fs");
var path = require("path");
var loadPage = function (req, res, next) {
if (!req.headers.referer) {
return res.send(400);
}
var referer = parse(req.headers.referer);
Page.findOne({path: referer.path}, function (err, page) {
if (err) {
console.error(err);
return res.send(400);
}
req.page = page;
next();
});
};
module.exports = function (app) {
app.post("/attachments", loadPage, function (req, res) {
if(!req.files.attachments) { return res.send(400); }
var files = req.files.attachments[0] ? req.files.attachments : [req.files.attachments];
var unsupportedMedia = files.some(function (file) {
return supportedMediaTypes.media.indexOf(file.type) === -1;
});
if (unsupportedMedia) {
return res.send(415);
}
var page = req.page;
moveFiles(page, files, "attachments", function (err, attachments) {
if (err) {
console.error(err);
return res.send(400);
}
page.attachments = page.attachments.concat(attachments);
page.save(function (err) {
if (err) { return res.send(500); }
res.send({
attachments: attachments,
pageId: page._id
});
});
});
});
app.post("/images", loadPage, function (req, res) {
if(!req.files.images) { return res.send(400); }
var files = req.files.images[0] ? req.files.images : [req.files.images];
var unsupportedImageType = files.some(function (file) {
return supportedMediaTypes.images.indexOf(file.type) === -1;
});
var page = req.page;
moveFiles(page, files, "images", function (err, images) {
if (err) {
console.error(err);
return res.send(400);
}
page.images = page.images.concat(images);
page.save(function (err) {
if (err) {
console.error(err);
return res.send(500);
}
res.send({
images: images,
pageId: page._id
});
});
});
});
app.delete("/attachments", loadPage, function (req, res) {
var removedFile = null;
var page = req.page;
page.attachments = page.attachments.filter(function (attachment) {
if (req.body.file == attachment) {
removedFile = attachment;
return false;
}
return true;
});
if (removedFile) {
return page.save(function(err) {
if(err) {console.error(err); return 500; }
fs.unlink(path.join(__dirname, "..", "public", "attachment", page.id, removedFile), function(err) {
res.send(200);
});
});
}
res.send(404);
});
app.delete("/images", loadPage, function (req, res) {
var removedFile = null;
var page = req.page;
page.images = page.images.filter(function (image) {
if (req.body.file == image) {
removedFile = image;
return false;
}
console.log(true);
return true;
});
if (removedFile) {
return page.save(function(err) {
if(err) {console.error(err); return 500; }
fs.unlink(path.join(__dirname, "..", "public", "images", page.id, removedFile), function(err) {
res.send(200);
});
});
}
res.send(404);
});
};
|
JavaScript
| 0.000001 |
@@ -1983,16 +1983,96 @@
%7D);%0A%0A
+ if (unsupportedImageType) %7B%0A return res.send(415);%0A %7D%0A
%0A
|
d404a5d65837c8626f4afa294e5773cea0b4299d
|
Update StaggerConfig.js
|
src/tweens/typedefs/StaggerConfig.js
|
src/tweens/typedefs/StaggerConfig.js
|
/**
* @typedef {object} Phaser.Types.Tweens.StaggerConfig
* @since 3.19.0
*
* @property {any} targets - The object, or an array of objects, to run the tween on.
* @property {number} [delay=0] - The number of milliseconds to delay before the tween will start.
* @property {number} [duration=1000] - The duration of the tween in milliseconds.
* @property {(string|function)} [ease='Power0'] - The easing equation to use for the tween.
* @property {array} [easeParams] - Optional easing parameters.
* @property {number} [hold=0] - The number of milliseconds to hold the tween for before yoyo'ing.
* @property {number} [repeat=0] - The number of times each property tween repeats.
* @property {number} [repeatDelay=0] - The number of milliseconds to pause before a repeat.
* @property {boolean} [yoyo=false] - Should the tween complete, then reverse the values incrementally to get back to the starting tween values? The reverse tweening will also take `duration` milliseconds to complete.
* @property {boolean} [flipX=false] - Horizontally flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipX` property.
* @property {boolean} [flipY=false] - Vertically flip the target of the Tween when it completes (before it yoyos, if set to do so). Only works for targets that support the `flipY` property.
* @property {number|function|object|array} [offset=null] - Used when the Tween is part of a Timeline.
* @property {number|function|object|array} [completeDelay=0] - The time the tween will wait before the onComplete event is dispatched once it has completed, in ms.
* @property {number|function|object|array} [loop=0] - The number of times the tween will repeat. (A value of 1 means the tween will play twice, as it repeated once.) The first loop starts after every property tween has completed once.
* @property {number|function|object|array} [loopDelay=0] - The time the tween will pause before starting either a yoyo or returning to the start for a repeat.
* @property {boolean} [paused=false] - Does the tween start in a paused state (true) or playing (false)?
* @property {Object.<string,(number|string|Phaser.Types.Tweens.GetEndCallback|Phaser.Types.Tweens.TweenPropConfig)>} [props] - The properties to tween.
* @property {boolean} [useFrames=false] - Use frames or milliseconds?
* @property {any} [callbackScope] - Scope (this) for the callbacks. The default scope is the tween.
* @property {Phaser.Types.Tweens.TweenOnCompleteCallback} [onComplete] - A function to call when the tween completes.
* @property {array} [onCompleteParams] - Additional parameters to pass to `onComplete`.
* @property {any} [onCompleteScope] - Scope (this) for `onComplete`.
* @property {Phaser.Types.Tweens.TweenOnLoopCallback} [onLoop] - A function to call each time the tween loops.
* @property {array} [onLoopParams] - Additional parameters to pass to `onLoop`.
* @property {any} [onLoopScope] - Scope (this) for `onLoop`.
* @property {Phaser.Types.Tweens.TweenOnRepeatCallback} [onRepeat] - A function to call each time the tween repeats. Called once per property per target.
* @property {array} [onRepeatParams] - Additional parameters to pass to `onRepeat`.
* @property {any} [onRepeatScope] - Scope (this) for `onRepeat`.
* @property {Phaser.Types.Tweens.TweenOnStartCallback} [onStart] - A function to call when the tween starts playback, after any delays have expired.
* @property {array} [onStartParams] - Additional parameters to pass to `onStart`.
* @property {any} [onStartScope] - Scope (this) for `onStart`.
* @property {Phaser.Types.Tweens.TweenOnUpdateCallback} [onUpdate] - A function to call each time the tween steps. Called once per property per target.
* @property {array} [onUpdateParams] - Additional parameters to pass to `onUpdate`.
* @property {any} [onUpdateScope] - Scope (this) for `onUpdate`.
* @property {Phaser.Types.Tweens.TweenOnYoyoCallback} [onYoyo] - A function to call each time the tween yoyos. Called once per property per target.
* @property {array} [onYoyoParams] - Additional parameters to pass to `onYoyo`.
* @property {any} [onYoyoScope] - Scope (this) for `onYoyo`.
* @property {Phaser.Types.Tweens.TweenOnActiveCallback} [onActive] - A function to call when the tween becomes active within the Tween Manager.
* @property {array} [onActiveParams] - Additional parameters to pass to `onActive`.
* @property {any} [onActiveScope] - Scope (this) for `onActive`.
*
* @example
* {
* targets: null,
* delay: 0,
* duration: 1000,
* ease: 'Power0',
* easeParams: null,
* hold: 0,
* repeat: 0,
* repeatDelay: 0,
* yoyo: false,
* flipX: false,
* flipY: false
* };
*/
|
JavaScript
| 0 |
@@ -76,94 +76,8 @@
%0A *%0A
- * @property %7Bany%7D targets - The object, or an array of objects, to run the tween on.%0A
* @
|
237be8847a763cc8e7e2799afa8fa1dcf82456e7
|
make file helper a little more readable
|
test/helpers/file.js
|
test/helpers/file.js
|
var fs = require('fs');
module.exports.copy = function (source, target, callback) {
var finished = false;
var readStream = fs.createReadStream(source);
readStream.on("error", function(error) {
done(error);
});
var writeStream = fs.createWriteStream(target);
writeStream.on("error", function(error) {
done(error);
});
writeStream.on("close", function(ex) {
done();
});
readStream.pipe(writeStream);
function done(error) {
if (!finished) {
if (error) { console.log('unable to copy file'); }
finished = true;
callback();
}
}
};
module.exports.delete = function (path, callback) {
fs.unlink(path, function (error) {
if(error) { console.log('unable to delete file'); }
callback();
});
};
|
JavaScript
| 0.000001 |
@@ -515,32 +515,42 @@
if (error) %7B
+%0D%0A
console.log('una
@@ -565,25 +565,41 @@
opy file');
-%7D
+%0D%0A %7D%0D%0A
%0D%0A fini
@@ -756,16 +756,24 @@
rror) %7B
+%0D%0A
console.
@@ -802,17 +802,29 @@
file');
-%7D
+%0D%0A %7D%0D%0A
%0D%0A ca
|
b172bc4b845c6745f66076753b55c745c0978555
|
Fix quote and reply
|
src/ui/components/views/ChatInput.js
|
src/ui/components/views/ChatInput.js
|
/* @flow */
import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import ImageChooser from 'react-native-image-chooser';
import Colors from '../../Colors';
import Icon from './Icon';
import GrowingTextInput from './GrowingTextInput';
import TouchFeedback from './TouchFeedback';
import ChatSuggestionsContainer from '../containers/ChatSuggestionsContainer';
import ImageUploadContainer from '../containers/ImageUploadContainer';
import ImageUploadChat from './ImageUploadChat';
const {
StyleSheet,
View,
PixelRatio
} = ReactNative;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'stretch',
backgroundColor: Colors.white,
borderColor: Colors.underlay,
borderTopWidth: 1 / PixelRatio.get(),
elevation: 4
},
inputContainer: {
flex: 1,
paddingHorizontal: 16,
},
input: {
paddingVertical: 8,
margin: 0,
backgroundColor: 'transparent',
color: Colors.black,
},
iconContainer: {
alignItems: 'center',
justifyContent: 'center'
},
icon: {
color: Colors.fadedBlack,
margin: 17
}
});
type Props = {
room: string;
thread: string;
user: string;
sendMessage: Function;
}
type State = {
text: string;
query: string;
photo: ?{
uri: string;
size: number;
name: string;
height: number;
width: number;
};
}
export default class ChatInput extends Component<void, Props, State> {
static propTypes = {
room: PropTypes.string.isRequired,
thread: PropTypes.string.isRequired,
user: PropTypes.string.isRequired,
sendMessage: PropTypes.func.isRequired
};
state: State = {
text: '',
query: '',
photo: null,
};
shouldComponentUpdate(nextProps: Props, nextState: State): boolean {
return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState);
}
setQuotedText: Function = (text) => {
this._computeAndSetText({
replyTo: text.from,
quotedText: text.text
});
};
setReplyTo: Function = (text) => {
this._computeAndSetText({
replyTo: text.from
});
};
_input: Object;
_sendMessage: Function = () => {
this.props.sendMessage(null, this.state.text);
this.setState({
text: ''
});
};
_handleUploadImage: Function = async () => {
try {
this.setState({
photo: null
});
const photo = await ImageChooser.pickImage();
this.setState({
photo
});
} catch (e) {
// Do nothing
}
};
_handleUploadFinish: Function = ({ id, result }) => {
const {
photo,
} = this.state;
if (!result.url || !photo) {
return;
}
const { height, width, name } = photo;
const aspectRatio = height / width;
this.props.sendMessage(id, `${photo.name}: ${result.url}`, {
photo: {
height,
width,
title: name,
url: result.url,
thumbnail_height: Math.min(480, width) * aspectRatio,
thumbnail_width: Math.min(480, width),
thumbnail_url: result.thumbnail
}
});
setTimeout(() => this._handleUploadClose(), 500);
};
_handleUploadClose: Function = () => {
this.setState({
photo: null,
});
};
_handleSuggestionSelect: Function = nick => {
this.setState({
text: '@' + nick + ' ',
query: ''
});
};
_handleChangeText: Function = text => {
const query = /^@[a-z0-9]*$/.test(text) ? text : '';
this.setState({
text,
query
});
};
_computeAndSetText: Function = opts => {
const quotedText = opts.quotedText ? opts.quotedText.replace(/\n/g, ' ') : null;
let newValue = this.state.text;
if (quotedText) {
if (newValue) {
newValue += '\n\n';
}
newValue += '> ' + (opts.replyTo ? '@' + opts.replyTo + ' - ' : '') + quotedText + '\n\n';
} else if (opts.replyTo) {
if (newValue) {
newValue += ' ';
}
newValue += `@${opts.replyTo} `;
}
this.setState({
text: newValue
}, () => this._input.focusKeyboard());
};
render() {
return (
<View {...this.props}>
<ChatSuggestionsContainer
room={this.props.room}
thread={this.props.thread}
user={this.props.user}
text={this.state.query}
style={styles.suggestions}
onSelect={this._handleSuggestionSelect}
/>
<View style={styles.container}>
<GrowingTextInput
ref={c => (this._input = c)}
value={this.state.text}
onChangeText={this._handleChangeText}
underlineColorAndroid='transparent'
placeholder='Write a message…'
autoCapitalize='sentences'
numberOfLines={7}
style={styles.inputContainer}
inputStyle={styles.input}
/>
<TouchFeedback
borderless
onPress={this.state.text ? this._sendMessage : this._handleUploadImage}
>
<View style={styles.iconContainer}>
<Icon
name={this.state.text ? 'send' : 'image'}
style={styles.icon}
size={24}
/>
</View>
</TouchFeedback>
</View>
{this.state.photo ?
<ImageUploadContainer
component={ImageUploadChat}
photo={this.state.photo}
onUploadClose={this._handleUploadClose}
onUploadFinish={this._handleUploadFinish}
/> : null
}
</View>
);
}
}
|
JavaScript
| 0 |
@@ -1924,20 +1924,23 @@
o: text.
-from
+creator
,%0A%09%09%09quo
@@ -1953,20 +1953,20 @@
t: text.
-text
+body
%0A%09%09%7D);%0A%09
@@ -2050,20 +2050,23 @@
o: text.
-from
+creator
%0A%09%09%7D);%0A%09
|
068850e087f11dedba23ce978bb7c90670946a0b
|
tag.name is lowercase, BREAKING CHANGE
|
test/multi_stream.js
|
test/multi_stream.js
|
var trumpet = require('../');
var test = require('tape');
var fs = require('fs');
var through = require('through');
var concat = require('concat-stream');
test('multiple read streams', function (t) {
t.plan(7);
var tr = trumpet();
tr.pipe(through(null, function () { output.end() }));
var output = through();
output.pipe(concat(function (src) {
t.equal(src.toString('utf8'), 'tacosyburritos');
}));
var html = [
'tacos',
'y',
'burritos'
];
tr.selectAll('.b span', function (span) {
t.equal(span.name, 'SPAN');
var rs = span.createReadStream();
rs.pipe(output, { end: false });
rs.pipe(concat(function (src) {
t.equal(src.toString('utf8'), html.shift());
}));
});
fs.createReadStream(__dirname + '/multi_stream.html').pipe(tr);
});
|
JavaScript
| 0.999975 |
@@ -586,12 +586,12 @@
e, '
-SPAN
+span
');%0A
|
08d4abd8ac0f11098ac3d463b58f06200d374b2c
|
Add back browser refresh at the top of prefill test case
|
test/e2e/specs/recordedit/data-independent/add/00-recordedit.add.spec.js
|
test/e2e/specs/recordedit/data-independent/add/00-recordedit.add.spec.js
|
var chaisePage = require('../../../../utils/chaise.page.js'), IGNORE = "tag:isrd.isi.edu,2016:ignore", HIDDEN = "tag:misd.isi.edu,2015:hidden";
var recordEditHelpers = require('../../helpers.js'), chance = require('chance').Chance();
describe('Record Add', function() {
var params, testConfiguration = browser.params.configuration.tests, testParams = testConfiguration.params;
for (var i=0; i< testParams.tables.length; i++) {
(function(tableParams, index) {
var table;
describe("======================================================================= \n "
+ tableParams.records + " record(s) for table " + tableParams.table_name + ",", function() {
beforeAll(function () {
browser.ignoreSynchronization=true;
browser.get(browser.params.url + ":" + tableParams.table_name);
table = browser.params.defaultSchema.content.tables[tableParams.table_name];
browser.sleep(3000);
});
describe("Presentation and validation,", function() {
var params = recordEditHelpers.testPresentationAndBasicValidation(tableParams);
});
describe("delete record, ", function() {
if (tableParams.records > 1) {
it(tableParams.records + " buttons should be visible and enabled", function() {
chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
expect(buttons.length).toBe(tableParams.records + 1);
buttons.forEach(function(btn) {
expect(btn.isDisplayed()).toBe(true);
expect(btn.isEnabled()).toBe(true);
});
});
});
var randomNo = chaisePage.recordEditPage.getRandomInt(0, tableParams.records - 1);
it("click any delete button", function() {
chaisePage.recordEditPage.getDeleteRowButton(randomNo).then(function(button) {
chaisePage.clickButton(button);
browser.sleep(50);
chaisePage.recordEditPage.getDeleteModalButton().then(function(modalBtn) {
chaisePage.clickButton(modalBtn);
browser.sleep(50);
chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
expect(buttons.length).toBe(tableParams.records);
});
});
});
});
} else {
it("zero delete buttons should be visible", function() {
chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
expect(buttons.length).toBe(1);
buttons.forEach(function(btn) {
expect(btn.isDisplayed()).toBe(false);
});
});
});
}
});
describe("Submit " + tableParams.records + " records", function() {
beforeAll(function() {
// Submit the form
chaisePage.recordEditPage.submitForm();
});
var hasErrors = false;
xit("should have no errors, and should be redirected", function(done) {
chaisePage.recordEditPage.getAlertError().then(function(err) {
if (err) {
expect("Page has errors").toBe("No errors");
hasErrors = true;
} else {
expect(true).toBe(true);
}
});
done();
}).pend("Postpone test until foreign key UI is updated for the new reference apis");
xit("should be redirected to record page", function() {
if (!hasErrors) {
browser.sleep(3000);
browser.driver.getCurrentUrl().then(function(url) {
console.log(url);
if (tableParams.records > 1) {
expect(url.startsWith(process.env.CHAISE_BASE_URL + "/recordset/")).toBe(true);
} else {
expect(url.startsWith(process.env.CHAISE_BASE_URL + "/record/")).toBe(true);
}
});
}
}).pend("Postpone test until foreign key UI is updated for the new reference apis");
});
});
})(testParams.tables[i], i);
}
it('should load custom CSS and document title defined in chaise-config.js', function() {
var chaiseConfig = browser.executeScript('return chaiseConfig');
if (chaiseConfig.customCSS) {
expect($("link[href='" + chaiseConfig.customCSS + "']").length).toBeTruthy();
}
if (chaiseConfig.headTitle) {
browser.getTitle().then(function(title) {
expect(title).toEqual(chaiseConfig.headTitle);
});
}
});
describe('When url has a prefill query string param set, ', function() {
var testCookie = {};
beforeAll(function() {
// Write a dummy cookie for creating a record in Accommodation table
testCookie = {
constraintName: 'product:accommodation_category_fkey1', // A FK that Accommodation table has with Category table
rowname: chance.sentence(),
keys: {id: 1}
};
browser.manage().addCookie('test', JSON.stringify(testCookie));
// Reload the page with prefill query param in url
browser.get(browser.params.url + ":" + testParams.tables[0].table_name + '?prefill=test');
browser.sleep(3000);
});
it('should pre-fill fields from the prefill cookie', function() {
browser.manage().getCookie('test').then(function(cookie) {
if (cookie) {
var input = element.all(by.css('.popup-select-value')).first();
expect(input.getText()).toBe(testCookie.rowname);
} else {
expect('Cookie did not load').toEqual('but cookie should have loaded');
}
});
});
afterAll(function() {
browser.manage().deleteCookie('test');
});
});
});
|
JavaScript
| 0 |
@@ -4459,32 +4459,183 @@
ll(function() %7B%0A
+ // Refresh the page%0A browser.get(browser.params.url + %22:%22 + testParams.tables%5B0%5D.table_name);%0A browser.sleep(3000);%0A%0A
// W
|
8b42ab14890c1bcb8da5555e9ffb9281e37462c2
|
Update tests
|
test/notification.js
|
test/notification.js
|
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'mocha-jsdom';
import expect from 'expect';
import Notification from '../src/notification';
const MOCK = {
message: 'Test',
action: 'Dismiss',
onClick: function handleClick() {
return;
},
style: {
bar: {
background: '#bababa'
},
action: {
color: '#000'
},
active: {
left: '2rem'
}
}
};
describe('Notification', () => {
jsdom();
it('should be a valid element', done => {
const component = (
<Notification
message={MOCK.message}
action={MOCK.action}
onClick={MOCK.onClick}
/>
);
if (TestUtils.isElement(component)) done();
});
it('should render correct message and action text', done => {
const tree = TestUtils.renderIntoDocument(
<Notification
message={MOCK.message}
action={MOCK.action}
onClick={MOCK.onClick}
/>
);
let { message, action } = tree.refs;
expect(message.innerHTML).toBe(MOCK.message);
expect(action.innerHTML).toBe(MOCK.action);
done();
});
it('should handle click events', done => {
const tree = TestUtils.renderIntoDocument(
<Notification
message={MOCK.message}
action={MOCK.action}
onClick={MOCK.onClick}
/>
);
let wrapper = TestUtils.findRenderedDOMComponentWithClass(tree, 'notification-bar-wrapper');
TestUtils.Simulate.click(wrapper);
done();
});
});
|
JavaScript
| 0.000001 |
@@ -137,16 +137,18 @@
;%0Aimport
+ %7B
Notific
@@ -152,16 +152,37 @@
fication
+, NotificationStack %7D
from '.
@@ -187,28 +187,21 @@
'../src/
-notification
+index
';%0A%0Acons
@@ -1520,12 +1520,291 @@
;%0A %7D);%0A%7D);%0A
+%0Adescribe('NotificationStack', () =%3E %7B%0A jsdom();%0A%0A it('should be a valid element', done =%3E %7B%0A const component = (%0A %3CNotificationStack%0A notifications=%7B%5B%5D%7D%0A onDismiss=%7BMOCK.onClick%7D%0A /%3E%0A );%0A%0A if (TestUtils.isElement(component)) done();%0A %7D);%0A%7D);%0A
|
2f543ef202f8f14861696e6af37193d687e8f3e5
|
test push
|
app/js/painter.js
|
app/js/painter.js
|
define([],function() {
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
var painter = {
drawBG: function() {
ctx.save();
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
},
drawMatrices: function(ctrl) {
ctx.save();
for(var i = 0; i < ctrl.matrices.length; i++) {
ctrl.matrices[i].draw(ctx);
}
ctx.restore();
},
drawPlayerData: function(ctrl) {
ctx.fillText(ctrl.players[0].name, 250, 350);
ctrl.players[0].matrix.draw(ctx);
ctx.fillText(ctrl.players[0].matrix.trace(), 250, 550);
ctx.fillText(ctrl.players[0].score, 250, 600);
ctx.fillText(ctrl.players[1].name, 500, 350);
ctrl.players[1].matrix.draw(ctx);
ctx.fillText(ctrl.players[1].matrix.trace(), 500, 550);
ctx.fillText(ctrl.players[1].score, 500, 600);
},
drawWaiting: function() {
ctx.save();
ctx.font = "40px Helvetica";
ctx.fillText('Looking for opponent...', canvas.width/2, canvas.height/2);
ctx.restore();
},
drawTurn: function(id) {
ctx.save();
if(id == 0) {
ctx.fillText('Your Turn', 380, 310);
} else {
ctx.fillText('Opponent\'s Turn', 380, 310);
}
ctx.restore();
},
drawDisconnect: function() {
ctx.save();
ctx.font = "40px Helvetica";
ctx.fillText('Your opponent has left the game.', canvas.width/2, canvas.height/2);
ctx.restore();
},
defaultStyles: function() {
ctx.fillStyle = "#000000";
ctx.font = "24px Helvetica";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
}
};
return painter;
});
|
JavaScript
| 0.000001 |
@@ -4,11 +4,8 @@
ine(
-%5B%5D,
func
|
3e7027f16a8c5fcaec69b77c1cd092ddbcb6dbbd
|
fix update account name in UI after name changed
|
src/frontend/electron_vue/src/store/modules/wallet.js
|
src/frontend/electron_vue/src/store/modules/wallet.js
|
const wallet = {
namespaced: true,
state: {
accounts: [],
activeAccount: null,
balance: null,
mutations: null,
receiveAddress: null,
walletBalance: null,
walletPassword: null
},
mutations: {
SET_ACCOUNTS(state, accounts) {
state.accounts = accounts;
},
SET_ACTIVE_ACCOUNT(state, accountUUID) {
state.activeAccount = accountUUID;
},
SET_BALANCE(state, balance) {
state.balance = balance;
},
SET_MUTATIONS(state, mutations) {
state.mutations = mutations;
},
SET_RECEIVE_ADDRESS(state, receiveAddress) {
state.receiveAddress = receiveAddress;
},
SET_WALLET_BALANCE(state, walletBalance) {
state.walletBalance = walletBalance;
},
SET_WALLET_PASSWORD(state, password) {
state.walletPassword = password;
}
},
actions: {
SET_ACCOUNT_NAME({ state, commit }, payload) {
let accounts = [...state.accounts];
let account = accounts.find(x => x.UUID === payload.accountUUID);
account.label = payload.newAccountName;
commit({ type: "SET_ACCOUNTS", accounts: accounts });
},
SET_ACCOUNTS({ commit }, accounts) {
commit("SET_ACCOUNTS", accounts);
},
SET_ACTIVE_ACCOUNT({ commit }, accountUUID) {
// clear mutations and receive address
commit("SET_MUTATIONS", { mutations: null });
commit("SET_RECEIVE_ADDRESS", { receiveAddress: "" });
commit("SET_ACTIVE_ACCOUNT", accountUUID);
},
SET_BALANCE({ commit }, new_balance) {
commit("SET_BALANCE", new_balance);
},
SET_MUTATIONS({ commit }, mutations) {
commit("SET_MUTATIONS", mutations);
},
SET_RECEIVE_ADDRESS({ commit }, receiveAddress) {
commit("SET_RECEIVE_ADDRESS", receiveAddress);
},
SET_WALLET_BALANCE({ commit }, walletBalance) {
commit("SET_WALLET_BALANCE", walletBalance);
},
SET_WALLET_PASSWORD({ commit }, password) {
commit("SET_WALLET_PASSWORD", password);
}
},
getters: {
totalBalance: state => {
let balance = state.walletBalance;
if (balance === undefined || balance === null) return null;
return (
(balance.availableIncludingLocked +
balance.unconfirmedIncludingLocked +
balance.immatureIncludingLocked) /
100000000
);
},
accounts: state => {
return state.accounts
.filter(x => x.state === "Normal")
.sort((a, b) => {
const labelA = a.label.toUpperCase();
const labelB = b.label.toUpperCase();
let comparison = 0;
if (labelA > labelB) {
comparison = 1;
} else if (labelA < labelB) {
comparison = -1;
}
return comparison;
});
},
account: state => {
return state.accounts.find(x => x.UUID === state.activeAccount);
},
miningAccount: state => {
return state.accounts.find(
x => x.type === "Mining" && x.state === "Normal"
); // this will retrieve the first account of type Mining
}
}
};
export default wallet;
|
JavaScript
| 0 |
@@ -1073,16 +1073,8 @@
mit(
-%7B type:
%22SET
@@ -1097,20 +1097,8 @@
unts
-: accounts %7D
);%0A
|
29e745b56b2d41510f5075be37ac3e13553dc410
|
Fix karma coverage
|
app/karma.conf.js
|
app/karma.conf.js
|
'use strict';
// Karma configuration
// Generated on Fri Apr 21 2017 19:34:22 GMT-0400 (EDT)
module.exports = function(config) {
var sourcePreprocessors = 'coverage';
function isDebug(argument) {
return argument === '--debug';
}
if (process.argv.some(isDebug)) {
sourcePreprocessors = [];
}
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-ios9-uiwebview-patch/angular-ios9-uiwebview-patch.js',
'node_modules/marked/lib/marked.js',
'node_modules/angular-marked/dist/angular-marked.js',
'node_modules/angular-resource/angular-resource.js',
'node_modules/angular-sanitize/angular-sanitize.js',
'node_modules/angularjs-scroll-glue/src/scrollglue.js',
'node_modules/angular-ui-router/release/angular-ui-router.js',
'node_modules/angular-websocket/dist/angular-websocket.js',
'node_modules/angular-mocks/angular-mocks.js',
'vendor/jsrsasign-all-min.js',
'public/js/app.js',
'public/js/controllers/default.js',
'public/js/controllers/play.js',
'public/js/controllers/site.js',
'public/js/directives/profileCore.js',
'public/js/services/auth.js',
'public/js/services/commandHistory.js',
'public/js/services/go_ga.js',
'public/js/services/map.js',
'public/js/services/playerSession.js',
'public/js/services/playerSocket.js',
'public/js/services/user.js',
'public/templates/*.html',
'test/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'public/scripts/**/*.js': sourcePreprocessors,
'public/templates/*.html': 'ng-html2js'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec', 'coverage'],
// configure the coverage reporter
coverageReporter: {
dir : 'reports/coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'json', subdir: '.' }
]
},
ngHtml2JsPreprocessor: {
stripPrefix: 'public/templates/',
moduleName: 'templates'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
});
};
|
JavaScript
| 0.000026 |
@@ -165,16 +165,17 @@
erage';%0A
+%0A
functi
@@ -2038,14 +2038,9 @@
lic/
-script
+j
s/**
@@ -2388,137 +2388,69 @@
-dir : 'reports/coverage',%0A reporters: %5B%0A %7B type: 'lcov', subdir: '.' %7D,%0A %7B type: 'json', subdir: '.' %7D%0A %5D
+type: 'lcov',%0A dir : 'reports',%0A subdir: 'coverage'
%0A
|
8fac55cafc520feba9d0e6d2a7699a53544593f3
|
revert accidental boolean flip, this test doesn't make much sense any more
|
share/www/script/test/update_documents.js
|
share/www/script/test/update_documents.js
|
// 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.
couchTests.update_documents = function(debug) {
var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
db.deleteDb();
db.createDb();
if (debug) debugger;
var designDoc = {
_id:"_design/update",
language: "javascript",
updates: {
"hello" : stringFun(function(doc, req) {
if (!doc) {
if (req.docId) {
return [{
_id : req.docId
}, "New World"]
}
return [null, "Empty World"];
}
doc.world = "hello";
doc.edited_by = req.userCtx;
return [doc, "hello doc"];
}),
"in-place" : stringFun(function(doc, req) {
var field = req.query.field;
var value = req.query.value;
var message = "set "+field+" to "+value;
doc[field] = value;
return [doc, message];
}),
"bump-counter" : stringFun(function(doc, req) {
if (!doc.counter) doc.counter = 0;
doc.counter += 1;
var message = "<h1>bumped it!</h1>";
return [doc, message];
}),
"error" : stringFun(function(doc, req) {
superFail.badCrash;
}),
"xml" : stringFun(function(doc, req) {
var xml = new XML('<xml></xml>');
xml.title = doc.title;
var posted_xml = new XML(req.body);
doc.via_xml = posted_xml.foo.toString();
var resp = {
"headers" : {
"Content-Type" : "application/xml"
},
"body" : xml
};
return [doc, resp];
})
}
};
T(db.save(designDoc).ok);
var doc = {"word":"plankton", "name":"Rusty"}
var resp = db.save(doc);
T(resp.ok);
var docid = resp.id;
// update error
var xhr = CouchDB.request("POST", "/test_suite_db/_design/update/_update/");
T(xhr.status == 404, 'Should be missing');
T(JSON.parse(xhr.responseText).reason == "Invalid path.");
// hello update world
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/hello/"+docid);
T(xhr.status == 201);
T(xhr.responseText == "hello doc");
T(/charset=utf-8/.test(xhr.getResponseHeader("Content-Type")))
doc = db.open(docid);
T(doc.world == "hello");
// Fix for COUCHDB-379
T(equals(xhr.getResponseHeader("Server").substr(0,7), "CouchDB"));
// hello update world (no docid)
xhr = CouchDB.request("POST", "/test_suite_db/_design/update/_update/hello");
T(xhr.status == 200);
T(xhr.responseText == "Empty World");
// no GET allowed
xhr = CouchDB.request("GET", "/test_suite_db/_design/update/_update/hello");
T(xhr.status == 405);
T(JSON.parse(xhr.responseText).error == "method_not_allowed");
// // hello update world (non-existing docid)
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/hello/nonExistingDoc");
T(xhr.status == 201);
T(xhr.responseText == "New World");
// in place update
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/in-place/"+docid+'?field=title&value=test');
T(xhr.status == 201);
T(xhr.responseText == "set title to test");
doc = db.open(docid);
T(doc.title == "test");
// bump counter
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/bump-counter/"+docid, {
headers : {"X-Couch-Full-Commit":"false"}
});
T(xhr.status == 201);
T(xhr.responseText == "<h1>bumped it!</h1>");
doc = db.open(docid);
T(doc.counter == 1);
// _update honors full commit if you need it to
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/bump-counter/"+docid, {
headers : {"X-Couch-Full-Commit":"false"}
});
doc = db.open(docid);
T(doc.counter == 2);
// parse xml
xhr = CouchDB.request("PUT", "/test_suite_db/_design/update/_update/xml/"+docid, {
headers : {"X-Couch-Full-Commit":"false"},
"body" : '<xml><foo>bar</foo></xml>'
});
T(xhr.status == 201);
T(xhr.responseText == "<xml>\n <title>test</title>\n</xml>");
doc = db.open(docid);
T(doc.via_xml == "bar");
};
|
JavaScript
| 0.00003 |
@@ -4158,36 +4158,35 @@
h-Full-Commit%22:%22
-fals
+tru
e%22%7D%0A %7D);%0A %0A d
|
3f7cb80f4eb3054e4d3e8fe92e4e8a3d0b48de57
|
Add sensor stats schema
|
app/lib/models.js
|
app/lib/models.js
|
var mongoose = require( 'mongoose' );
var Schema = mongoose.Schema;
var SensorReadingSchema = Schema( {
date: Date,
temp_c: Number,
temp_f: Number,
humidity: Number,
pressure: Number,
luminosity: Number
} );
SensorReadingSchema.statics = {
add: function ( sensorReadingData, cb ) {
// Override the date here in case time from Raspberry Pi is off
sensorReadingData.data = new Date();
this.create( sensorReadingData, function ( err, newSensorReading ) {
if ( err ) {
return cb( err );
}
return cb( null, newSensorReading );
} );
},
calcStatsForDateRange: function ( startDate, endDate, cb ) {
var matchOptions = {
date: {
$gte: startDate,
$lte: endDate
}
};
var groupOptions = {
_id: null,
avg_temp_c: {
$avg: "$temp_c"
},
min_temp_c: {
$min: "$temp_c"
},
max_temp_c: {
$max: "$temp_c"
},
avg_temp_f: {
$avg: "$temp_f"
},
min_temp_f: {
$min: "$temp_f"
},
max_temp_f: {
$max: "$temp_f"
},
avg_humidity: {
$avg: "$humidity"
},
min_humidity: {
$min: "$humidity"
},
max_humidity: {
$max: "$humidity"
},
avg_pressure: {
$avg: "$pressure"
},
min_pressure: {
$min: "$pressure"
},
max_pressure: {
$max: "$pressure"
},
avg_luminosity: {
$avg: "$luminosity"
},
min_luminosity: {
$min: "$luminosity"
},
max_luminosity: {
$max: "$luminosity"
}
};
var q = this.aggregate()
.match( matchOptions )
.group( groupOptions );
q.exec( cb );
}
};
exports.SensorReading = mongoose.model( 'SensorReading', SensorReadingSchema );
var SystemReadingSchema = Schema( {
date: Date,
cpu_temp_c: Number,
cpu_temp_f: Number
} );
SystemReadingSchema.statics = {
add: function ( systemReadingData, cb ) {
// Override the date here in case time from Raspberry Pi is off
systemReadingData.data = new Date();
this.create( systemReadingData, function ( err, newSystemReading ) {
if ( err ) {
return cb( err );
}
return cb( null, newSystemReading );
} );
}
};
exports.SystemReading = mongoose.model( 'SystemReading', SystemReadingSchema );
|
JavaScript
| 0.000001 |
@@ -31,17 +31,16 @@
ose' );%0A
-%0A
var Sche
@@ -59,24 +59,655 @@
e.Schema;%0A%0A%0A
+// Sensor Stats%0Avar SensorStatsSchema = Schema( %7B%0A date: Date,%0A type: String,%0A avg_temp_c: Number,%0A min_temp_c: Number,%0A max_temp_c: Number,%0A avg_temp_f: Number,%0A min_temp_f: Number,%0A max_temp_f: Number,%0A avg_humidity: Number,%0A min_humidity: Number,%0A max_humidity: Number,%0A avg_pressure: Number,%0A min_pressure: Number,%0A max_pressure: Number,%0A avg_luminosity: Number,%0A min_luminosity: Number,%0A max_luminosity: Number%0A%7D );%0A%0ASensorStatsSchema.index( %7B date: 1, type: 1 %7D, %7B unique: true %7D );%0A%0Avar SensorStats = mongoose.model( 'SensorStats', SensorStatsSchema );%0A%0A%0A// Sensor Reading%0A
var SensorRe
@@ -1315,26 +1315,15 @@
n (
-startDate, endDate
+options
, cb
@@ -1398,16 +1398,24 @@
$gte:
+options.
startDat
@@ -1439,16 +1439,24 @@
$lte:
+options.
endDate%0A
@@ -2698,16 +2698,8 @@
- var q =
thi
@@ -2712,24 +2712,16 @@
egate()%0A
-
@@ -2759,24 +2759,16 @@
-
-
.group(
@@ -2781,18 +2781,16 @@
ptions )
-;%0A
%0A
@@ -2794,40 +2794,561 @@
-q
+
.exec(
-cb );%0A %7D%0A%7D;%0A%0Aexports.
+function ( err, data ) %7B%0A if ( err ) %7B%0A return cb( err );%0A %7D%0A%0A data = data%5B 0 %5D;%0A delete data._id;%0A data.date = options.date;%0A data.type = options.type;%0A%0A SensorStats.create( data, function ( err, newSensorStat ) %7B%0A if ( err ) %7B%0A return cb( err );%0A %7D%0A return cb( null, newSensorStat );%0A %7D );%0A %7D );%0A %7D%0A%7D;%0A%0Avar
Sens
@@ -3417,16 +3417,34 @@
ma );%0A%0A%0A
+// System Reading%0A
var Syst
@@ -3961,16 +3961,12 @@
%7D;%0A%0A
-exports.
+var
Syst
@@ -4017,24 +4017,139 @@
SystemReadingSchema );%0A
+%0A%0Aexports.SensorStats = SensorStats;%0Aexports.SystemReading = SystemReading;%0Aexports.SensorReading = SensorReading;%0A
|
8e422e61f9e1aeb91d5d0a4c7db368f390af2953
|
remove unneccessary stopPropagation
|
assets/js/ui.js
|
assets/js/ui.js
|
(function (window, Cryptoloji, $, undefined) {
/*
methods prefixed with _ are "private"
to see exposed method goto bottom :)
*/
function _createKeyElement (key) {
return '<p class="key" key="' + key + '">' + Cryptoloji.twemoji(key) + '</p>'
}
//
// Encrypt / key select
//
function _keySelect(key) {
Cryptoloji.use_key(key)
console.debug('Chosen key', key)
$(".share_key_emoji-item").html(Cryptoloji.twemoji(key))
}
function _encryptionKeySelect(event) {
$('.encryption .key').removeClass('selected')
event.stopPropagation()
var $self = $(event.target).closest('.key')
var key = $self.attr('key')
$self.addClass('selected')
_keySelect(key)
encryptText()
}
function _decryptionKeySelect(event) {
$('.decryption .key').removeClass('selected')
event.stopPropagation()
var $self = $(event.target).closest('.key')
var key = $self.attr('key')
$self.addClass('selected')
_keySelect(key)
// decryptText()
}
//////////////////////////////////////////////////////////////////////////////
//
// public methods
//
function encryptText() {
if (Cryptoloji.Encrypter.key) {
var text = $('.encryption .main_content_top_input').val()
if (text !== '' && !/^\s+$/.test(text)) {
console.debug('Chosen text:', text)
text = Cryptoloji.encrypt(text)
console.debug('Encrypted text:', text)
text = Cryptoloji.twemoji(text)
$('.encryption .main_content_bottom_input').html(text)
$('.share_message_item').html(text)
Cryptoloji.stateman.emit('encrypt:show-share')
}
}
}
function encryptionInputCounter(textMaxSize) {
$('#encryption_input_count').text(textMaxSize)
$('#encryption_input').on('input propertychange', function (event) {
var textSize = $('#encryption_input').val().length
$('#encryption_input_count').text(textMaxSize-textSize)
})
}
function fillEncryptionKeyslider(emojiList) {
var text = ''
_.each(emojiList, function(elem) {
text += _createKeyElement(elem)
})
$('.keyslider_content').append(text)
$('#encryption_keyslider').on('click', '.key', _encryptionKeySelect)
}
function fillDecryptionKeyslider(emojiList) {
var text = ''
_.each(emojiList, function(elem) {
text += _createKeyElement(elem)
})
$('#decryption_key_modal_open').before(text)
$('#decryption_keyslider').on('click', '.key', _decryptionKeySelect)
}
function fillKeymodal (emojiList) {
var text = ''
_.times(20, function () {
_.each(emojiList, function(elem) {
text += _createKeyElement(elem)
})
})
$(".main_key_modal_emoji_container").append(text)
}
//////////////////////////////////////////////////////////////////////////////
Cryptoloji.UI = {
encryptText: encryptText,
encryptionInputCounter: encryptionInputCounter,
fillEncryptionKeyslider: fillEncryptionKeyslider,
fillDecryptionKeyslider: fillDecryptionKeyslider,
fillKeymodal: fillKeymodal,
}
})(window, window.Cryptoloji, jQuery);
|
JavaScript
| 0.999992 |
@@ -548,36 +548,8 @@
d')%0A
- event.stopPropagation()%0A
@@ -792,36 +792,8 @@
d')%0A
- event.stopPropagation()%0A
|
e438b7cd353c0e6230393368871f7a90f0069ddd
|
check to see if field is non-null
|
ast/function.js
|
ast/function.js
|
'use strict';
/* @jsig */
var assert = require('assert');
var uuid = require('uuid');
var LiteralTypeNode = require('./literal.js');
var LocationLiteralNode = require('./location-literal.js');
var JsigASTReplacer = require('../type-checker/lib/jsig-ast-replacer.js');
module.exports = FunctionNode;
function FunctionNode(opts) {
assert(!(opts && opts.label), 'cannot have label on function');
assert(!(opts && opts.optional), 'cannot have optional on function');
this.type = 'function';
this.args = opts.args || [];
this.result = opts.result;
this.thisArg = opts.thisArg || null;
// Brand is used if this function is a constructor
// This will brand the object instance allocated with `new`
this.brand = opts.brand || 'Object';
// specialKind is used to store singleton information
// For example the assert function has special type narrow
// semantics so its FunctionNode is the "assert" specialKind
this.specialKind = opts.specialKind || null;
this.inferred = (opts && 'inferred' in opts) ?
opts.inferred : false;
this._raw = null;
if (opts.generics && typeof opts.generics[0] === 'string') {
/*jsig ignore next: narrowing by array member not implemented*/
this.generics = this._findGenerics(opts.generics);
} else {
this.generics = [];
}
}
FunctionNode.prototype.computeUniqueGenericNames =
function computeUniqueGenericNames() {
var uniqueGenerics = [];
for (var i = 0; i < this.generics.length; i++) {
if (uniqueGenerics.indexOf(this.generics[i].name) === -1) {
uniqueGenerics.push(this.generics[i].name);
}
}
return uniqueGenerics;
};
FunctionNode.prototype._findGenerics =
function _findGenerics(generics) {
var replacer = new GenericReplacer(this, generics);
var astReplacer = new JsigASTReplacer(replacer, true, true);
astReplacer.inlineReferences(this, this, []);
// console.log('seenGenerics?', replacer.seenGenerics);
return replacer.seenGenerics;
};
function GenericReplacer(node, generics) {
this.node = node;
this.knownGenerics = generics;
this.genericUUIDs = Object.create(null);
for (var i = 0; i < this.knownGenerics.length; i++) {
this.genericUUIDs[this.knownGenerics[i]] = uuid();
}
this.seenGenerics = [];
}
GenericReplacer.prototype.replace = function replace(ast, raw, stack) {
if (ast.type === 'typeLiteral') {
return this.replaceTypeLiteral(ast, stack);
} else if (ast.type === 'genericLiteral') {
// TODO: mark the generics in the genericLiteral itself ?
return ast;
} else {
assert(false, 'unexpected other type: ' + ast.type);
}
};
GenericReplacer.prototype.replaceTypeLiteral =
function replaceTypeLiteral(ast, stack) {
if (this.knownGenerics.indexOf(ast.name) === -1) {
return ast;
}
// if this has already been marked as generic
var identifierUUID;
if (ast.isGeneric) {
identifierUUID = ast.genericIdentifierUUID;
this.seenGenerics.push(
new LocationLiteralNode(ast.name, stack.slice(), identifierUUID)
);
return ast;
}
identifierUUID = this.genericUUIDs[ast.name];
this.seenGenerics.push(
new LocationLiteralNode(ast.name, stack.slice(), identifierUUID)
);
var copyAst = new LiteralTypeNode(ast.name, ast.builtin, {
line: ast.line,
loc: ast.loc,
concreteValue: ast.concreteValue
});
copyAst.isGeneric = true;
copyAst.genericIdentifierUUID = identifierUUID;
return copyAst;
};
|
JavaScript
| 0.000072 |
@@ -2983,16 +2983,54 @@
sGeneric
+ && ast.genericIdentifierUUID !== null
) %7B%0A
|
43e6a3be74bf077397131d6fbf7f5557beafa07c
|
Remove linebreaks from words in input file
|
app/initialize.js
|
app/initialize.js
|
var Trie = require('trie');
trie = new Trie();
/* Request words file */
var wordRequest = new XMLHttpRequest();
wordRequest.addEventListener('load', transferComplete, false);
wordRequest.addEventListener('progress', updateProgress, false);
wordRequest.open('get', 'words.txt', true);
var percentElement = document.getElementById('loading');
function updateProgress(event) {
if (event.lengthComputable) {
var percentComplete = (100 * event.loaded / event.total).toFixed(0) + '%';
percentElement.innerHTML = percentComplete;
}
}
function transferComplete() {
var words = this.responseText.split('\n');
for (var word in words) {
trie.add(words[word]);
}
var spinnerElement = document.getElementById('spinner');
var mainElement = document.getElementById('main');
spinnerElement.parentElement.removeChild(spinnerElement);
mainElement.style.display = 'block';
}
wordRequest.send();
/* Read input from user */
var searchInput = document.getElementById('search-input');
var searchResults = document.getElementById('search-results');
var addButton = document.getElementById('add-button');
addButton.disabled = true;
searchInput.oninput = function() {
searchResults.innerHTML = '';
var results = trie.search(this.value);
var exists = trie.find(this.value);
if (results) {
for (var result in results) {
var el = document.createElement('li');
var elText = document.createTextNode(results[result]);
el.appendChild(elText);
searchResults.appendChild(el);
}
}
if (exists || !this.value) {
addButton.disabled = true;
} else {
addButton.disabled = false;
}
};
searchInput.onkeyup = function(event) {
if (event.which === 13) {
addButton.click();
}
};
addButton.onclick = function() {
trie.add(searchInput.value);
var result = trie.find(searchInput.value);
if (result) {
searchInput.oninput();
}
};
console.log(trie);
|
JavaScript
| 0.000016 |
@@ -664,16 +664,40 @@
ds%5Bword%5D
+.replace(/%5Cr?%5Cn%7C%5Cr/, '')
);%0A %7D%0A%0A
|
f9ddc8c1da4a0e9fdbc788caebf63f1e23863d1a
|
fix addthis share link for root angular url
|
app/js/addthis.js
|
app/js/addthis.js
|
"use strict";
/**
* AddThis widget directive, Re-renders addthis buttons as angular changes
* views in our app since the add this buttons only load by default on page
* load and not when the DOM is updated. based on:
* {@link http://stackoverflow.com/questions/15593039/angularjs-and-addthis-social-plugin}
* @example
* Usage:
* <!-- 1. include `addthis_widget.js` in index page with async attribute -->
* <script src="//s7.addthis.com/js/300/addthis_widget.js#pubid={pubid}&async=1"></script>
*
* <!-- 2. add "sn-addthis-toolbox" directive to a widget's toolbox div -->
* <div class="addthis_custom_sharing" sn-addthis-toolbox>
* ... ^
* </div>
*
* <!-- 3. add classes to anchor links to attach the link to a service -->
* <!-- ['addthis_button_google_plusone_share','addthis_button_twitter','addthis_button_facebook'] -->
* <a href class="addthis_button_google_plusone_share">Share on Google+</a>
*
* @main sn.addthis
* @module sn.addthis
* @author SOON_
*/
angular.module("sn.addthis", [])
/**
* angular directive which initialise addthis toolbox
* @example
* <sn-addthis-toolbox class="addthis_custom_sharing">
* <a href class="addthis_button_facebook">Facebook</a>
* </sn-addthis-toolbox>
* @class snAddthisToolbox
* @module sn.addthis
* @author SOON_
*/
.directive("snAddthisToolbox", [
"$document",
"$timeout",
"$window",
"$location",
/**
* @constructor
* @param {Service} $document
* @param {Service} $timeout
* @param {Service} $window
* @param {Service} $location
*/
function ($document, $timeout, $window, $location) {
return {
restrict: "EAC",
replace: false,
scope: {
share: "="
},
link: function ($scope, $element) {
/**
* Number of times to check for stock addthis buttons
* @property checksLeft
* @type {Number}
* @default 10
*/
$scope.checksLeft = 10;
/**
* {@link http://support.addthis.com/customer/portal/articles/1337994-the-addthis_config-variable}
* @property config
* @type {Object}
*/
$scope.config = $window.addthis_config ? $window.addthis_config : {}; // jshint ignore:line
/**
* Removes the stock addthis buttons
* @method removeStockButtons
*/
$scope.removeStockButtons = function removeStockButtons() {
if ($scope.checksLeft > 0){
$scope.checksLeft--;
var addthisEl = $element[0].getElementsByClassName("at-share-tbx-element")[0];
if (addthisEl){
addthisEl.parentNode.removeChild(addthisEl);
} else {
$timeout.cancel($scope.timer);
$scope.timer = $timeout($scope.removeStockButtons, 500);
}
}
};
/**
* Initialise the addthis buttons on directive load
* @method init
*/
$scope.init = function init(){
// Use location service to get url if not set
$scope.share = $scope.share || {};
if (!$scope.share.url) {
$scope.share.url = $location.absUrl();
}
$window.addthis.init();
if ($window.addthis.layers && $window.addthis.layers.refresh) {
$window.addthis.layers.refresh();
}
$window.addthis.toolbox($element[0], $scope.config, $scope.share);
$scope.timer = $timeout($scope.removeStockButtons, 500);
};
$scope.init();
}
};
}
]);
|
JavaScript
| 0 |
@@ -3626,16 +3626,234 @@
bsUrl();
+%0A%0A // Fix addthis share link for root url%0A if ($location.path() === '/') %7B%0A $scope.share.url = $scope.share.url + '#/';%0A %7D
%0A
|
2585f209f98f91da68739bdb33b599df45b3a6e6
|
fix test missing assertion
|
test/res.download.js
|
test/res.download.js
|
var after = require('after');
var assert = require('assert');
var Buffer = require('safe-buffer').Buffer
var express = require('..');
var request = require('supertest');
describe('res', function(){
describe('.download(path)', function(){
it('should transfer as an attachment', function(done){
var app = express();
app.use(function(req, res){
res.download('test/fixtures/user.html');
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Content-Disposition', 'attachment; filename="user.html"')
.expect(200, '<p>{{user.name}}</p>', done)
})
it('should accept range requests', function (done) {
var app = express()
app.get('/', function (req, res) {
res.download('test/fixtures/user.html')
})
request(app)
.get('/')
.expect('Accept-Ranges', 'bytes')
.expect(200, '<p>{{user.name}}</p>', done)
})
it('should respond with requested byte range', function (done) {
var app = express()
app.get('/', function (req, res) {
res.download('test/fixtures/user.html')
})
request(app)
.get('/')
.set('Range', 'bytes=0-2')
.expect('Content-Range', 'bytes 0-2/20')
.expect(206, '<p>', done)
})
})
describe('.download(path, filename)', function(){
it('should provide an alternate filename', function(done){
var app = express();
app.use(function(req, res){
res.download('test/fixtures/user.html', 'document');
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Content-Disposition', 'attachment; filename="document"')
.expect(200, done)
})
})
describe('.download(path, fn)', function(){
it('should invoke the callback', function(done){
var app = express();
var cb = after(2, done);
app.use(function(req, res){
res.download('test/fixtures/user.html', cb);
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Content-Disposition', 'attachment; filename="user.html"')
.expect(200, cb);
})
})
describe('.download(path, filename, fn)', function(){
it('should invoke the callback', function(done){
var app = express();
var cb = after(2, done);
app.use(function(req, res){
res.download('test/fixtures/user.html', 'document', done);
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Content-Disposition', 'attachment; filename="document"')
.expect(200, cb);
})
})
describe('.download(path, filename, options, fn)', function () {
it('should invoke the callback', function (done) {
var app = express()
var cb = after(2, done)
var options = {}
app.use(function (req, res) {
res.download('test/fixtures/user.html', 'document', options, done)
})
request(app)
.get('/')
.expect(200)
.expect('Content-Type', 'text/html; charset=UTF-8')
.expect('Content-Disposition', 'attachment; filename="document"')
.end(cb)
})
it('should allow options to res.sendFile()', function (done) {
var app = express()
app.use(function (req, res) {
res.download('test/fixtures/.name', 'document', {
dotfiles: 'allow',
maxAge: '4h'
})
})
request(app)
.get('/')
.expect(200)
.expect('Content-Disposition', 'attachment; filename="document"')
.expect('Cache-Control', 'public, max-age=14400')
.expect(shouldHaveBody(Buffer.from('tobi')))
.end(done)
})
describe('when options.headers contains Content-Disposition', function () {
it('should be ignored', function (done) {
var app = express()
app.use(function (req, res) {
res.download('test/fixtures/user.html', 'document', {
headers: {
'Content-Type': 'text/x-custom',
'Content-Disposition': 'inline'
}
})
})
request(app)
.get('/')
.expect(200)
.expect('Content-Type', 'text/x-custom')
.expect('Content-Disposition', 'attachment; filename="document"')
.end(done)
})
it('should be ignored case-insensitively', function (done) {
var app = express()
app.use(function (req, res) {
res.download('test/fixtures/user.html', 'document', {
headers: {
'content-type': 'text/x-custom',
'content-disposition': 'inline'
}
})
})
request(app)
.get('/')
.expect(200)
.expect('Content-Type', 'text/x-custom')
.expect('Content-Disposition', 'attachment; filename="document"')
.end(done)
})
})
})
describe('on failure', function(){
it('should invoke the callback', function(done){
var app = express();
app.use(function (req, res, next) {
res.download('test/fixtures/foobar.html', function(err){
if (!err) return next(new Error('expected error'));
res.send('got ' + err.status + ' ' + err.code);
});
});
request(app)
.get('/')
.expect(200, 'got 404 ENOENT', done);
})
it('should remove Content-Disposition', function(done){
var app = express()
app.use(function (req, res, next) {
res.download('test/fixtures/foobar.html', function(err){
if (!err) return next(new Error('expected error'));
res.end('failed');
});
});
request(app)
.get('/')
.expect(shouldNotHaveHeader('Content-Disposition'))
.expect(200, 'failed', done);
})
})
})
function shouldHaveBody (buf) {
return function (res) {
var body = !Buffer.isBuffer(res.body)
? Buffer.from(res.text)
: res.body
assert.ok(body, 'response has body')
assert.strictEqual(body.toString('hex'), buf.toString('hex'))
}
}
function shouldNotHaveHeader(header) {
return function (res) {
assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header);
};
}
|
JavaScript
| 0.002886 |
@@ -2496,22 +2496,19 @@
ument',
-done);
+cb)
%0A %7D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.