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
|
---|---|---|---|---|---|---|---|
d2e9581f0b6d2c668a16fbab64d64bef78416d0e
|
Fix scale when reading from a geometry file.
|
server/util/wall_geometry.js
|
server/util/wall_geometry.js
|
/* Copyright 2019 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {Polygon} from '../../lib/math/polygon2d.js';
import fs from 'fs';
import {easyLog} from '../../lib/log.js';
const log = easyLog('wall:wall_geometry');
// Returns a polygon that entirely contains the wall geometry. NOTE: any point
// to the left of the polygon is outside of it, because we assume that points
// are addressed from the top-left pixel.
function parseGeometry(polygonPoints) {
const points = polygonPoints.reduce(function(agg, point) {
const last = agg[agg.length - 1];
let next;
if (point.right) {
next = {x: last.x + point.right, y: last.y};
} else if (point.down) {
next = {x: last.x, y: last.y + point.down};
} else if (point.left) {
next = {x: last.x - point.left, y: last.y};
} else if (point.up) {
next = {x: last.x, y: last.y - point.up};
}
agg.push(next);
return agg;
}, [{x: 0, y: 0}]);
return new Polygon(points);
}
export function loadGeometry(path) {
// Convert from config description to actual polygon.
const config = JSON.parse(fs.readFileSync(path));
return config.polygon;
}
let geo;
export function getGeo() {
return geo;
}
// TODO(applmak): Geometry specified as a single polygon doesn't really accurately reflect what's going on
// on an actual wall, which has a bunch of rectangles slightly offset from one another. Instead of a poly,
// switch the model generating a concave hull of the screens as they load in, which becomes the poly.
export function init(flags) {
let xscale = 1920;
let yscale = 1080;
if (flags.screen_width) {
xscale = flags.screen_width;
yscale = xscale * 1080 / 1920;
}
if (!flags.use_geometry && !flags.geometry_file) {
log.warn('No wall geometry specified... assuming 1x1.');
geo = parseGeometry([{"right":1},{"down":1},{"left":1},{"up":1}]).scale(xscale, yscale);
} else if (flags.use_geometry) {
geo = parseGeometry(flags.use_geometry).scale(xscale, yscale);
} else if (flags.geometry_file) {
// Note that the geometry loaded from a file isn't scaled.
geo = parseGeometry(loadGeometry(flags.geometry_file));
}
}
|
JavaScript
| 0 |
@@ -2752,16 +2752,38 @@
y_file))
+.scale(xscale, yscale)
;%0A %7D%0A%7D%0A
|
91970c5eac8cd1ff53b9ac8dd2c50f7f2a2bf9e6
|
remove flash.destroy as it fails on latest builds of Ember (#218)
|
tests/unit/components/flash-message-test.js
|
tests/unit/components/flash-message-test.js
|
import Ember from 'ember';
import {
moduleForComponent,
test
} from 'ember-qunit';
import FlashMessage from 'ember-cli-flash/flash/object';
const {
run,
get,
set
} = Ember;
let flash;
moduleForComponent('flash-message', 'FlashMessageComponent', {
unit: true,
beforeEach() {
flash = FlashMessage.create({
message: 'test',
type: 'test',
timeout: 50,
extendedTimeout: 5000,
showProgress: true
});
},
afterEach() {
run(() => {
flash.destroy();
});
flash = null;
}
});
test('it renders with the right props', function(assert) {
assert.expect(5);
const component = this.subject({ flash });
assert.equal(get(component, 'active'), false, 'it initializes with `active` set to false');
this.render();
assert.equal(get(component, 'alertType'), 'alert alert-test', 'it has the right `alertType`');
assert.equal(get(component, 'flashType'), 'Test', 'it has the right `flashType`');
assert.equal(get(component, 'progressDuration'), `transition-duration: ${flash.get('timeout')}ms`, 'it has the right `progressDuration`');
run.next(() => {
assert.equal(get(component, 'active'), true, 'it sets `active` to true after rendering');
});
});
test('exiting the flash object sets exiting on the component', function(assert) {
assert.expect(2);
const component = this.subject({ flash });
this.render();
assert.equal(get(component, 'exiting'), false, 'it initializes with `exiting` set to false');
run(() => {
set(flash, 'exiting' , true);
assert.ok(get(component, 'exiting'), 'it sets `exiting` to true when the flash object is exiting');
});
});
test('it destroys the flash object on click', function(assert) {
assert.expect(1);
const component = this.subject({ flash });
this.render();
$('.alert').click();
assert.ok(get(component, 'flash').isDestroyed, 'it destroys the flash object on click');
});
test('it does not destroy the flash object when `flash.destroyOnClick` is false', function(assert) {
assert.expect(1);
flash.destroyOnClick = false;
const component = this.subject({ flash });
this.render();
$('.alert').click();
assert.notOk(get(component, 'flash').isDestroyed, 'it does not destroy the flash object on click');
});
|
JavaScript
| 0 |
@@ -468,56 +468,8 @@
) %7B%0A
- run(() =%3E %7B%0A flash.destroy();%0A %7D);%0A%0A
|
653e8358ddb7e82e78ccef183036013a5365df69
|
Add deep test
|
test/manager.create.js
|
test/manager.create.js
|
var assert = require('assert');
var Promise = require('bluebird');
var Bootstrap = require('./support/bootstrap');
var manager = require('./support/manager');
describe('manager', function() {
describe('.create', function() {
Bootstrap.beforeEach(Bootstrap.database);
Bootstrap.beforeEach(Bootstrap.tables);
it('should create a new model', function(done) {
manager.create('car').then(function(car) {
assert.ok(manager.isModel(car), 'Car should be a Model');
assert.ok(car.id, 'Car should have ID 1');
done();
});
});
it('should create a new collection', function(done) {
manager.create('cars').then(function(cars) {
assert.ok(manager.isCollection(cars), 'Car should be a Collection');
done();
});
});
it('should create a new, populated model', function(done) {
manager.create('car', {
quantity: 1
}).then(function(car) {
assert.equal(1, car.id, 'Car should have ID 1');
assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
done();
});
})
it('should create a new, populated collection', function(done) {
manager.create('cars', [
{ quantity: 1 },
{ quantity: 2 },
]).then(function(cars) {
assert.equal(2, cars.length, 'Cars collection should have 2 Car models');
assert.equal(1, cars.at(0).id, 'Car #1 should have ID 1, not ' + cars.at(0).id);
assert.equal(2, cars.at(1).id, 'Car #2 should have ID 2, not ' + cars.at(1).id);
done();
});
})
it('should create a model within a new model (belongsTo)', function(done) {
manager.create('car', {
color: {
name: 'White',
hex_value: '#fff',
},
quantity: 1
}).then(function(car) {
assert.equal(1, car.id, 'Car should have ID 1');
assert.equal(1, car.get('quantity'), 'Car should have quantity of 1');
assert.equal(1, car.related('color').id, 'Color should have ID 1, not ' + car.related('color').id);
assert.equal('White', car.related('color').get('name'), 'Color name should be White');
assert.equal('#fff', car.related('color').get('hex_value'), 'Color hex_value should be #fff');
done();
})
});
it('should modify an existing nested model', function(done) {
manager.create('color', {
name: 'White',
hex_value: '#fff',
}).then(function(color) {
manager.create('car', {
color: {
id: color.id,
name: 'Grey',
hex_value: '#666',
},
quantity: 2
}).then(function(car) {
assert.equal(color.id, car.related('color').id, 'Color ID should stay the same')
assert.equal('Grey', car.related('color').get('name'), 'Color name should be Grey');
assert.equal('#666', car.related('color').get('hex_value'), 'Color hex_value should be #666');
done();
});
});
});
it('should create models within a nested collection (belongsToMany)', function(done) {
manager.create('car', {
features: [
{ name: 'ABS', cost: '1250' },
{ name: 'GPS', cost: '500' },
],
quantity: 1
}).then(function(car) {
assert.equal(1, car.id, 'Car should have ID 1');
assert.equal(2, car.related('features').length, 'There should be 2 features');
assert.ok(car.related('features').at(0).id, 'Feature #1 should have ID');
assert.ok(car.related('features').at(1).id, 'Feature #2 should have ID');
assert.equal('ABS', car.related('features').at(0).get('name'), 'Feature #1 name should be ABS');
assert.equal('GPS', car.related('features').at(1).get('name'), 'Feature #2 name should be GPS');
done();
});
});
it('should create models within a nested collection (hasMany)', function(done) {
manager.create('make', {
models: [
{ name: 'X3' },
{ name: 'X5' },
]
}).then(function(make) {
assert.equal(1, make.id, 'Make should have ID 1');
assert.equal(2, make.related('models').length);
assert.ok(make.related('models').at(0).id, 'Model #1 should have ID');
assert.ok(make.related('models').at(1).id, 'Model #2 should have ID');
assert.equal('X3', make.related('models').at(0).get('name'), 'Model #1 name should be X3');
assert.equal('X5', make.related('models').at(1).get('name'), 'Model #2 name should be X5');
done();
});
});
});
});
|
JavaScript
| 0.000012 |
@@ -4592,16 +4592,1108 @@
%0A %7D);
+%0A%0A it('should create a deep object', function(done) %7B%0A manager.create('make', %7B%0A name: 'BMW',%0A models: %5B%0A %7B%0A name: 'X5',%0A cost: 50000,%0A type: %7B%0A name: 'Crossover'%0A %7D,%0A specs: %5B%0A %7B name: '4 door' %7D,%0A %7B name: 'v6' %7D,%0A %5D%0A %7D%0A %5D%0A %7D).then(function(result) %7B%0A return manager.fetch('make', %7B name: 'BMW' %7D, %5B'models.type', 'models.specs'%5D).then(function(actual) %7B%0A assert.equal(%0A actual.related('models').length,%0A result.related('models').length%0A );%0A%0A assert.equal(%0A actual.related('models').at(0).related('specs').length,%0A result.related('models').at(0).related('specs').length%0A );%0A%0A assert.equal(%0A JSON.stringify(actual.related('models').at(0).related('type').toJSON(), null, 2),%0A JSON.stringify(result.related('models').at(0).related('type').toJSON(), null, 2)%0A );%0A%0A done();%0A %7D);%0A %7D);%0A %7D);
%0A %7D);%0A%7D
|
a2b3744c2939c2f8511b790de297277f76b96a28
|
Replace all occurences of substrings instead of one
|
src/libs/better.js
|
src/libs/better.js
|
/* global _: true */
var better = {};
/**
* Better key
* Transform a bad formated string in a good key name
*/
better.key = function(value){
value = value
.replace(String.fromCharCode(58), '')
.replace(String.fromCharCode(160), String.fromCharCode(32));
return _.camelCase(value);
};
/**
* Better value
* Transform a bad formated string in a good value name
*/
better.value = function(value){
return value
.replace(String.fromCharCode(160), String.fromCharCode(32))
.trim();
};
/**
* Better int
* Transform string in int
*/
better.int = function(value){
value = value.match(/[0-9]+/g);
if(_.isArray(value) && value.length > 1) {
value.join('');
}
if(_.isArray(value) && value.length === 1) {
value = value[0];
}
return parseInt(value);
};
/**
* Better url
* Urlify string
*/
better.url = function(value){
return value
.replace(' ', '+')
.replace('%20', '+')
.replace('%2B', '+');
};
/**
* Better serialize
* Serialize object
*/
better.serialize = function(obj){
var serialized = Object.keys(obj)
.reduce(function(a, k){
a.push(k + '=' + encodeURIComponent(obj[k]));
return a;
},[])
.join('&');
return '?' + serialized.replace('%2B', '+');
};
/**
* Better deathBy
* Transform deathBy list into array
*/
better.deathBy = function(value){
return value
.match(/\D+/g)[1]
.replace('by an')
.replace('by a', '')
.replace('by', '')
.replace('.', '')
.replace(' and ',', ')
.trim()
.split(', ');
};
module.exports = better;
|
JavaScript
| 0.999994 |
@@ -161,32 +161,43 @@
ue%0A .replace(
+new RegExp(
String.fromCharC
@@ -204,16 +204,22 @@
ode(58),
+ 'g'),
'')%0A
@@ -220,32 +220,43 @@
')%0A .replace(
+new RegExp(
String.fromCharC
@@ -256,32 +256,38 @@
omCharCode(160),
+ 'g'),
String.fromChar
@@ -471,16 +471,27 @@
replace(
+new RegExp(
String.f
@@ -507,16 +507,22 @@
de(160),
+ 'g'),
String.
|
f2620c42762313479f8f3d6110b3e026b39db457
|
Fix `moduleForComponent` syntax
|
tests/unit/components/pikaday-input-test.js
|
tests/unit/components/pikaday-input-test.js
|
import { test, moduleForComponent } from 'ember-qunit';
import Ember from 'ember';
import { openDatepicker } from 'ember-pikaday/helpers/pikaday';
moduleForComponent('pikaday-input', 'PikadayInputComponent');
test('is an input tag', function(assert) {
assert.equal('INPUT', this.$().prop('tagName'));
});
test('the input tag has the readonly attribute if it has been set on the component', function(assert) {
this.subject({ 'readonly': true });
assert.ok(this.$().is('[readonly]'));
});
test('clicking the input opens the pikaday dialog', function(assert) {
this.render();
assert.ok($('.pika-single').hasClass('is-hidden'));
openDatepicker(this.$());
assert.ok(!$('.pika-single').hasClass('is-hidden'));
});
test('selecting a date should update the value attribute', function(assert) {
var interactor = openDatepicker(this.$());
interactor.selectDate(new Date(2013, 3, 28));
var date = this.subject().get('value');
assert.equal(date.getFullYear(), 2013);
assert.equal(date.getMonth(), 3);
assert.equal(date.getDate(), 28);
});
test('setting the value attribute should select the correct date', function(assert) {
this.subject({ value: new Date(2010, 7, 10) });
var interactor = openDatepicker(this.$());
assert.equal(interactor.selectedYear(), 2010);
assert.equal(interactor.selectedMonth(), 7);
assert.equal(interactor.selectedDay(), 10);
});
test('DD.MM.YYYY should be the default format for the input', function(assert) {
this.subject({ value: new Date(2010, 7, 10) });
assert.equal(this.$().val(), '10.08.2010');
});
test('format of the input is changeable', function(assert) {
this.subject({ format: 'YYYY.DD.MM', value: new Date(2010, 7, 10) });
assert.equal(this.$().val(), '2010.10.08');
});
test('yearRange of the input defaults to 10', function(assert) {
var interactor = openDatepicker(this.$());
var currentYear = new Date().getFullYear();
assert.equal(interactor.minimumYear(), currentYear - 10);
assert.equal(interactor.maximumYear(), currentYear + 10);
});
test('yearRange of the input can be set with a range', function(assert) {
this.subject({ yearRange: '4' });
var interactor = openDatepicker(this.$());
var currentYear = new Date().getFullYear();
assert.equal(interactor.minimumYear(), currentYear - 4);
assert.equal(interactor.maximumYear(), currentYear + 4);
});
test('yearRange of the input can be set with comma separated years', function(assert) {
this.subject({ yearRange: '1900,2006' });
var interactor = openDatepicker(this.$());
assert.equal(interactor.minimumYear(), 1900);
assert.equal(interactor.maximumYear(), 2006);
});
test('yearRange of the input with comma separated years supports currentYear as max', function(assert) {
this.subject({ yearRange: '1900,currentYear' });
var interactor = openDatepicker(this.$());
var currentYear = new Date().getFullYear();
assert.equal(interactor.minimumYear(), 1900);
assert.equal(interactor.maximumYear(), currentYear);
});
test('default i18n configuration of Pikaday can be changed', function(assert) {
this.subject({
i18n: {
previousMonth: 'Vorheriger Monat',
nextMonth: 'Nächster Monat',
months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
weekdays: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
weekdaysShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
},
value: new Date(2014, 2, 10)
});
openDatepicker(this.$());
assert.equal($('.pika-select-month option:selected').text(), 'März');
});
test('if utc is set the date returned from pikaday should be in UTC format', function(assert) {
this.subject({ useUTC: true });
var interactor = openDatepicker(this.$());
interactor.selectDate(new Date(2013, 3, 28));
var date = this.subject().get('value');
assert.equal(date.getUTCFullYear(), 2013);
assert.equal(date.getUTCMonth(), 3);
assert.equal(date.getUTCDate(), 28);
});
|
JavaScript
| 0.0004 |
@@ -200,16 +200,20 @@
mponent'
+, %7B%7D
);%0A%0Atest
|
4a7304c9ac22d3b0fae53be46ee84a5dc5b01d94
|
use correct setters
|
static/js/addons/cl.utils.js
|
static/js/addons/cl.utils.js
|
/*!
* @author: Divio AG
* @copyright: http://www.divio.ch
*/
//######################################################################################################################
// #NAMESPACES#
/**
* @module Cl
*/
var Cl = window.Cl || {};
//######################################################################################################################
// #UTILS#
(function ($) {
'use strict';
/**
* Contains various helpers, feel free to extend and adapt
*
* @class Utils
* @namespace Cl
*/
Cl.Utils = {
/**
* Document setup for no javascript fallbacks and logging
*
* @method _document
* @private
*/
_document: function () {
// remove no-js class if javascript is activated
$(document.body).removeClass('noscript');
// ensure that console methods don't throw errors
this._consoleWrapper();
},
/**
* Stubs all the methods from console api that are not available in current environment
* DOCS: https://developer.chrome.com/devtools/docs/console-api
*
* @method _consoleWrapper
* @private
*/
_consoleWrapper: function () {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
},
/**
* Simple redirection
*
* @method redirectTo
* @param url {String} URL string
*/
redirectTo: function (url) {
window.location.href = url;
},
/**
* Save information within local storage
*
* @method setStorage
* @param token {String} namespace
* @param value {String} storage value
*/
setStorage: function (token, value) {
if (window.localStorage) {
localStorage.setItem(token, value);
}
},
/**
* Retrieve information from local storage
*
* @method getStorage
* @param token {String} namespace
*/
getStorage: function (token) {
if (window.localStorage) {
return localStorage.getItem(token);
}
}
};
})(jQuery);
|
JavaScript
| 0.00016 |
@@ -2512,35 +2512,43 @@
if (
-window.localStorage
+typeof(Storage) !== void(0)
) %7B%0A
@@ -2839,27 +2839,35 @@
if (
-window.localStorage
+typeof(Storage) !== void(0)
) %7B%0A
|
d061590f5b5e39314f88a83bdbabb733b7410d75
|
Move areInValue method
|
static/js/form-collection.js
|
static/js/form-collection.js
|
'use strict';
window.define(['react', 'color-picker', 'underscore'], function (React, ColorPicker, _) {
var searchableTypes = [
'name',
'defaultValue',
'value',
'label'
];
var FormCollection = React.createClass({
areDefined: function (value) {
return typeof value !== 'undefined';
},
containsSearchTerm: function (value, key) {
var searchTerm = this.props.searchTerm.toLowerCase().replace(/\s+?/gi, ' ');
var searchTerms = searchTerm.split(' ');
var areInValue = function (term) {
return value.toLowerCase().indexOf(term) >= 0;
};
return searchableTypes.indexOf(key) >= 0 &&
value &&
(
value.toLowerCase().indexOf(searchTerm) >= 0 ||
_.every(searchTerms, areInValue)
);
},
create: {
subHeader: function (child) {
if (this.props.searchTerm) {
return undefined;
}
return React.createElement(
'h5',
null,
child.value
);
},
variable: function (child, index) {
var self = this;
var colorPicker, label;
if (this.props.searchTerm && !_.any(child, this.containsSearchTerm)) {
return undefined;
}
if (child.type === 'color') {
colorPicker = React.createElement(
ColorPicker,
{
setValue: self.props.updateVariable.bind(null, self.props.index, index),
value: child.value,
defaultValue: child.defaultValue
}
);
}
if (child.label) {
label = React.createElement(
'p',
null,
React.createElement(
'sub',
null,
child.label
)
);
}
return React.createElement(
'div',
{
className: 'form-group'
},
label,
React.createElement(
'label',
null,
child.name
),
React.createElement(
'div',
{
className: 'input-wrapper'
},
React.createElement(
'input',
{
className: 'form-control',
placeholder: child.defaultValue,
value: child.value,
onChange: self.props.updateVariable.bind(null, self.props.index, index)
},
child.value
),
colorPicker
)
);
}
},
render: function () {
var self = this;
var description, hasSearchResults, children;
var isNotActiveCollection = typeof this.props.activeIndex !== 'undefined' && this.props.index !== this.props.activeIndex;
var isActiveCollection = typeof this.props.activeIndex !== 'undefined' && this.props.index === this.props.activeIndex;
if (isNotActiveCollection && !this.props.searchTerm) {
return false;
}
if (isActiveCollection || this.props.searchTerm) {
children = this.props.group.children.map(function (child, index) {
return self.create[child.element].call(self, child, index);
});
}
if (isActiveCollection && this.props.group.description) {
description = React.createElement(
'p',
null,
this.props.group.description
);
}
if (this.props.searchTerm) {
hasSearchResults = _.any(children, this.areDefined);
if (!hasSearchResults) {
return false;
}
}
return React.createElement(
'div',
{
className: 'form-collection' +
(isActiveCollection ? ' active' : '') +
(hasSearchResults ? ' filtered' : '')
},
React.createElement(
'a',
{
onClick: self.props.setActiveCollection.bind(null, this.props.index)
},
React.createElement(
'h4',
null,
this.props.group.value
)
),
description,
children
);
}
});
return FormCollection;
});
|
JavaScript
| 0.000004 |
@@ -313,24 +313,126 @@
d';%0A %7D,%0A%0A
+ areInValue: function (value, term) %7B%0A return value.toLowerCase().indexOf(term) %3E= 0;%0A %7D,%0A%0A
contains
@@ -463,24 +463,47 @@
lue, key) %7B%0A
+ var self = this;%0A
var se
@@ -625,114 +625,8 @@
);%0A%0A
- var areInValue = function (term) %7B%0A return value.toLowerCase().indexOf(term) %3E= 0;%0A %7D;%0A%0A
@@ -787,16 +787,21 @@
hTerms,
+self.
areInVal
@@ -802,16 +802,34 @@
eInValue
+.bind(self, value)
)%0A
|
7dcdd9048d08c1c455b0ffd8c9b36635d122cd82
|
simplify reading of implementation
|
src/modules/list/zip.es6
|
src/modules/list/zip.es6
|
import {curry} from '../functional/curry';
/* jshint -W067 */
export
const zip = curry((arr1, arr2) => (
(aux =>
(aux = ([x1,...arr1], [x2,...arr2], acc) =>
x1 === undefined || x2 === undefined ? acc
: aux(arr1, arr2, [...acc, [x1, x2]])
)(arr1, arr2, [])
)()
));
/* jshint +W067 */
|
JavaScript
| 0.000008 |
@@ -41,96 +41,23 @@
';%0A%0A
-/* jshint -W067 */%0Aexport%0A
+%0A
const
+_
zip =
+%0A
-curry((arr1, arr2) =%3E (%0A (aux =%3E%0A (aux =
(%5Bx
@@ -90,20 +90,16 @@
acc) =%3E%0A
-
x1 =
@@ -182,17 +182,14 @@
-
-
:
-aux
+_zip
(arr
@@ -220,62 +220,73 @@
2%5D%5D)
-%0A )(arr1, arr2, %5B%5D)%0A )()%0A ));%0A/* jshint +W067 */
+;%0A%0Aexport%0A const zip = curry((arr1, arr2) =%3E _zip(arr1, arr2, %5B%5D));
%0A
|
005f3368c00f176c7a186252ce2379bf83d8717b
|
Remove setTimeout hack from ExampleIcon.ready.
|
library/CM/Form/ExampleIcon.js
|
library/CM/Form/ExampleIcon.js
|
/**
* @class CM_Form_ExampleIcon
* @extends CM_Form_Abstract
*/
var CM_Form_ExampleIcon = CM_Form_Abstract.extend({
/** @type String */
_class: 'CM_Form_ExampleIcon',
events: {
'click .iconBox': function(event) {
this.selectIcon($(event.currentTarget));
}
},
ready: function() {
this.on('change', function() {
this._updateCss();
}, this);
var self = this;
setTimeout(function() {
self._updateCss();
}, 0);
},
/**
* @param {jQuery} $icon
*/
selectIcon: function($icon) {
$icon.addClass('active').siblings().removeClass('active');
this.$('.iconMarkup').text('<span class="icon icon-' + $icon.find('.label').text() + '"></span>');
},
_getShadowValue: function() {
return [
this.getField('shadowColor').getValue() || '#fff', this.getField('shadowX').getValue() + 'px', this.getField('shadowY').getValue() + 'px', this.getField('shadowBlur').getValue() + 'px'
].join(' ');
},
_updateCss: function() {
var appliedStyles = {};
appliedStyles['background-color'] = this.$('.iconBox').css('background-color', this.getField('colorBackground').getValue()).css('background-color');
appliedStyles['text-shadow'] = this.$('.iconBox .icon').css('text-shadow', this._getShadowValue()).css('text-shadow');
appliedStyles['color'] = this.$('.iconBox .icon').css('color', this.getField('color').getValue()).css('color');
appliedStyles['font-size'] = this.$('.iconBox .icon').css('font-size', this.getField('sizeSlider').getValue() + "px").css('font-size');
this.$('.iconCss').html(_.reduce(appliedStyles, function(memo, value, key) {
return memo + key + ': ' + value + ';<br />';
}, ''));
}
});
|
JavaScript
| 0 |
@@ -384,63 +384,12 @@
-var self = this;%0A setTimeout(function() %7B%0A self
+this
._up
@@ -403,19 +403,8 @@
();%0A
- %7D, 0);%0A
%7D,
|
7facb6f5575b41975925bbba1d207c30c595504e
|
add cache namespace flush tests
|
test/services/cache.js
|
test/services/cache.js
|
import test from 'ava';
import DI from '../../src/di';
import * as providers from '../../src/services/providers';
DI.registerMockedProviders(Object.values(providers), `${__dirname}/../_demo_project/config`);
const cache = DI.get('cache');
test.beforeEach('Flush all', () => {
cache.flush();
});
test('Cache get & set', async(t) => {
await cache.set('foo', 'bar');
t.is(await cache.get('foo'), 'bar');
});
test('Cache namespace get & set', async(t) => {
await cache.namespace('ns').set('foo', 'bar');
t.is(await cache.namespace('ns').get('foo'), 'bar');
t.is(await cache.namespace('ns1').has('foo'), false);
});
test('Cache namespace flush', async(t) => {
await cache.namespace('ns').set('foo', 'bar');
await cache.namespace('ns1').set('foo', 'bar');
await cache.namespace('ns').flush();
t.is(await cache.namespace('ns').has('foo'), false);
t.is(await cache.namespace('ns1').has('foo'), true);
});
test('Cache set nx || xx', async(t) => {
let ret = await cache.set('foo', 'bar', 0, 'xx');
t.true(ret === null);
ret = await cache.set('foo', 'bar', 0, 'nx');
t.true(ret === 'OK');
ret = await cache.set('foo', 'bar', 0, 'nx');
t.true(ret === null);
ret = await cache.set('foo', 'bar', 0, 'xx');
t.true(ret === 'OK');
ret = await cache.set('foo', 'bar', 1, 'xx');
t.true(ret === 'OK');
await cache.flush();
});
test('Cache namespace set nx || xx', async(t) => {
let ret = await cache.namespace('ns').set('foo', 'bar', 0, 'xx');
t.true(ret === null);
ret = await cache.namespace('ns').set('foo', 'bar', 0, 'nx');
t.true(ret === 'OK');
ret = await cache.namespace('ns').set('foo', 'bar', 0, 'nx');
t.true(ret === null);
ret = await cache.namespace('ns').set('foo', 'bar', 0, 'xx');
t.true(ret === 'OK');
ret = await cache.namespace('ns').set('foo', 'bar', 1, 'xx');
t.true(ret === 'OK');
await cache.namespace('ns').flush();
});
|
JavaScript
| 0 |
@@ -1892,20 +1892,345 @@
e('ns').flush();%0A%7D);
+%0A%0Atest('Cache namespace flush returns', async(t) =%3E %7B%0A t.is(await cache.namespace('ns').flush(), 0);%0A%0A await cache.namespace('ns').set('foo1', 'bar1', 0, 'nx');%0A await cache.namespace('ns').set('foo2', 'bar2', 0, 'xx');%0A await cache.namespace('ns').set('foo3', 'bar3');%0A t.is(await cache.namespace('ns').flush(), 2);%0A%7D);
|
1116a4a08a2c32709f78f6201d9a499551da2266
|
Use exponential notation in integration test timeout setup
|
setup-integration-timeout.js
|
setup-integration-timeout.js
|
"use strict";
// allow CLI integration tests to run for awhile
jasmine.DEFAULT_TIMEOUT_INTERVAL = 300000;
|
JavaScript
| 0.000004 |
@@ -56,16 +56,23 @@
r awhile
+ (300s)
%0Ajasmine
@@ -102,13 +102,12 @@
AL = 300
-000
+e3
;%0A
|
192715add404d2b7b363c184d7b68c4fd09c18da
|
add spec name console
|
test/ssr/build-test.js
|
test/ssr/build-test.js
|
/**
* @file build test file
* @author zhoumin
*/
const san = require('../../dist/san.ssr');
const fs = require('fs');
const path = require('path');
let htmlTpl = fs.readFileSync(path.resolve(__dirname, '../index-ssr.html.tpl'), 'UTF-8');
let html = '';
let specTpls = '';
// generate html
let genContent = function ({componentClass, componentSource, compontentData, specTpl, dirName, result}) {
let renderer = san.compileToRenderer(componentClass);
let id = dirName;
// if no inject mark, add it
if (!/\/\/\s*\[inject\]/.test(specTpl)) {
specTpl = specTpl.replace(/function\s*\([a-z0-9_,$\s]*\)\s*\{/, function ($0) {
return $0 + '\n// [inject] init';
});
}
let injectHtml = result ? result : renderer(compontentData);
html += '<div id="' + id + '">'
+ injectHtml
+ '</div>\n\n';
let preCode = `
${componentSource}
var wrap = document.getElementById('${id}');
var myComponent = new MyComponent({
el: wrap.firstChild
});
`;
specTpl = specTpl.replace(/\/\/\s*\[inject\]\s* init/, preCode);
specTpls += specTpl;
};
let buildFile = function (filePath) {
let files = fs.readdirSync(filePath);
let componentClass;
let componentSource;
let specTpl;
let compontentData;
let dirName;
let result;
let sourceFile = '';
if (!files.length) {
return;
}
files.forEach(filename => {
// absolute path
let abFilePath = path.join(filePath, filename);
let stats = fs.statSync(abFilePath);
let isFile = stats.isFile();
let isDir = stats.isDirectory();
// if it's a file, init data
if (isFile) {
// component file
if (filename === 'component.js') {
componentClass = require(abFilePath);
componentSource = fs.readFileSync(path.resolve(abFilePath), 'UTF-8')
.split('\n')
.map(line => {
if (/(\.|\s)exports\s*=/.test(line)
|| /san\s*=\s*require\(/.test(line)
) {
return '';
}
return line;
})
.join('\n');
sourceFile = filename;
}
if (filename === 'spec.js') {
specTpl = fs.readFileSync(path.resolve(abFilePath), 'UTF-8');
}
if (filename === 'data.js') {
compontentData = require(abFilePath);
}
if (filename === 'result.html') {
result = fs.readFileSync(path.resolve(abFilePath), 'UTF-8').replace('\n', '');
}
}
// iterate
if (isDir) {
buildFile(abFilePath);
}
});
let match = filePath.match(/\/([a-zA-Z0-9_,$\-]*)$/);
// dirName is the identity of each component
dirName = match[1];
// generate html when it has source file
if (sourceFile) {
genContent({
componentClass,
componentSource,
compontentData,
specTpl,
dirName,
result
});
}
};
let writeIn = function ({htmlTpl, html, specTpls}) {
let karmaHtml = fs.readFileSync(path.resolve(__dirname, '../karma-context.html.tpl'), 'UTF-8');
fs.writeFileSync(
path.resolve(__dirname, '../karma-context.html'),
karmaHtml.replace('##ssr-elements##', html),
'UTF-8'
);
fs.writeFileSync(
path.resolve(__dirname, '../index-ssr.html'),
htmlTpl.replace('##ssr-elements##', html),
'UTF-8'
);
fs.writeFileSync(
path.resolve(__dirname, 'ssr.spec.js'),
specTpls,
'UTF-8'
);
};
buildFile(path.resolve(__dirname, './'));
// write into file
writeIn({htmlTpl, html, specTpls});
|
JavaScript
| 0.000001 |
@@ -2816,24 +2816,81 @@
f (isDir) %7B%0A
+ console.log(%60%5BBuild SSR spec%5D $%7Bfilename%7D%60);%0A
|
21fa78de5f733a22397812f77850b5fb54a089ac
|
Add support for multi-test meta tests.
|
test/support/runner.js
|
test/support/runner.js
|
#!/usr/bin/env node
var glob = require('glob')
var path = require('path')
var _ = require('lodash')
var async = require('async')
var teenytest = require('../../index')
var globLocator = process.argv[2] || 'test/*.js'
var passing = false
async.series(_.map(glob.sync(globLocator), function (file) {
return function (cb) {
teenytest.plugins.unregisterAll()
console.log('Running test in "' + file + '"')
require(path.resolve(process.cwd(), file))(cb)
}
}), function (er) {
if (er) { throw er }
console.log('Looks good!')
passing = true
})
process.on('exit', function () {
if (!passing) {
console.error('You fail!')
process.exit(1)
}
})
|
JavaScript
| 0 |
@@ -294,16 +294,110 @@
file) %7B%0A
+ var metaTest = require(path.resolve(process.cwd(), file))%0A if (_.isFunction(metaTest)) %7B%0A
return
@@ -409,24 +409,26 @@
tion (cb) %7B%0A
+
teenytes
@@ -453,24 +453,26 @@
erAll()%0A
+
+
console.log(
@@ -513,54 +513,288 @@
-require(path.resolve(process.cwd(), file))(cb)
+ metaTest(cb)%0A %7D%0A %7D else %7B%0A return function (cb) %7B%0A async.eachSeries(_.toPairs(metaTest), function (entry, cb) %7B%0A teenytest.plugins.unregisterAll()%0A console.log('Running test %22' + entry%5B0%5D + '%22 in %22' + file + '%22')%0A entry%5B1%5D(cb)%0A %7D, cb)%0A %7D
%0A %7D
|
982a7cccb5abdb32d15c5703451e32275c9786ae
|
Fix duplicate variable causing test failure.
|
test/tap/prepublish.js
|
test/tap/prepublish.js
|
// verify that prepublish runs on pack and publish
var test = require('tap').test
var npm = require('../../')
var fs = require('fs')
var pkg = __dirname + '/prepublish_package'
var tmp = pkg + '/tmp'
var cache = pkg + '/cache'
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var npm = require('npm')
var path = require('path')
test('setup', function (t) {
var n = 0
mkdirp(pkg, then())
mkdirp(cache, then())
mkdirp(tmp, then())
function then (er) {
n ++
return function (er) {
if (er)
throw er
if (--n === 0)
next()
}
}
function next () {
fs.writeFile(pkg + '/package.json', JSON.stringify({
name: 'npm-test-prepublish',
version: '1.2.5',
scripts: { prepublish: 'echo ok' }
}), 'ascii', function (er) {
if (er)
throw er
t.pass('setup done')
t.end()
})
}
})
test('test', function (t) {
var spawn = require('child_process').spawn
var node = process.execPath
var npm = path.resolve(__dirname, '../../cli.js')
var env = {
npm_config_cache: cache,
npm_config_tmp: tmp,
npm_config_prefix: pkg,
npm_config_global: 'false'
}
for (var i in process.env) {
if (!/^npm_config_/.test(i))
env[i] = process.env[i]
}
var child = spawn(node, [npm, 'pack'], {
cwd: pkg,
env: env
})
child.stdout.setEncoding('utf8')
child.stderr.on('data', function(chunk) {
throw new Error('got stderr data: ' + JSON.stringify('' + chunk))
})
child.stdout.on('data', ondata)
child.on('close', onend)
var c = ''
function ondata (chunk) {
c += chunk
}
function onend () {
c = c.trim()
t.equal( c
, '> [email protected] prepublish .\n'
+ '> echo ok\n'
+ '\n'
+ 'ok\n'
+ 'npm-test-prepublish-1.2.5.tgz')
t.end()
}
})
test('cleanup', function (t) {
rimraf(pkg, function(er) {
if (er)
throw er
t.pass('cleaned up')
t.end()
})
})
|
JavaScript
| 0.000002 |
@@ -286,33 +286,8 @@
f')%0A
-var npm = require('npm')%0A
var
|
9c467f585f35e90c045908cc8714f052a93eedd4
|
update test code
|
test/test.core.type.js
|
test/test.core.type.js
|
describe('ax5.util.getType TEST', function() {
var testCases = [
{
args: [ 1 ],
expect: 'number'
},
{
args: [ '1' ],
expect: 'string'
},
{
args: [ [0, 1, 2] ],
expect: 'array'
},
{
args: [ {a: 1} ],
expect: 'object'
},
{
args: [ function(){} ],
expect: 'function'
},
{
args: [ document.querySelectorAll("div") ],
expect: 'nodelist'
},
{
args: [ document.querySelector("body") ],
expect: 'element'
},
{
args: [ document.createDocumentFragment() ],
expect: 'fragment'
},
{
args: [ null ],
expect: 'null'
},
{
args: [ undefined ],
expect: 'undefined'
},
{
args: [ window ],
expect: 'window'
}
];
testCases.forEach(function(testCase){
it('ax5.util.getType(' + testCase.expect + ') expect ' + testCase.expect, function() {
var actual = ax5.util.getType.apply(this, testCase.args);
should.equal(actual, testCase.expect);
});
});
});
describe('ax5.util.is{Type}', function() {
var getTypes = function(typeNames, isExclude) {
var types = [
{ name: 'Window', value: window },
{ name: 'DOMElement', value: document.createElement('div') },
{ name: 'Object', value: {} },
{ name: 'Array', value: [] },
{ name: 'Function', value: new Function() },
{ name: 'String', value: 'ax5ui' },
{ name: 'Number', value: 5 },
{ name: 'DOMNodelist', value: document.querySelectorAll('.content') },
{ name: 'undefined', value: undefined },
{ name: 'Null', value: null },
{ name: 'EmptyString', value: '' },
{ name: 'Date', value: new Date() }
];
var matchedTypes = _.map(typeNames, function(typeName){
return _.find(types, { 'name': typeName });
});
if (isExclude === true) {
return _.reject(types, function(type){
return _.findIndex(matchedTypes, { 'name': type.name }) > -1;
});
} else {
return matchedTypes;
}
}
var getTestCases = function(typeNames){
var testCases = [];
var trueExpectedTypes = getTypes(typeNames);
var falseExpectedTypes = getTypes(typeNames, true);
_.each(trueExpectedTypes, function(type){
testCases.push({
args: [ type ],
expect: true
});
});
_.each(falseExpectedTypes, function(type){
testCases.push({
args: [ type ],
expect: false
});
});
return testCases;
}
var testTargets = [
{
testMethod: 'isWindow',
testCases: getTestCases(['Window'])
},
{
testMethod: 'isElement',
testCases: getTestCases(['DOMElement'])
},
{
testMethod: 'isObject',
testCases: getTestCases(['Object'])
},
{
testMethod: 'isArray',
testCases: getTestCases(['Array'])
},
{
testMethod: 'isFunction',
testCases: getTestCases(['Function'])
},
{
testMethod: 'isString',
testCases: getTestCases(['String', 'EmptyString'])
},
{
testMethod: 'isNumber',
testCases: getTestCases(['Number'])
},
{
testMethod: 'isNodelist',
testCases: getTestCases(['DOMNodelist'])
},
{
testMethod: 'isUndefined',
testCases: getTestCases(['undefined'])
},
{
testMethod: 'isNothing',
testCases: getTestCases(['undefined', 'Null', 'EmptyString'])
},
{
testMethod: 'isDate',
testCases: getTestCases(['Date'])
}
];
_.each(testTargets, function(testTarget){
describe('ax5.util.' + testTarget.testMethod + ' TEST', function() {
_.each(testTarget.testCases, function(testCase){
_.each(testCase.args, function(args){
it('ax5.util.' + testTarget.testMethod + '(' + args.name + ') expect ' + testCase.expect, function() {
var actual = ax5.util[testTarget.testMethod].call(this, args.value);
should.equal(actual, testCase.expect);
});
});
});
});
});
});
describe('ax5.util.isDateFormat TEST', function() {
var testCases = [
{
args: [ '20160101' ],
expect: true
},
{
args: [ '2016-01-01' ],
expect: true
},
{
args: [ '2016/01/01' ],
expect: true
},
{
args: [ '2016*01*01' ],
expect: true
},
{
args: [ '01/01/2016' ],
expect: true
},
{
args: [ '2016010' ],
expect: false
},
{
args: [ '201601011200' ],
expect: true
},
{
args: [ '2016-01-01T12:00' ],
expect: true
},
{
args: [ '2016-01-01T12:00+09:00' ],
expect: true
},
{
args: [ '' ],
expect: false
},
{
args: [ false ],
expect: false
},
{
args: [ null ],
expect: false
},
{
args: [ undefined ],
expect: false
}
];
testCases.forEach(function(testCase){
it('ax5.util.isDateFormat(' + JSON.stringify(testCase.args[0]) + ') expect ' + testCase.expect, function() {
var actual = ax5.util.isDateFormat.apply(this, testCase.args);
actual.should.equal(testCase.expect);
});
});
});
|
JavaScript
| 0.000001 |
@@ -1017,16 +1017,98 @@
window'%0A
+ %7D,%0A %7B%0A args: %5B jQuery %5D,%0A expect: 'function'%0A
|
ee8ac046e4f4331a27f9afdd829cb9ad95a0a3b1
|
Update rule on ajax success
|
src/mist/io/static/js/app/controllers/rules.js
|
src/mist/io/static/js/app/controllers/rules.js
|
define('app/controllers/rules', ['app/models/rule', 'ember'],
//
// Rules Controller
//
// @returns Class
//
function (Rule) {
'use strict';
return Ember.ArrayController.extend(Ember.Evented, {
//
//
// Properties
//
//
content: [],
creationPending: false,
aggregateList: [{
'title': 'any',
'value': 'any'
}, {
'title': 'every',
'value': 'all'
}, {
'title': 'average',
'value': 'avg'
}],
operatorList: [{
'title': 'gt',
'symbol': '>'
}, {
'title': 'lt',
'symbol': '<'
}],
actionList: [
'alert',
'reboot',
'destroy',
'command'
],
//
//
// Initialization
//
//
load: function(rules) {
this._updateContent(rules);
},
//
//
// Methods
//
//
newRule: function (machine, callback) {
var that = this;
this.set('creationPending', true);
Mist.ajax.POST('/rules', {
'backendId': machine.backend.id,
'machineId': machine.id,
'metric': 'load.shortterm',
'operator': 'gt',
'value': 5,
'action': 'alert'
}).success(function (rule) {
that._addRule(rule);
}).error(function (message) {
Mist.notificationController.notify(
'Error while creating rule: ' + message);
}).complete(function (success, data) {
that.set('creationPending', false);
if (callback) callback(success, data);
});
},
deleteRule: function (rule) {
var that = this;
rule.set('pendingAction', true);
Mist.ajax.DELETE('/rules/' + rule.id, {
}).success(function(){
that._deleteRule(rule);
}).error(function(message) {
Mist.notificationController.notify(
'Error while deleting rule: ' + message);
rule.set('pendingAction', false);
});
},
editRule: function (args) {
var payload = {
id: args.rule.id
};
// Construct payload
forIn(args.properties, function (value, property) {
payload[property] = value;
});
args.rule.set('pendingAction', true);
Mist.ajax.POST('/rules',
payload
).error(function(message) {
Mist.notificationController.notify(
'Error while updating rule: ' + message);
}).complete(function (success, data) {
args.rule.set('pendingAction', false);
if (args.callback) args.callback(success, data);
});
},
ruleExists: function (ruleId) {
return !!this.getRuleById(ruleId);
},
getRuleById: function(ruleId) {
return this.content.findBy('id', ruleId);
},
getOperatorByTitle: function(ruleTitle) {
return this.operatorList.findBy('title', ruleTitle);
},
getAggregateByValue: function (aggregateValue) {
return this.aggregateList.findBy('value', aggregateValue);
},
//
//
// Pseudo-Private Methods
//
//
_updateContent: function (rules) {
Ember.run(this, function() {
// Remove deleted rules
this.content.forEach(function (rule) {
if (!rules[rule.id])
this._deleteRule(rule);
}, this);
forIn(this, rules, function (rule, ruleId) {
rule.id = ruleId;
var oldRule = this.getRuleById(ruleId);
if (oldRule)
this._updateRule(oldRule, rule);
else
// Add new rules
this._addRule(rule);
});
this.trigger('onRuleListChange');
});
},
_addRule: function (rule) {
Ember.run(this, function () {
var newRule = Rule.create(rule);
if (this.ruleExists(rule.id)) return;
this.content.addObject(newRule);
this.trigger('onRuleAdd', {
rule: newRule
});
});
},
_updateRule: function (rule, data) {
Ember.run(this, function () {
rule.updateFromRawData(data);
this.trigger('onRuleUpdate', {
rule: rule,
});
});
},
_deleteRule: function (rule) {
Ember.run(this, function () {
this.content.removeObject(rule);
this.trigger('onRuleDelete', {
rule: rule
});
});
},
//
//
// Observers
//
//
creationPendingObserver: function() {
if (this.creationPending)
$('#add-rule-button').addClass('ui-state-disabled');
else
$('#add-rule-button').removeClass('ui-state-disabled');
}.observes('creationPending'),
});
}
);
|
JavaScript
| 0 |
@@ -2979,32 +2979,65 @@
%7D);%0A%0A
+ var that = this;%0A
@@ -3159,16 +3159,116 @@
+).success(function (data) %7B%0A that._updateRule(args.rule, data);%0A %7D
).error(
|
fd20e9fe93bea6e6032d720cec46154d04945e7d
|
add support for http-parser jenkins jobs (#154)
|
scripts/jenkins-status.js
|
scripts/jenkins-status.js
|
'use strict'
const pushJenkinsUpdate = require('../lib/push-jenkins-update')
const enabledRepos = ['citgm', 'node']
const jenkinsIpWhitelist = process.env.JENKINS_WORKER_IPS ? process.env.JENKINS_WORKER_IPS.split(',') : []
function isJenkinsIpWhitelisted (req) {
const ip = req.connection.remoteAddress
if (jenkinsIpWhitelist.length && !jenkinsIpWhitelist.includes(ip)) {
req.log.warn({ ip }, 'Ignoring, not allowed to push Jenkins updates')
return false
}
return true
}
module.exports = function (app) {
app.post('/:repo/jenkins/start', (req, res) => {
const isValid = pushJenkinsUpdate.validate(req.body)
const repo = req.params.repo
if (!isValid) {
return res.status(400).end('Invalid payload')
}
if (!enabledRepos.includes(repo)) {
return res.status(400).end('Invalid repository')
}
if (!isJenkinsIpWhitelisted(req)) {
return res.status(401).end('Invalid Jenkins IP')
}
pushJenkinsUpdate.pushStarted({
owner: 'nodejs',
repo,
logger: req.log
}, req.body)
res.status(201).end()
})
app.post('/:repo/jenkins/end', (req, res) => {
const isValid = pushJenkinsUpdate.validate(req.body)
const repo = req.params.repo
if (!isValid) {
return res.status(400).end('Invalid payload')
}
if (!enabledRepos.includes(repo)) {
return res.status(400).end('Invalid repository')
}
if (!isJenkinsIpWhitelisted(req)) {
return res.status(401).end('Invalid Jenkins IP')
}
pushJenkinsUpdate.pushEnded({
owner: 'nodejs',
repo,
logger: req.log
}, req.body)
res.status(201).end()
})
}
|
JavaScript
| 0 |
@@ -101,16 +101,31 @@
'citgm',
+ 'http-parser',
'node'%5D
|
f19eedbfbe1b7ad6d7d866139ec79863a5ebe0f7
|
fix failing test
|
libs/build_tools/js_handler.js
|
libs/build_tools/js_handler.js
|
// vendor dependencies
var babel = require('gulp-babel')
var sourcemaps = require('gulp-sourcemaps')
// local dependencies
var logger = require(enduro.enduro_path + '/libs/logger')
// * ———————————————————————————————————————————————————————— * //
// * JS Task
// * Transpile ES6 to JS
// * ———————————————————————————————————————————————————————— * //
var js_handler = function () {}
js_handler.prototype.init = function (gulp, browser_sync) {
// stores task name
var js_handler_task_name = 'js';
gulp.task(js_handler_task_name, function() {
if (enduro.config.babel) {
logger.timestamp('JS compiling started', 'enduro_events')
var babelConfig = enduro.config.babel || {
presets: ['es2015']
};
return gulp.src([enduro.project_path + '/assets/js/*.js',
'!' + enduro.project_path + '/assets/js/*.min.js',
'!' + enduro.project_path + '/assets/js/handlebars.js'])
.pipe(sourcemaps.init())
.pipe(babel(babelConfig))
.on('error', function (err) {
logger.err_blockStart('JS error')
logger.err(err.message)
logger.err_blockEnd()
this.emit('end')
})
.pipe(sourcemaps.write())
.pipe(gulp.dest(enduro.project_path + '/' + enduro.config.build_folder + '/assets/js'))
.pipe(browser_sync.stream())
.on('end', () => {
logger.timestamp('JS compiling finished', 'enduro_events')
})
} else {
logger.timestamp('js compiling not enabled, add babel options to enduro.json to enable')
}
})
return js_handler_task_name;
}
module.exports = new js_handler()
|
JavaScript
| 0.000006 |
@@ -98,30 +98,193 @@
s')%0A
-%0A// local dependencies
+var Promise = require('bluebird')%0Avar fs = Promise.promisifyAll(require('fs-extra'))%0A%0A// local dependencies%0Avar flat_helpers = require(enduro.enduro_path + '/libs/flat_db/flat_helpers')
%0Avar
@@ -1624,16 +1624,303 @@
nable')%0A
+%09%09%09var copy_from = enduro.project_path + '/assets/js'%0A%09%09%09var copy_to = enduro.project_path + '/' + enduro.config.build_folder + '/assets/js'%0A%09%09%09return flat_helpers.dir_exists(copy_from)%0A%09%09%09%09.then(() =%3E %7B%0A%09%09%09%09%09return fs.copyAsync(copy_from, copy_to, %7B overwrite: true %7D)%0A%09%09%09%09%7D, () =%3E %7B%7D)%0A
%09%09%7D%0A%09%7D)%0A
|
6482eeb13711744477b7bef5d5a370925fc881c2
|
Update pl_PL.js
|
javascript/lang/pl_PL.js
|
javascript/lang/pl_PL.js
|
if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
console.error('Class ss.i18n not defined');
} else {
ss.i18n.addDictionary('pl_PL', {
'CMSMAIN.WARNINGSAVEPAGESBEFOREADDING' : "Należy najpierw zapisać stronę, aby móc dodać strony podrzędne",
'CMSMAIN.CANTADDCHILDREN' : "Nie można dodać stron podrzędnych",
'CMSMAIN.ERRORADDINGPAGE' : 'Błąd przy dodawaniu strony',
'CMSMAIN.FILTEREDTREE' : 'Drzewo filtrowane pokazujące tylko zmienione strony',
'CMSMAIN.ERRORFILTERPAGES' : 'Nie można było filtrować drzewa<br />%s',
'CMSMAIN.ERRORUNFILTER' : 'Nie można było cofnąć filtrowania drzewa<br />%s',
'CMSMAIN.PUBLISHINGPAGES' : 'Publikacja strony...',
'CMSMAIN.SELECTONEPAGE' : "Proszę wybrać przynajmniej jedną stronę",
'CMSMAIN.ERRORPUBLISHING' : 'Błąd podczas publikacji stron',
'CMSMAIN.REALLYDELETEPAGES' : "Czy na pewno zaznaczone strony %s usunąć?",
'CMSMAIN.DELETINGPAGES' : 'Usuwanie stron...',
'CMSMAIN.ERRORDELETINGPAGES': 'Błąd podczas usuwania stron',
'CMSMAIN.PUBLISHING' : 'Publikacja...',
'CMSMAIN.RESTORING': 'Odzyskiwanie...',
'CMSMAIN.ERRORREVERTING': 'Błąd podczas powrotu do opublikowanej strony',
'CMSMAIN.SAVING' : 'Zapisywanie...'
'CMSMAIN.SELECTMOREPAGES' : "Zaznaczono %s stron.\n\nCzy na pewno chcesz wykonać tę akcje?",
'CMSMAIN.ALERTCLASSNAME': 'Ta strona zostanie zaktualizowana po jej zapisani'ur,
'CMSMAIN.URLSEGMENTVALIDATION': 'Adres URL może składać się tylko z liter, cyfr i łączników.',
'AssetAdmin.BATCHACTIONSDELETECONFIRM': "Czy na pewno usunąć %s folderów?",
'AssetTableField.REALLYDELETE': 'Czy na pewno usunąć zaznaczone pliki??',
'AssetTableField.MOVING': 'Przenoszenie %s plików',
'CMSMAIN.AddSearchCriteria': 'Dodaj kryteria',
'WidgetAreaEditor.TOOMANY': 'Przepraszam, ale osiągnięto maksymalną ilość widgetów w tym obszarze',
'AssetAdmin.ConfirmDelete': 'Czy na pewno usunąć ten folder i wszystkie pliki w nim zawarte?',
'Folder.Name': 'Nazwa folderu',
'Tree.AddSubPage': 'Dodaj tutaj nową stronę',
'Tree.EditPage': 'Edytuj',
'CMSMain.ConfirmRestoreFromLive': "Czy na pewno skopiować opublikowaną treść do strony roboczej?",
'CMSMain.RollbackToVersion': "Czy na pewno cofnąć do wersji #%s tej strony?",
'URLSEGMENT.Edit': 'Edytuj',
'URLSEGMENT.OK': 'OK',
'URLSEGMENT.Cancel': 'Anuluj'
});
}
|
JavaScript
| 0.000003 |
@@ -1193,16 +1193,17 @@
anie...'
+,
%0A%09%09'CMSM
|
6fe39efa6b1dff6134346b4a4274b1dcaee878fe
|
Fix error handling when fetching source
|
scripts/packages/index.js
|
scripts/packages/index.js
|
'use strict';
var Promise = require('bluebird');
var xhr = require('../shared/xhr');
var format = require('../shared/format');
var distributions = ['stable', 'testing', 'unstable', 'experimental'];
var waitDiv = document.querySelector('#wait');
var fileTypeRenderers = {
file: fileRenderer,
folder: folderRenderer
};
try {
var source = pathToSource(window.location.pathname);
(function r() {
findSource(source).spread(function(status, response) {
switch (status) {
case 200:
document.querySelector('#header').addClass('up');
fileTypeRenderers[response.fileType](response.data);
break;
case 202:
setTimeout(r, 1000);
break;
case 404:
throw new Error(
format("The file %s was not found in this package.", source.filename)
);
case 500:
throw new Error('There was a server error. Please try again later.');
}
});
}());
}
catch (e) {
waitDiv.remove();
showError(e.message);
}
function fileRenderer(data) {
}
function folderRenderer(data) {
}
function findSource(source) {
var url = format(
'/api/packages/%s/%s/%s/%s',
source.distribution,
source.name,
source.version,
source.filename
);
return new Promise(function(resolve, request) {
// We're doing the xhr request manually since
// we need the status code
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
resolve([xhr.status, xhr.response]);
};
xhr.responseType = 'json';
xhr.open('GET', url);
xhr.send();
}
function pathToSource(path) {
var parts = path.split('/').filter(Boolean).slice(1);
if (distributions.indexOf(parts[0]) === -1) {
throw new Error(
format("The distribution %s doesn't exist or isn't supported.", parts[0])
);
}
if (parts.length < 3) {
throw new Error("The URL you're trying to reach is too short.");
}
var source = {};
source.distribution = parts[0];
source.name = parts[1];
source.version = parts[2];
source.filename = parts.slice(3).join('/');
return source;
}
function showError(msg) {
var errorDiv = document.querySelector('#error');
errorDiv.textContent = msg;
errorDiv.hidden = false;
}
|
JavaScript
| 0.000009 |
@@ -324,16 +324,28 @@
rer%0A%7D;%0A%0A
+var source;%0A
try %7B%0A
@@ -342,28 +342,24 @@
;%0Atry %7B%0A
-var
source = pat
@@ -395,20 +395,51 @@
hname);%0A
-
+%7D catch(e) %7B%0A catchError(e);%0A%7D%0A%0A
(functio
@@ -442,28 +442,24 @@
ction r() %7B%0A
-
findSour
@@ -513,20 +513,16 @@
-
switch (
@@ -527,28 +527,24 @@
(status) %7B%0A
-
case
@@ -561,20 +561,16 @@
-
document
@@ -607,28 +607,24 @@
lass('up');%0A
-
@@ -684,39 +684,31 @@
-
-
break;%0A
-
case
@@ -725,20 +725,16 @@
-
-
setTimeo
@@ -754,39 +754,31 @@
-
-
break;%0A
-
case
@@ -787,36 +787,32 @@
04:%0A
-
-
throw new Error(
@@ -820,36 +820,32 @@
-
-
format(%22The file
@@ -870,22 +870,21 @@
in this
-packag
+sourc
e.%22, sou
@@ -905,28 +905,24 @@
-
-
);%0A
@@ -924,26 +924,17 @@
- case 500:%0A
+default:%0A
@@ -1023,44 +1023,94 @@
+%7D%0A
%7D
-%0A %7D
+).catch(function(e) %7B%0A catchError(e
);%0A
+%7D);%0A
%7D());%0A
-%7D%0Acatch
+%0Afunction catchError
(e)
@@ -1876,16 +1876,24 @@
send();%0A
+ %7D);%0A
%7D%0A%0Afunct
|
4f5f142007f806988cb9be60cfb59783cf2a5bde
|
Add now navigates to Lists page
|
client-src/js/components/list-edit-component.js
|
client-src/js/components/list-edit-component.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {
e.preventDefault();
console.log("saveClickHandler", this);
this.props.addNewList(this.state.listName);
}
cancelClickHandler(e) {
e.preventDefault();
console.log("cancelClickHandler");
}
render() {
//console.log('edit List', props);
let screenTitle = this.props.params.listId ? "Edit List" : "Add new List";
return (
<div>
<h3>{screenTitle}</h3>
<input type="text"
placeholder="Name of List"
onChange={event => this.setState({listName: event.target.value})}
/>
<div className="footer">
<a onClick={this.cancelClickHandler.bind(this)} href="#">Cancel</a>
<a onClick={this.saveClickHandler.bind(this)} href="#">Save</a>
</div>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
"use strict";
return bindActionCreators({addNewList}, dispatch);
}
export default connect(null, mapDispatchToProps)(ListEdit);
|
JavaScript
| 0 |
@@ -441,16 +441,54 @@
tName);%0A
+ this.props.history.push('/');%0A
%7D%0A%0A
|
49b9239d7c570460772c1e8b43b93c619bbb569e
|
add semicolon
|
pocky/index.test.js
|
pocky/index.test.js
|
/* eslint-env node, jest */
jest.mock('axios');
jest.mock('../achievements');
jest.mock('../lib/slackUtils')
const axios = require('axios');
const pocky = require('./index.js');
const Slack = require('../lib/slackMock.js');
let slack = null;
beforeEach(() => {
slack = new Slack();
process.env.CHANNEL_SANDBOX = slack.fakeChannel;
pocky(slack);
});
describe('pocky', () => {
it('responds to "ほげ?"', async () => {
axios.response = {data: [null, ['ほげ ふが']]}
const {username, text} = await slack.getResponseTo('ほげ?');
expect(username).toBe('pocky');
expect(text).toBe('ふが');
});
});
|
JavaScript
| 0.998846 |
@@ -102,16 +102,17 @@
kUtils')
+;
%0A%0Aconst
|
0b05b61d974192dd786ff8377dd88214791af4ac
|
Update core.js
|
src/modula/core.js
|
src/modula/core.js
|
/**
* @project : modula.js
* @package : core
* @internal : modula.core
* @type : object
* @dependencies : none
*
* @description :
* the modula.core is the object used when NO selector is given to the modula.js
* here in are only the basic functions available
*/
/**
* define modula.core and it's prototype
*/
modula.core = {
version : version,
constructor : modula,
uid : 'modula.js' + 1 * Date.now(),
extend : Propertizer( "extend" ),
};
var
core = modula.core.prototype = {};
/**
* define init for modula.core
*/
var
coreinit = modula.core.init = function() {};
/**
* bind prototype for further usage
*/
coreinit.prototype = modula.core;
|
JavaScript
| 0.000001 |
@@ -451,17 +451,43 @@
er(
-%22
+'
extend
-%22
+' ),%0A%0A%09%09task : tasks.create(
),%0A%0A
|
4d215e542cbce6a96a88f17a19808a56fd0bf151
|
introduce the list.delete() function
|
app/transactions.js
|
app/transactions.js
|
"use strict";
var _ = require('lodash'),
redis = require('redis'),
when = require('when'),
moment = require('moment'),
url = require('url'),
redisClient, redisURL;
if (process.env.NODE_ENV === 'production') {
redisURL = url.parse(process.env.REDISCLOUD_URL);
redisClient = redis.createClient(redisURL.port, redisURL.hostname, {no_ready_check: true});
redisClient.auth(redisURL.auth.split(":")[1]);
} else {
redisClient = redis.createClient();
}
/**
* Class to represent a single transaction
*/
function Transaction(obj, client) {
this.client = client || redisClient;
this.key = (obj) ? obj.key : null;
this.date = (obj) ? obj.date : null;
this.time = (obj) ? obj.time : null;
this.name = (obj) ? obj.name : null;
this.amount = (obj) ? obj.amount : null;
}
Transaction.prototype.save = function() {
if (_.any([this.time, this.date, this.amount, this.name], function (item) {
return _.isNull(item);
})) {
return when.reject(new Error('Transaction fields must be set before saving.'));
}
var promise, multi = this.client.multi(),
week = 'w' + moment().isoWeek();
promise = when.promise(function (resolve, reject) {
this.client.incr('tkey', function (err, reply) {
if (err || (reply === null)) reject(new Error('No trans key?'));
this.key = reply;
multi.hmset(this.key, {
key: this.key,
date: this.date,
time: this.time,
name: this.name,
amount: this.amount
});
multi.rpush(week, this.key);
multi.exec(function (err, replies) {
console.log(replies);
if (err) {
console.log('save trans ' + this.key + ': FAIL');
reject(new Error(err));
return false;
}
console.log('save trans ' + this.key + ': SUCCESS');
resolve(replies);
return true;
}.bind(this));
}.bind(this));
}.bind(this));
return promise;
}
Transaction.prototype.set = function (obj) {
this.date = obj.date;
this.time = obj.time;
this.name = obj.name;
this.amount = obj.amount;
}
/**
* Class to facilitate the representation of many transactions
*/
function TransactionList(client) {
this.client = client || redisClient;
this.key = null;
this.transactions = [];
}
TransactionList.prototype.sum = function () {
var promise, sum = 0;
promise = when.promise(function (resolve, reject) {
_.forEach(this.transactions, function (trans) {
sum += +trans.amount;
});
resolve(sum);
}.bind(this));
return promise;
}
TransactionList.prototype.save = function () {
var promise, actions = [];
promise = when.promise(function (resolve, reject) {
_.forEach(this.transactions, function (trans) {
actions.push(trans.save());
});
when.all(actions)
.then(resolve)
.catch(reject);
}.bind(this));
return promise;
}
TransactionList.prototype.fetch = function (week) {
var promise, actions = [];
this.transactions = [];
promise = when.promise(function (resolve, reject) {
this.client.lrange(week, 0, -1, function (err, replies) {
if (err) {
console.log(err);
reject(err);
}
if (_.isEmpty(replies)) {
resolve(false);
}
_.forEach(replies, (function (reply) {
actions.push(when.promise(function (resolve, reject) {
this.client.hgetall(reply, function (err, reply) {
if (err) reject(err);
this.transactions.push(new Transaction(reply));
resolve(true);
}.bind(this));
}.bind(this)));
}.bind(this)));
when.all(actions)
.then(function () {
resolve(true);
});
}.bind(this));
}.bind(this));
return promise;
}
TransactionList.prototype.delete = function (week) {
console.log('attemping delete of ' + week);
return this.fetch(week)
.then(function () {
return when.promise(function (resolve, reject) {
_.forEach(this.transactions, function (transaction) {
this.client.del(transaction.key, function (err, reply) {
if (err) {
reject(err);
return;
}
console.log('del trans ' + transaction.key + ': SUCCESS');
resolve(true);
});
}.bind(this));
this.client.del('w' + week);
}.bind(this));
}.bind(this))
.catch(function (err) {
// grace
});
}
module.exports = {
list: TransactionList,
item: Transaction,
client: redisClient
};
|
JavaScript
| 0.000179 |
@@ -3833,16 +3833,17 @@
week);%0A
+%0A
return
|
25a5360b6be790484a8d0f09a51da1f5140ca0c4
|
fix whitespace cut
|
lib/build/css/validateNames.js
|
lib/build/css/validateNames.js
|
(module.exports = function(flow){
var fconsole = flow.console;
var idMap = flow.css.idMap;
var classMap = flow.css.classMap;
var warnCount = 0;
//
// warnings
//
var warnNoStyle = [];
var warnNoHtml = [];
for (var name in classMap)
{
var list = classMap[name];
var inHtml = list.sources.html || list.sources.tmpl;
var inCss = list.sources.style;
if (inHtml && !inCss)
warnNoStyle.push('class: ' + name);
if (!inHtml && inCss)
{
warnNoHtml.push('class: ' + name);
if (flow.options.cssCutUnused)
for (var i = 0, item; item = list[i]; i++)
if (item.type == 'style-class')
deleteSelector(item.token);
}
}
for (var name in idMap)
{
var list = idMap[name];
var inHtml = list.sources.html || list.sources.tmpl;
var inCss = list.sources.style;
if (inHtml && !inCss)
warnNoStyle.push('id: ' + name);
if (!inHtml && inCss)
{
warnNoHtml.push('id: ' + name);
if (flow.options.cssCutUnused)
for (var i = 0, item; item = list[i]; i++)
if (item.type == 'style-id')
deleteSelector(item.token);
}
}
if (warnNoHtml.length)
{
fconsole.log('[!] Never used in html & templates');
fconsole.list(warnNoHtml, ' ');
fconsole.log();
}
if (warnNoStyle.length)
{
fconsole.log('[!] No styles for');
fconsole.list(warnNoStyle, ' ');
fconsole.log();
}
if (warnCount)
fconsole.log('[WARN] ' + warnCount + ' problem(s) detected, name optimizing may breakdown app\n');
}).handlerName = '[css] Validate names';
function deleteSelector(token){
var simpleselector = token.stack[0];
var selector = token.stack[1];
var rule = token.stack[2];
var stylesheet = token.stack[3];
var idx;
idx = selector.indexOf(simpleselector);
if (idx != -1)
{
// delete simple selector from selector
selector.splice(idx > 2 ? idx - 1 : idx, 2);
}
if (selector.length == 2)
{ // no more simple selectors
idx = stylesheet.indexOf(rule);
if (idx != -1)
{
// delete rule from stylesheet
stylesheet.splice(idx, 1);
if (stylesheet[idx][1] == 's')
stylesheet.splice(idx, 1);
}
}
}
|
JavaScript
| 0.028978 |
@@ -2164,16 +2164,35 @@
eet%5Bidx%5D
+ && stylesheet%5Bidx%5D
%5B1%5D == '
|
20baf5ee9f48c99653f0d801c858f951adbcaba2
|
call path.join once and store in fspath var
|
lib/cmds/template_generator.js
|
lib/cmds/template_generator.js
|
var fs = require('../core/fs.js');
var path = require('path');
var utils = require('../utils/utils.js');
var TemplateGenerator = function(templateName) {
this.templateName = templateName;
};
TemplateGenerator.prototype.generate = function(destinationFolder, name) {
var templatePath = fs.embarkPath(this.templateName);
console.log('Initializing Embark Template....'.green);
fs.copySync(templatePath, path.join(destinationFolder, name));
utils.cd(path.join(destinationFolder, name));
utils.sed('package.json', '%APP_NAME%', name);
console.log('Installing packages.. this can take a few seconds'.green);
utils.runCmd('npm install');
console.log('Init complete'.green);
console.log('\nApp ready at '.green + path.join(destinationFolder, name));
if (name === 'embark_demo') {
console.log('-------------------'.yellow);
console.log('Next steps:'.green);
console.log(('-> ' + ('cd ' + path.join(destinationFolder, name)).bold.cyan).green);
console.log('-> '.green + 'embark blockchain'.bold.cyan + ' or '.green + 'embark simulator'.bold.cyan);
console.log('open another console in the same directory and run'.green);
console.log('-> '.green + 'embark run'.bold.cyan);
console.log('For more info go to http://github.com/iurimatias/embark-framework'.green);
}
};
module.exports = TemplateGenerator;
|
JavaScript
| 0 |
@@ -379,36 +379,22 @@
n);%0A
-%0A
-fs.copySync(templatePath,
+var fspath =
pat
@@ -428,56 +428,65 @@
ame)
-)
;
+%0A
%0A
-utils.cd(path.join(destinationFolder, name)
+fs.copySync(templatePath, fspath);%0A utils.cd(fspath
);%0A
@@ -721,42 +721,14 @@
n +
+fs
path
-.join(destinationFolder, name)
);%0A%0A
@@ -882,42 +882,14 @@
' +
+fs
path
-.join(destinationFolder, name)
).bo
|
fe0de38d3a247ca30315dc25179fe2227f3da91d
|
save jsreport package dependency in package.json when installing it
|
lib/commands/_initializeApp.js
|
lib/commands/_initializeApp.js
|
'use strict'
var path = require('path')
var fs = require('fs')
var Promise = require('bluebird')
var install = require('npm-install-package')
function initializeApp (cwd, force) {
return new Promise(function (resolve, reject) {
var existsPackageJson = fs.existsSync(path.join(cwd, './package.json'))
var jsreportModule
var jsreportVersion
var isMainJsreport = false
checkOrInstallJsreport(cwd, existsPackageJson, function (err, detectedJsreport) {
var errorToReject
if (err) {
errorToReject = new Error('Unexpected error happened')
errorToReject.originalError = err
return reject(errorToReject)
}
isMainJsreport = (detectedJsreport === 'jsreport')
try {
jsreportModule = require(path.join(cwd, 'node_modules/' + detectedJsreport + '/package.json'))
jsreportVersion = jsreportModule.version
} catch (err) {
errorToReject = new Error('Unexpected error happened')
errorToReject.originalError = err
return reject(errorToReject)
}
if (!fs.existsSync(path.join(cwd, './server.js')) || force) {
console.log('Creating server.js')
fs.writeFileSync(
path.join(cwd, './server.js'),
fs.readFileSync(
path.join(__dirname, '../../example.server.js')
).toString().replace('$moduleName$', detectedJsreport)
)
}
if (!existsPackageJson || force) {
console.log('Creating package.json')
var serverPackageJson = {
'name': 'jsreport-server',
'main': 'server.js',
'scripts': {
'start': 'node server'
},
'jsreport': {
'entryPoint': 'server.js'
},
'dependencies': {
}
}
serverPackageJson.dependencies[detectedJsreport] = jsreportVersion
if (isMainJsreport) {
serverPackageJson.scripts.jsreport = 'jsreport'
}
fs.writeFileSync(path.join(cwd, './package.json'), JSON.stringify(serverPackageJson, null, 2))
}
if ((!fs.existsSync(path.join(cwd, './prod.config.json')) || force) && isMainJsreport) {
console.log('Creating prod.config.json (applied on npm start --production)')
fs.writeFileSync(path.join(cwd, './prod.config.json'), fs.readFileSync(path.join(__dirname, '../../example.config.json')))
console.log('Creating dev.config.json (applied on npm start)')
fs.writeFileSync(path.join(cwd, './dev.config.json'), fs.readFileSync(path.join(__dirname, '../../example.config.json')))
}
console.log('Initialized')
resolve({
name: detectedJsreport,
version: jsreportVersion
})
})
})
}
function checkOrInstallJsreport (cwd, existsPackageJson, cb) {
var detectedJsreport
var userPkg
var userDependencies
var originalCWD = process.cwd()
if (existsPackageJson) {
userPkg = require(path.join(cwd, './package.json'))
userDependencies = userPkg.dependencies || {}
if (userDependencies['jsreport']) {
detectedJsreport = 'jsreport'
} else if (userDependencies['jsreport-core']) {
detectedJsreport = 'jsreport-core'
}
}
if (!detectedJsreport) {
if (fs.existsSync(path.join(cwd, 'node_modules/jsreport'))) {
detectedJsreport = 'jsreport'
} else if (fs.existsSync(path.join(cwd, 'node_modules/jsreport-core'))) {
detectedJsreport = 'jsreport-core'
}
}
if (!detectedJsreport) {
console.log('jsreport installation not found, intalling it now, wait a moment...')
detectedJsreport = 'jsreport'
process.chdir(cwd)
// creating basic package.json in order to make npm install
// work normally in current directory, later the real package.json
// will be created
if (!existsPackageJson) {
fs.writeFileSync(
path.join(cwd, './package.json'),
JSON.stringify({
name: 'jsreport-server'
}, null, 2))
}
install(detectedJsreport, function (installErr) {
process.chdir(originalCWD)
if (installErr) {
return cb(installErr)
}
console.log('jsreport installation finished..')
cb(null, detectedJsreport)
})
} else {
cb(null, detectedJsreport)
}
}
module.exports = initializeApp
|
JavaScript
| 0 |
@@ -4010,16 +4010,32 @@
sreport,
+ %7B save: true %7D,
functio
|
ecff36279f4331136346c56dccfa18a92732c3b1
|
move fields pushing to inForm
|
lib/components/mixins/ready.js
|
lib/components/mixins/ready.js
|
var isEqual = require('../../helpers/is-equal');
module.exports = {
ready: function() {
var inForm = this.inForm();
if (!this.$parent.options.sendOnlyDirtyFields)
this.$parent.fields.push(this);
if (inForm) {
if (this.$parent.options.sendOnlyDirtyFields) {
this.$watch('dirty', function(isDirty) {
var method = isDirty?'push':'$remove';
this.$parent.fields[method](this);
});
}
var form = this.$parent;
var v = this.$parent.validation;
if (v.rules && v.rules.hasOwnProperty(this.name))
this.rules = v.rules[this.name];
if (typeof v.messages!='undefined' && v.messages.hasOwnProperty(this.name))
this.messages = v.messages[this.name];
this.validate();
if (form.relatedFields.hasOwnProperty(this.name))
var foreignField = form.getField(form.relatedFields[this.name]);
}
this.$watch('value', function(newVal, oldVal) {
this.$dispatch('vue-formular.change::' + this.name, {value:newVal, oldValue:oldVal});
if (typeof foreignField!='undefined') {
foreignField.validate();
}
this.dirty = !isEqual(this.value,this.initialValue);
this.pristine = false;
if (inForm) {
this.validate();
}
},{deep:true});
}
}
|
JavaScript
| 0 |
@@ -114,24 +114,45 @@
.inForm();%0A%0A
+ if (inForm) %7B%0A%0A
if (!thi
@@ -229,35 +229,16 @@
this);%0A%0A
- if (inForm) %7B%0A%0A
if
|
da0131fd6156831add9b048b0a15d0e77660b8d0
|
Create separator for objects rendered by console.log
|
lib/console/console-message.js
|
lib/console/console-message.js
|
/* See license.txt for terms of usage */
"use strict";
var main = require("../main.js");
const { Cu } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js");
const { Domplate } = require("../core/domplate.js");
const { Dom } = require("../core/dom.js");
const { Events } = require("../core/events.js");
const { Reps } = require("../reps/reps.js");
// API for custom console messages
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const consoleOutputPath = "devtools/webconsole/console-output";
const { Messages, Widgets } = devtools.require(consoleOutputPath);
const ConsoleGeneric = Messages.ConsoleGeneric;
const Heritage = require("sdk/core/heritage");
// Devtools API
const utilsPath = "devtools/toolkit/webconsole/utils";
let WebConsoleUtils = devtools.require(utilsPath).Utils;
// Domplate
const { SPAN, A, domplate } = Domplate;
/**
* TODO: description
* @param msg {JSON} The packet received from the back-end.
*/
function ConsoleMessage(msg) {
Messages.ConsoleGeneric.call(this, msg);
this.message = msg;
};
ConsoleMessage.prototype = Heritage.extend(ConsoleGeneric.prototype,
/** @lends ConsoleMessage */
{
// Render console message using registered reps.
render: function() {
let render = ConsoleGeneric.prototype.render.bind(this);
let element = render().element;
let parentNode = element.querySelector(".message-body");
Dom.clearNode(parentNode);
let args = this.message.arguments;
for (let i = 0; i < args.length; i++) {
let grip = args[i];
this.appendObject(args[i], parentNode);
}
return this;
},
appendObject: function(object, parentNode) {
try {
let rep = Reps.getRep(object, this.context);
// xxxHonza: Hack until we get IF support in domplate
// (or bug 116083 gets fixed).
let tag = rep.tag;
if (rep === Reps.Text)
tag = rep.getWhitespaceCorrectedTag(object);
let node = tag.append({object: object}, parentNode, rep);
// xxxHonza: hack FIX ME, the listener must be registered
// by {@Chrome} for all panel contents.
node.addEventListener("click", (event) => {
this.output.openVariablesView({
label: "",
objectActor: Reps.getRepObject(event.target),
autofocus: true,
});
}, true);
return node;
}
catch (e) {
TraceError.sysout("consoleMessage.appendObject; EXCEPTION " + e, e);
}
}
});
function logConsoleAPIMessage(aMessage) {
Trace.sysout("logConsoleAPIMessage ", this);
let body = null;
let clipboardText = null;
let sourceURL = aMessage.filename;
let sourceLine = aMessage.lineNumber;
let level = aMessage.level;
let args = aMessage.arguments;
let objectActors = new Set();
let node = null;
// Gather the actor IDs.
args.forEach((aValue) => {
if (WebConsoleUtils.isActorGrip(aValue)) {
objectActors.add(aValue.actor);
}
});
let msg = new ConsoleMessage(aMessage);
node = msg.init(this.output).render().element;
if (objectActors.size > 0) {
node._objectActors = objectActors;
if (!node._messageObject) {
let repeatNode = node.getElementsByClassName("message-repeats")[0];
repeatNode._uid += [...objectActors].join("-");
}
}
return node;
}
exports.ConsoleMessage = ConsoleMessage;
exports.logConsoleAPIMessage = logConsoleAPIMessage;
|
JavaScript
| 0 |
@@ -1602,24 +1602,64 @@
arentNode);%0A
+ this.appendSeparator(parentNode);%0A
%7D%0A%0A r
@@ -2508,24 +2508,136 @@
, e);%0A %7D%0A
+ %7D,%0A%0A appendSeparator: function(parentNode) %7B%0A let tag = SPAN(%22 %22);%0A return tag.append(%7B%7D, parentNode);%0A
%7D%0A%7D);%0A%0Afun
|
737d2a4c9c362bf206f4c9f410d1c3e53edf00ff
|
fix validateRecord
|
lib/dataTier/flow/flowModel.js
|
lib/dataTier/flow/flowModel.js
|
/*jshint node: true, -W106 */
'use strict';
/*
* Name : graphModel.js
* Module : Lib::DataTier::FlowModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version Date Programmer Description
* =========================================================
* 0.0.1 2015-05-14 Filippo Rampado Initial code
* =========================================================
*/
var FilterModel = require('./filterModel.js');
var Helper = require('../../helpers/functionHelper.js');
function FlowModel(params) {
if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
console.log('Error: 251');
return;
}
this._ID=params.ID;
this._name='';
this._type='';
this._filters=null;
this._records=[];
if(typeof params.type === 'string' && (params.type==='BarChartFlow' || params.type==='LineChartFlow' || params.type==='MapChartFlow' || params.type==='TableFlow')){
this._type=params.type;
}
this.updateProperties(params);
}
FlowModel.prototype.generateNorrisRecordID = function(number){
var date = new Date();
if (number !== undefined && typeof number === 'number'){
return this._ID.concat(date.getTime()).concat(number);
}
return this._ID.concat(date.getTime()).concat(0);
};
FlowModel.prototype.getProperties = function(){
var f=null;
if (this._filters!==null){
f=this._filters.getFilterText();
}
return {
ID: this._ID,
name: this._name,
filters: f
};
};
FlowModel.prototype.getData = function(){
var flowData=[];
var records= this._records.length;
for(var i=0; i<records; i++){
flowData[i]=this._records[i];
}//for records
return flowData;
};
FlowModel.prototype.validateData = function(){
if (this._filters !== null){
var records= this._records.length;
for (var i=0; i<records; i++){
this.validateRecord(i);
}
}
};
FlowModel.prototype.validateRecord = function(index){
if (this._filters !== null && typeof index === 'number' && index>=0 && index<this._records.length){
if (this._filters.validateRecord(this._records[index]) === true){
this._records[index].norrisRecordIsValid = true;
}
if (this._filters.validateRecord(this._records[index]) === false){
this._records[index].norrisRecordIsValid = false;
}
}
};
FlowModel.prototype.updateProperties = function(params) {
if (params !== undefined){
//ID field can't be modified
var prop={};
if(params.name!==undefined && typeof params.name === 'string'){
this._name=prop.name=params.name;
}
if(typeof params.filters === 'string'){
var filter=new FilterModel(params.filters);
if (filter.hasOwnProperty('_filterText')){ //valid FilterModel
this._filters = filter;
prop.filters=params.filters;
this.validateData();
}
}
return prop;
}
return 252;
};
FlowModel.prototype.converter = function(record, key, format) {
return Helper.converter(record,key,format);
};
module.exports = FlowModel;
|
JavaScript
| 0.000002 |
@@ -1921,16 +1921,100 @@
index)%7B%0A
+%09if (this._filters === null)%7B%0A%09%09this._records%5Bindex%5D.norrisRecordIsValid = true;%0A%09%7D%0A
%09if (thi
@@ -2361,20 +2361,16 @@
%09%7D%0A%09%7D%0A%7D;
-
%0A%0AFlowMo
|
1ebedf51333b03034bd7818744473be7dd354399
|
Update page-manipulation.js
|
src/page-manipulation.js
|
src/page-manipulation.js
|
(function($){
$(".layout__slot:nth-child(1)").attr("id","calendar-list");
$(".layout__slot:nth-child(2)").attr("id","app-list");
$(".layout__slot:nth-child(3)").attr("id","activity-list");
$(".layout__slot:nth-child(4)").attr("id","tweets-list");
$(".layout__slot:nth-child(4)").attr("id","tweets-list");
var appList = $("app-list")
appList.prependTo(appList.parent())
appList.removeClass();
})(jQuery)
|
JavaScript
| 0.000001 |
@@ -331,16 +331,17 @@
st = $(%22
+#
app-list
|
4160dc89ba2e5a8efc1b081882bff67884670c54
|
Fix minor error.
|
src/net/scripts.js
|
src/net/scripts.js
|
// Copyright 2012 Google Inc. All Rights Reserved.
/**
* @fileoverview Functions for dynamically loading scripts without blocking.
* By nesting multiple calls in callback parameters, execution order of
* the scripts can be preserved as well.
*
* Single script example:
* spf.net.scripts.load(url, function() {
* doSomethingAfterOneScriptIsLoaded();
* });
*
* Multiple script example, preserving execution order of the scripts:
* spf.net.scripts.load(url1, function() {
* spf.net.scripts.load(url2, function() {
* doSomethingAfterTwoScriptsAreLoadedInOrder();
* });
* });
*
* @author [email protected] (Alex Nicksay)
*/
goog.provide('spf.net.scripts');
goog.require('spf.dom.dataset');
goog.require('spf.pubsub');
goog.require('spf.string');
/**
* Evaluates a script text by dynamically creating an element and appending it
* to the document. A callback can be specified to execute once the script
* has been loaded.
*
* @param {string} text The text of the script.
* @param {Function=} opt_callback Callback function to execute when the
* script is loaded.
*/
spf.net.scripts.eval = function(text, opt_callback) {
if (window.execScript) {
window.execScript(text, 'JavaScript');
} else {
var scriptEl = document.createElement('script');
scriptEl.appendChild(document.createTextNode(text));
// Place the scripts in the head instead of the body to avoid errors when
// called from the head in the first place.
var head = document.getElementsByTagName('head')[0];
// Use insertBefore instead of appendChild to avoid errors with loading
// multiple scripts at once in IE.
head.insertBefore(scriptEl, head.firstChild);
}
if (opt_callback) {
opt_callback();
}
};
/**
* Loads a script URL by dynamically creating an element and appending it to
* the document. A callback can be specified to execute once the script
* has been loaded. Subsequent calls to load the same URL will not
* reload the script.
*
* @param {string} url Url of the script.
* @param {Function=} opt_callback Callback function to execute when the
* script is loaded.
* @return {Element} The dynamically created script element.
*/
spf.net.scripts.load = function(url, opt_callback) {
var id = spf.net.scripts.ID_PREFIX + spf.string.hashCode(url);
var scriptEl = document.getElementById(id);
var isLoaded = scriptEl && spf.dom.dataset.get(scriptEl, 'loaded');
var isLoading = scriptEl && !isLoaded;
// If the script is already loaded, execute the callback(s) immediately.
if (isLoaded) {
if (opt_callback) {
opt_callback();
}
return scriptEl;
}
// Register the callback.
if (opt_callback) {
spf.pubsub.subscribe(id, opt_callback);
}
// If the script is currently loading, wait.
if (isLoading) {
return scriptEl;
}
// Otherwise, the script needs to be loaded.
// Lexical closures allow this trickiness with the "el" variable.
var el = spf.net.scripts.load_(url, id, function() {
if (!spf.dom.dataset.get(el, 'loaded')) {
spf.dom.dataset.set(el, 'loaded', 'true');
spf.pubsub.publish(id);
spf.pubsub.clear(id);
}
});
return el;
};
/**
* See {@link #load}.
*
* @param {string} url Url of the script.
* @param {string} id Id of the script element.
* @param {Function} fn Callback for when the script has loaded.
* @return {Element} The dynamically created script element.
* @private
*/
spf.net.scripts.load_ = function(url, id, fn) {
var scriptEl = document.createElement('script');
scriptEl.id = id;
// Safari/Chrome and Firefox support the onload event for scripts.
scriptEl.onload = fn;
// IE supports the onreadystatechange event; have it call the onload
// handler when appropriate.
scriptEl.onreadystatechange = function() {
switch (scriptEl.readyState) {
case 'loaded':
case 'complete':
scriptEl.onload();
}
};
// Set the onload and onreadystatechange handlers before setting the src
// to avoid potential IE bug where handlers are not called.
scriptEl.src = url;
// Place the scripts in the head instead of the body to avoid errors when
// called from the head in the first place.
var head = document.getElementsByTagName('head')[0];
// Use insertBefore instead of appendChild to avoid errors with loading
// multiple scripts at once in IE.
head.insertBefore(scriptEl, head.firstChild);
return scriptEl;
};
/**
* "Unloads" a script URL by finding a previously created element and
* removing it from the document. This will allow a URL to be loaded again
* if needed. Calling unload will stop execution of a pending callback, but
* will not stop loading a pending script.
*
* @param {string} url Url of the script.
*/
spf.net.scripts.unload = function(url) {
var id = spf.net.scripts.ID_PREFIX + spf.string.hashCode(url);
var scriptEl = document.getElementById(id);
if (scriptEl) {
spf.pubsub.clear(id);
scriptEl.parentNode.removeChild(scriptEl);
}
};
/**
* Parses scripts from an HTML string and executes them in the current
* document.
*
* @param {string} html The complete HTML content to use as a source for
* updates.
* @param {Function=} opt_callback Callback function to execute after
* all scripts are loaded.
*/
spf.net.scripts.execute = function(html, opt_callback) {
if (!html) {
return;
}
var queue = [];
// Extract the scripts.
html = html.replace(spf.net.scripts.SCRIPT_TAG_REGEXP,
function(fullMatch, attr, text) {
var url = attr.match(spf.net.scripts.SRC_ATTR_REGEXP);
if (url) {
queue.push([url[1], true]);
} else {
queue.push([text, false]);
}
return '';
});
// Load or evaluate the scripts in order.
var getNextScript = function() {
if (queue.length > 0) {
var pair = queue.shift();
var script = pair[0];
var isUrl = pair[1];
if (isUrl) {
spf.net.scripts.load(script, getNextScript);
} else {
spf.net.scripts.eval(script, getNextScript);
}
} else {
if (opt_callback) {
opt_callback();
}
}
};
getNextScript();
};
/**
* @type {string} The ID prefix for dynamically created script elements.
* @const
*/
spf.net.scripts.ID_PREFIX = 'js-';
/**
* Regular expression used to locate script tags in a string.
* See {@link #execute}.
*
* @type {RegExp}
* @const
*/
spf.net.scripts.SCRIPT_TAG_REGEXP =
/\x3cscript([\s\S]*?)\x3e([\s\S]*?)\x3c\/script\x3e/ig;
/**
* Regular expression used to locate src attributes in a string.
* See {@link #execute}.
*
* @type {RegExp}
* @const
*/
spf.net.scripts.SRC_ATTR_REGEXP = /src="([\S]+)"/;
|
JavaScript
| 0.000003 |
@@ -3910,16 +3910,20 @@
.onload(
+null
);%0A %7D
|
6a1f598be09a9eb8117f3ba02ab4071e9d2a0955
|
Update strings.js
|
src/nls/strings.js
|
src/nls/strings.js
|
define(function (require, exports, module) {
"use strict";
module.exports = {
root: true,
it: true
};
});
|
JavaScript
| 0.000002 |
@@ -111,16 +111,34 @@
it:
+ true,%0A de:
true%0A
|
93c6c0b1e78160a82c1dec746eaaf87c318315a5
|
test wrong values
|
src/options.spec.js
|
src/options.spec.js
|
import test from 'tape'
import ChunkifyOptions from './options'
test('should throw when receiving non-object literal options', t => {
let WRONG_TYPES = [
false,
true,
null,
undefined,
[],
function() {}
];
for (let thing of WRONG_TYPES) {
t.throws(() => {
ChunkifyOptions.of(thing)
}, new RegExp(`Expected options object, got ${typeof thing}`))
}
t.end()
});
test('should have defaults', t => {
let options = ChunkifyOptions.of({});
t.equals(typeof options.delay, 'number');
t.equals(typeof options.chunk, 'number');
t.end()
});
test('should override all defaults', t => {
let chunk = 50;
let delay = 100;
let options = ChunkifyOptions.of({chunk, delay});
t.equals(options.chunk, chunk);
t.equals(options.delay, delay);
t.end()
});
test('should override some defaults', t => {
let chunk = 50;
let delay = 100;
let options = ChunkifyOptions.of({chunk});
t.equals(options.chunk, chunk);
t.notEquals(options.delay, delay);
options = ChunkifyOptions.of({delay});
t.equals(options.delay, delay);
t.notEquals(options.chunk, chunk);
t.end()
});
test('should throw when an option override has the wrong type', t => {
let chunk = function() {};
let delay = [];
t.throws(() => {
ChunkifyOptions.of({chunk})
}, /Expected 'chunk' to be 'number', got 'function'/);
t.throws(() => {
ChunkifyOptions.of({delay})
}, /Expected 'delay' to be 'number', got 'object'/);
t.end()
});
test('should be immutable', t => {
let chunk = 50;
let delay = 100;
let options = ChunkifyOptions.of({chunk, delay});
t.throws(() => {
options.delay = 0
}, /delay is immutable/);
t.throws(() => {
options.chunk = 1
}, /chunk is immutable/);
delete options.delay;
delete options.chunk;
t.ok(options.delay);
t.ok(options.chunk);
t.end()
});
|
JavaScript
| 0.000064 |
@@ -1309,55 +1309,374 @@
%7D, /
-Expected 'chunk' to be 'number', got 'function'
+'chunk' should be a positive number/);%0A t.throws(() =%3E %7B%0A ChunkifyOptions.of(%7Bdelay%7D)%0A %7D, /'delay' should be a non-negative number/);%0A t.end()%0A%7D);%0A%0Atest('should throw when an option override has the wrong value', t =%3E %7B%0A let chunk = function() %7B%7D;%0A let delay = %5B%5D;%0A%0A t.throws(() =%3E %7B%0A ChunkifyOptions.of(%7Bchunk%7D)%0A %7D, /'chunk' should be a positive number
/);%0A
@@ -1736,53 +1736,47 @@
%7D, /
-Expected 'delay' to be 'number', got 'object'
+'delay' should be a non-negative number
/);%0A
|
93713aabea145b5521ed7e27b88781e1f7a5297a
|
add export default
|
src/num2persian.js
|
src/num2persian.js
|
/**
*
* @type {string}
*/
const Delimiter = ' و ';
/**
*
* @type {string}
*/
const Zero = 'صفر';
/**
*
* @type {*[]}
*/
const Letters = [
['', 'یک', 'دو', 'سه', 'چهار', 'پنج', 'شش', 'هفت', 'هشت', 'نه'],
['ده', 'یازده', 'دوازده', 'سیزده', 'چهارده', 'پانزده', 'شانزده', 'هفده', 'هجده', 'نوزده', 'بیست'],
['', '', 'بیست', 'سی', 'چهل', 'پنجاه', 'شصت', 'هفتاد', 'هشتاد', 'نود'],
['', 'یکصد', 'دویست', 'سیصد', 'چهارصد', 'پانصد', 'ششصد', 'هفتصد', 'هشتصد', 'نهصد'],
['', ' هزار', ' میلیون', ' میلیارد', ' بیلیون', ' بیلیارد', ' تریلیون', ' تریلیارد',
'کوآدریلیون', ' کادریلیارد', ' کوینتیلیون', ' کوانتینیارد', ' سکستیلیون', ' سکستیلیارد', ' سپتیلیون',
'سپتیلیارد', ' اکتیلیون', ' اکتیلیارد', ' نانیلیون', ' نانیلیارد', ' دسیلیون', ' دسیلیارد'],
];
/**
* Clear number and split to 3 sections
* @param {*} num
*/
const PrepareNumber = (num) => {
let Out = num;
if (typeof Out === 'number') {
Out = Out.toString();
}
const NumberLength = Out.length % 3;
if (NumberLength === 1) {
Out = `00${Out}`;
} else if (NumberLength === 2) {
Out = `0${Out}`;
}
// Explode to array
return Out.replace(/\d{3}(?=\d)/g, '$&*')
.split('*');
};
const ThreeNumbersToLetter = (num) => {
// return Zero
if (parseInt(num, 0) === 0) {
return '';
}
const parsedInt = parseInt(num, 0);
if (parsedInt < 10) {
return Letters[0][parsedInt];
}
if (parsedInt <= 20) {
return Letters[1][parsedInt - 10];
}
if (parsedInt < 100) {
const one = parsedInt % 10;
const ten = (parsedInt - one) / 10;
if (one > 0) {
return Letters[2][ten] + Delimiter + Letters[0][one];
}
return Letters[2][ten];
}
const one = parsedInt % 10;
const hundreds = (parsedInt - (parsedInt % 100)) / 100;
const ten = (parsedInt - ((hundreds * 100) + one)) / 10;
const out = [Letters[3][hundreds]];
const SecondPart = ((ten * 10) + one);
if (SecondPart > 0) {
if (SecondPart < 10) {
out.push(Letters[0][SecondPart]);
} else if (SecondPart <= 20) {
out.push(Letters[1][SecondPart - 10]);
} else {
out.push(Letters[2][ten]);
if (one > 0) {
out.push(Letters[0][one]);
}
}
}
return out.join(Delimiter);
};
const Num2persian = (num) => {
// return Zero
if (parseInt(num, 0) === 0) {
return Zero;
}
if (num.length > 66) {
return 'خارج از محدوده';
}
// Split to sections
const SpitedNumber = PrepareNumber(num);
// Fetch Sections and convert
const Output = [];
const SplitLength = SpitedNumber.length;
for (let i = 0; i < SplitLength; i += 1) {
const SectionTitle = Letters[4][SplitLength - (i + 1)];
const converted = ThreeNumbersToLetter(SpitedNumber[i]);
if (converted !== '') {
Output.push(converted + SectionTitle);
}
}
return Output.join(Delimiter);
};
String.prototype.toPersianLetter = function () {
return Num2persian(this);
};
Number.prototype.toPersianLetter = function () {
return Num2persian(parseInt(this).toString());
};
|
JavaScript
| 0.000002 |
@@ -3003,12 +3003,39 @@
ring());%0A%7D;%0A
+export default Num2persian%0A
|
1181a8c82bd5a261319c64c4b93196e7967b353f
|
Update functions init template to latest deps. (#434)
|
lib/init/features/functions.js
|
lib/init/features/functions.js
|
'use strict';
var chalk = require('chalk');
var fs = require('fs');
var RSVP = require('rsvp');
var spawn = require('cross-spawn');
var _ = require('lodash');
var logger = require('../../logger');
var prompt = require('../../prompt');
var enableApi = require('../../ensureApiEnabled').enable;
var requireAccess = require('../../requireAccess');
var scopes = require('../../scopes');
var INDEX_TEMPLATE = fs.readFileSync(__dirname + '/../../../templates/init/functions/index.js', 'utf8');
module.exports = function(setup, config) {
logger.info();
logger.info('A ' + chalk.bold('functions') + ' directory will be created in your project with a Node.js');
logger.info('package pre-configured. Functions can be deployed with ' + chalk.bold('firebase deploy') + '.');
logger.info();
setup.functions = {};
var projectId = _.get(setup, 'rcfile.projects.default');
var enableApis;
if (projectId) {
enableApis = requireAccess({project: projectId}, [scopes.CLOUD_PLATFORM]).then(function() {
enableApi(projectId, 'cloudfunctions.googleapis.com');
enableApi(projectId, 'runtimeconfig.googleapis.com');
});
} else {
enableApis = RSVP.resolve();
}
return enableApis.then(function() {
return config.askWriteProjectFile('functions/package.json', {
name: 'functions',
description: 'Cloud Functions for Firebase',
dependencies: {
'firebase-admin': '~4.2.1',
'firebase-functions': '^0.5.7'
},
private: true
});
}).then(function() {
return config.askWriteProjectFile('functions/index.js', INDEX_TEMPLATE);
}).then(function() {
return prompt(setup.functions, [
{
name: 'npm',
type: 'confirm',
message: 'Do you want to install dependencies with npm now?',
default: true
}
]);
}).then(function() {
if (setup.functions.npm) {
return new RSVP.Promise(function(resolve) {
var installer = spawn('npm', ['install'], {
cwd: config.projectDir + '/functions',
stdio: 'inherit'
});
installer.on('error', function(err) {
logger.debug(err.stack);
});
installer.on('close', function(code) {
if (code === 0) {
return resolve();
}
logger.info();
logger.error('NPM install failed, continuing with Firebase initialization...');
return resolve();
});
});
}
});
};
|
JavaScript
| 0 |
@@ -1411,9 +1411,9 @@
: '~
-4
+5
.2.1
@@ -1453,11 +1453,11 @@
'%5E0.
-5.7
+6.2
'%0A
|
1cc57f6772de43a1420c14739367ed81f27af498
|
Remove unused logger variable.
|
src/pat/sortable.js
|
src/pat/sortable.js
|
define([
"jquery",
"pat-registry"
"pat-logger",
"pat-parser"
], function($, patterns, logger, Parser) {
var log = logger.getLogger("pat.sortable"),
parser = new Parser("sortable");
parser.add_argument("selector");
var _ = {
name: "sortable",
trigger: ".pat-sortable",
init: function($el) {
if ($el.length > 1)
return $el.each(function() { _.init($(this)); });
var cfgs = parser.parse($el, true);
$el.data("patterns.sortable", cfgs);
// use only direct descendants to support nested lists
var $sortables = $el.children().filter(cfgs[0].selector);
// add handles and make them draggable for HTML5 and IE8/9
// it has to be an "a" tag (or img) to make it draggable in IE8/9
var $handles = $("<a href=\"#\" class=\"handle\"></a>").appendTo($sortables);
if("draggable" in document.createElement("span"))
$handles.attr("draggable", true);
else
$handles.bind("selectstart", function(event) {
event.preventDefault();
});
// invisible scroll activation areas
var scrollup = $("<div id=\"pat-scroll-up\"> </div>"),
scrolldn = $("<div id=\"pat-scroll-dn\"> </div>"),
scroll = $().add(scrollup).add(scrolldn);
scrollup.css({ top: 0 });
scrolldn.css({ bottom: 0 });
scroll.css({
position: "fixed", zIndex: 999999,
height: 32, left: 0, right: 0
});
scroll.bind("dragover", function(event) {
event.preventDefault();
if ($("html,body").is(":animated")) return;
var newpos = $(window).scrollTop() +
($(this).attr("id")==="pat-scroll-up" ? -32 : 32);
$("html,body").animate({scrollTop: newpos}, 50, "linear");
});
$handles.bind("dragstart", function(event) {
// Firefox seems to need this set to any value
event.originalEvent.dataTransfer.setData("Text", "");
event.originalEvent.dataTransfer.effectAllowed = ["move"];
if ("setDragImage" in event.originalEvent.dataTransfer)
event.originalEvent.dataTransfer.setDragImage(
$(this).parent()[0], 0, 0);
$(this).parent().addClass("dragged");
// Scroll the list if near the borders
$el.bind("dragover.pat-sortable", function(event) {
event.preventDefault();
if ($el.is(":animated")) return;
var pos = event.originalEvent.clientY + $("body").scrollTop();
if (pos - $el.offset().top < 32)
$el.animate({scrollTop: $el.scrollTop()-32}, 50, "linear");
else if ($el.offset().top+$el.height() - pos < 32)
$el.animate({scrollTop: $el.scrollTop()+32}, 50, "linear");
});
// list elements are only drop targets when one element of the
// list is being dragged. avoids dragging between lists.
$sortables.bind("dragover.pat-sortable", function(event) {
var $this = $(this),
midlineY = $this.offset().top - $(document).scrollTop() +
$this.height()/2;
// bail if dropping on self
if ($(this).hasClass("dragged"))
return;
$this.removeClass("drop-target-above drop-target-below");
if (event.originalEvent.clientY > midlineY)
$this.addClass("drop-target-below");
else
$this.addClass("drop-target-above");
event.preventDefault();
});
$sortables.bind("dragleave.pat-sortable", function() {
$sortables.removeClass("drop-target-above drop-target-below");
});
$sortables.bind("drop.pat-sortable", function(event) {
if ($(this).hasClass("dragged"))
return;
if ($(this).hasClass("drop-target-below"))
$(this).after($(".dragged"));
else
$(this).before($(".dragged"));
$(this).removeClass("drop-target-above drop-target-below");
event.preventDefault();
});
//XXX: Deactivate document scroll areas, as DnD affects only
// scrolling of parent element
//scroll.appendTo("body");
});
$handles.bind("dragend", function() {
$(".dragged").removeClass("dragged");
$sortables.unbind(".pat-sortable");
$el.unbind(".pat-sortable");
$("#pat-scroll-up, #pat-scroll-dn").detach();
});
return $el;
}
};
patterns.register(_);
return _;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
|
JavaScript
| 0 |
@@ -125,56 +125,8 @@
var
-log = logger.getLogger(%22pat.sortable%22),%0A
pars
|
b4dd9dad6df0ae84fb0ebf62de9a167fac2be9d3
|
Update ng-prettyjson-tmpl.js
|
src/ng-prettyjson-tmpl.js
|
src/ng-prettyjson-tmpl.js
|
(function(angular) {
'use strict';
angular.module('ngPrettyJson')
.run(['$templateCache', function ($templateCache) {
$templateCache.put('ng-prettyjson/ng-prettyjson-panel.tmpl.html',
'<div>' +
'<button ng-click="edit()" ng-show="edition && !editActivated">Edit</button>' +
'<button ng-click="edit()" ng-show="edition && editActivated">Cancel</button>' +
'<button ng-click="update()" ng-show="editActivated && parsable">Update</button>' +
'<pre class="pretty-json" id="{{id}}"></pre>' +
'</div>');
}]);
})(window.angular);
|
JavaScript
| 0.000004 |
@@ -205,32 +205,46 @@
+ %0A '%3Cbutton
+ type=%22button%22
ng-click=%22edit(
@@ -303,32 +303,46 @@
' +%0A '%3Cbutton
+ type=%22button%22
ng-click=%22edit(
@@ -410,16 +410,30 @@
'%3Cbutton
+ type=%22button%22
ng-clic
|
06e032972f1b4d8ccfa15ed6d6cfb77fc820bdc1
|
change proportion
|
src/objects/MapManager.js
|
src/objects/MapManager.js
|
//TO DESTROY LATER
const MaxLayer = 2
class MapManager {
constructor(map) {
this.removedBlock = [];
this.map = map;
}
findLayerToDestroy(x, y, lengthX, lengthY) {
let layerIndex = 0;
for(let index = 0; index < MaxLayer; index++) {
if( this.map.getTile(x, y, index) === null &&
this.map.getTile(x + lengthX-1, y + lengthY-1, index) === null) {
layerIndex++;
} else {
break;
}
}
return layerIndex;
}
eraseBlock() {
const x = 0;
const y = 0;
const lengthY = 10;
const lengthX = 10;
//check the layers associated to the deletion;
let objectsRemoves = []
const layerIndex = this.findLayerToDestroy(x, y, lengthX, lengthY);
for(let xAxis = x; xAxis < lengthX; xAxis++) {
for(let yAxis = y; yAxis < lengthY; yAxis++) {
const tile = this.map.removeTile(xAxis, yAxis, layerIndex);
objectsRemoves.push(tile);
}
}
this.removedBlock.push({tiles: objectsRemoves, layerIndex: layerIndex, x, y});
this.removedBlock.sort(this.sortByLayerIndex);
console.log(this.removedBlock)
}
sortByLayerIndex(a, b) {
return a.layerIndex < b.layerIndex;
}
undoBlock() {
const x = 0;
const y = 0;
const lengthX = 10;
const lengthY = 10;
const redoElements = this.removedBlock.find(list => list.x === x && list.y === y );
if(redoElements) {
redoElements.tiles.forEach(tile => {
this.map.putTile(tile, tile.x, tile.y, redoElements.layerIndex);
});
//remove the element after
const newArray = this.removedBlock.filter(elmt => elmt !== redoElements);
this.removedBlock = newArray.sort(this.sortByLayerIndex);
}
}
}
export default MapManager;
|
JavaScript
| 0.000005 |
@@ -534,34 +534,33 @@
const lengthY =
-10
+4
;%0A const leng
@@ -561,26 +561,25 @@
t lengthX =
-10
+4
;%0A //chec
@@ -745,24 +745,25 @@
= x; xAxis %3C
+=
lengthX; xA
@@ -803,16 +803,17 @@
yAxis %3C
+=
lengthY
@@ -1080,43 +1080,8 @@
x);%0A
- console.log(this.removedBlock)%0A
%7D%0A
@@ -1223,18 +1223,17 @@
ngthX =
-10
+4
;%0A co
@@ -1250,10 +1250,9 @@
Y =
-10
+4
;%0A
|
4ca9835f9a8979e1c8051c53623e664c2d39a1a2
|
add description
|
Algorithms/JS/strings/firstUniqueCharacter.js
|
Algorithms/JS/strings/firstUniqueCharacter.js
|
firstUniqueCharacter.js
|
JavaScript
| 0.000004 |
@@ -1,24 +1,269 @@
-firstUniqueCharacter.js
+// Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.%0A%0A// Examples:%0A%0A// s = %22leetcode%22%0A// return 0.%0A%0A// s = %22loveleetcode%22,%0A// return 2.%0A// Note: You may assume the string contain only lowercase letters.
%0A
|
7a5679651cf226ce7abfc328dd2c734253ab81c3
|
remove misleading comment
|
BowlingGame.js
|
BowlingGame.js
|
"use strict";
var assert = require('assert');
var add = function(x,y) { return x + y; };
var Game = function() {
this._pins = [];
this.roll = function(n) {
this._pins.push(n);
};
this._scoreSpare = function(i) {
return this._scoreFrame(i) + this._pins[i+2];
};
this._scoreFrame = function(i) {
return this._pins[i] + this._pins[i+1];
};
this._isSpare = function(i) {
return this._pins[i] + this._pins[i+1] === 10;
};
this.score = function() {
var sum = 0;
var pinCount = 0;
for (var i=0;i<10;++i) {
if (this._isSpare(pinCount))
sum += this._scoreSpare(pinCount);
else
sum += this._scoreFrame(pinCount);
pinCount += 2;
}
return sum;
};
return this;
};
describe('bowling game', function() {
var rollMany = function(game, roll, n) {
for (var i=0;i<n;++i) {
game.roll(roll);
}
};
it('rolling 20 gutter balls is a gutter game', function() {
var game = new Game();
rollMany(game, 0, 20);
assert.equal(0, game.score());
});
it('hitting 20 single pins scores 20', function() {
var game = new Game();
rollMany(game, 1, 20);
assert.equal(20, game.score());
});
it('handles spares', function() {
var game = new Game();
game.roll(5);
game.roll(5); // spare
game.roll(3);
// Rest is a gutter game
rollMany(game, 0,17);
assert.equal(16, game.score());
});
});
|
JavaScript
| 0 |
@@ -882,24 +882,99 @@
%0A%09%7D%0A %7D;%0A%0A
+ var rollSpare = function(game) %7B%0A%09game.roll(5);%0A%09game.roll(5);%0A %7D;%0A%0A
it('roll
@@ -1329,45 +1329,24 @@
);%0A%09
-game.roll(5);%0A%09game.roll(5); // spare
+rollSpare(game);
%0A%09ga
|
59a28940ee7eda1ad8c9884f1fbf18c44ba55d22
|
Remove leftover trace and fix block comment
|
lib/laws-filter/laws-filter.js
|
lib/laws-filter/laws-filter.js
|
/**
* Module dependencies.
*/
var Emitter = require('emitter');
var store = require('store')();
var laws = require('laws');
var citizen = require('citizen');
var merge = require('merge-util');
var t = require('t');
var type = require('type');
var _ = require('to-function');
var sorts = require('./sorts');
var log = require('debug')('democracyos:laws-filter');
/**
* Create a `LawsFilter` instance
*/
function LawsFilter() {
if (!(this instanceof LawsFilter)) {
return new LawsFilter();
};
this.state('initializing');
this.$_items = [];
this.$_filters = {};
this.$_counts = [];
this.sorts = sorts;
this.$_filters['sort'] = 'closing-soon';
this.sort = sorts[this.get('sort')];
laws.ready(this.fetch.bind(this));
}
/**
* Mixin `LawsFilter` with `Emitter`
*/
Emitter(LawsFilter.prototype);
LawsFilter.prototype.fetch = function() {
store.get('laws-filter', ondata.bind(this));
function ondata (err, data) {
if (err) log('unable to fetch');
this.set(data);
this.state('loaded');
}
}
LawsFilter.prototype.items = function(v) {
if (0 === arguments.length) {
return this.$_items;
}
this.$_items = v;
}
LawsFilter.prototype.get = function(key) {
if (0 === arguments.length) {
return this.$_filters;
};
return this.$_filters[key];
}
LawsFilter.prototype.set = function (key, value) {
if (2 === arguments.length) {
// Create param object and call recursively
var obj = {};
return obj[key] = value, this.set(obj);
};
// key is an object
merge(this.$_filters, key);
// notify change of filters
this.ready(onready.bind(this));
function onready() {
this.emit('change', this.get());
};
// reload items with updated filters
this.reload();
// save current state
return this.save();
}
LawsFilter.prototype.save = function () {
store.set('laws-filter', this.get(), onsave.bind(this));
function onsave(err, ok) {
if (err) return log('unable to save');
log('saved');
}
return this;
}
/**
* Emit `ready` if collection has
* completed a cycle of request
*
* @param {Function} fn
* @return {Laws} Instance of `Laws`
* @api public
*/
LawsFilter.prototype.ready = function(fn) {
var self = this;
function done() {
if ('loaded' === self.state()) {
return fn();
}
}
if ('loaded' === this.state()) {
//We force 0 timeout on call stack
setTimeout(done, 0);
} else {
this.once('loaded', done);
}
return this;
}
/**
* Save or retrieve current instance
* state and emit to observers
*
* @param {String} state
* @param {String} message
* @return {Laws|String} Instance of `Laws` or current `state`
* @api public
*/
LawsFilter.prototype.state = function(state, message) {
if (0 === arguments.length) {
return this.$_state;
}
log('state is now %s', state);
this.$_state = state;
this.emit(state, message);
return this;
};
LawsFilter.prototype.reload = function() {
var status = this.get('status');
var hideVoted = this.get('hide-voted');
var sortName = this.get('sort');
var items = laws.get();
this.$_counts['open'] = items.filter(_({ status: 'open'})).length;
this.$_counts['closed'] = items.filter(_({ status: 'closed'})).length;
// Filter by status
if (status) {
items = items.filter(_({ status: status }));
};
// Check if logged user's id is in the law's participants
if (hideVoted) {
items = items.filter(_('voted !== true'));
}
// Sort filtered
// TODO: remove hardcode and make it some sort of default
var sortFn = sortName ? sorts[sortName].sort : sorts['closing-soon'].sort;
items = items.sort(sortFn);
// save items
this.items(items);
this.ready(onready.bind(this));
function onready() {
this.emit('reload', this.items());
};
return this;
}
/**
* Counts laws under a specific status, without side-effect
* @param {String} status filter criterion
* @return {int} Number of laws with parameter status
*/
LawsFilter.prototype.countFiltered = function(status) {
return this.$_counts[status];
};
/**
* Expose `LawsFilter` constructor
*/
module.exports = new LawsFilter();
|
JavaScript
| 0 |
@@ -2484,44 +2484,31 @@
%0A *
-Save
+Gets
or
-retrieve current instance%0A *
+sets receiver's
sta
@@ -2792,41 +2792,8 @@
%7D%0A%0A
- log('state is now %25s', state);%0A
th
|
c2d834d83c363d6a5fa5cdf5e5e1158679b28408
|
test for headroom react
|
src/pages/page-2/index.js
|
src/pages/page-2/index.js
|
import React, { PureComponent } from 'react'
import Link from 'components/Link'
import PropTypes from 'prop-types'
export default class Page2 extends PureComponent {
static propTypes = {
children: PropTypes.any,
}
render() {
const { children } = this.props
return (
<div>
<h1>Hi from the second page</h1>
<p>Welcome to page 2</p>
<Link to='/'>Go back to the homepage</Link>
</div>
)
}
}
|
JavaScript
| 0.000001 |
@@ -417,16 +417,102 @@
%3C/Link%3E%0A
+ %3Cdiv style=%7B%7B marginTop: '2000px' %7D%7D%3E%0A %3Cdiv%3EFIN%3C/div%3E%0A %3C/div%3E%0A
%3C/
|
c3d0ca7aa3536868f5cba10dd00f4c9dca03b1ef
|
Add pad and truncate expression functions.
|
src/parsers/expression.js
|
src/parsers/expression.js
|
import {
ASTNode,
parse,
codegen,
functions as baseFunctions,
constants
} from 'vega-expression';
import {error, stringValue} from 'vega-util';
var Literal = 'Literal';
var Identifier = 'Identifier';
export var signalPrefix = '$';
export var scalePrefix = '%';
export var indexPrefix = '@';
export var eventPrefix = 'event.vega.';
function signalCode(id) {
return '_[' + stringValue('$' + id) + ']';
}
export var functions = function(codegen) {
var fn = baseFunctions(codegen);
// view-specific event information
fn.view = eventPrefix + 'view';
fn.item = eventPrefix + 'item';
fn.group = eventPrefix + 'group';
fn.xy = eventPrefix + 'xy';
fn.x = eventPrefix + 'x';
fn.y = eventPrefix + 'y';
fn.encode = 'this.encode';
fn.modify = 'this.modify';
// format functions
fn.format = 'this.format';
fn.timeFormat = 'this.timeFormat';
fn.utcFormat = 'this.utcFormat';
// color functions
fn.rgb = 'this.rgb';
fn.lab = 'this.lab';
fn.hcl = 'this.hcl';
fn.hsl = 'this.hsl';
// scales, projections, data
fn.span = 'this.span';
fn.range = 'this.range';
fn.scale = 'this.scale';
fn.invert = 'this.scaleInvert';
fn.copy = 'this.scaleCopy';
fn.indata = 'this.indata';
// interaction support
fn.pinchDistance = 'this.pinchDistance';
fn.pinchAngle = 'this.pinchAngle';
// environment functions
fn.open = 'this.open';
fn.screen = function() { return 'window.screen'; };
fn.windowsize = function() {
return '[window.innerWidth, window.innerHeight]';
};
return fn;
};
export var generator = codegen({
blacklist: ['_'],
whitelist: ['datum', 'event'],
fieldvar: 'datum',
globalvar: signalCode,
functions: functions,
constants: constants
});
function signal(name, scope, params) {
var signalName = signalPrefix + name;
if (!params.hasOwnProperty(signalName)) {
params[signalName] = scope.signalRef(name);
}
}
function scale(name, scope, params) {
var scaleName = scalePrefix + name;
if (!params.hasOwnProperty(scaleName)) {
params[scaleName] = scope.scaleRef(name);
}
}
function index(data, field, scope, params) {
var indexName = indexPrefix + field;
if (!params.hasOwnProperty(indexName)) {
params[indexName] = scope.getData(data).indataRef(field);
}
}
export default function(expr, scope, preamble) {
var params = {}, ast, gen;
try {
ast = parse(expr);
} catch (err) {
error('Expression parse error: ' + expr);
}
// analyze ast for dependencies
ast.visit(function visitor(node) {
if (node.type !== 'CallExpression') return;
var name = node.callee.name,
args = node.arguments;
switch (name) {
case 'scale':
case 'invert':
case 'range':
if (args[0].type === Literal) { // scale dependency
scale(args[0].value, scope, params);
} else if (args[0].type === Identifier) { // forward reference to signal
name = args[0].name;
args[0] = new ASTNode(Literal);
args[0].raw = '{signal:"' + name + '"}';
} else {
error('First argument to ' + name + ' must be a string literal or identifier.');
}
break;
case 'copy':
if (args[0].type !== Literal) error('Argument to copy must be a string literals.');
scale(args[0].value, scope, params);
break;
case 'indata':
if (args[0].type !== Literal) error('First argument to indata must be a string literal.');
if (args[1].type !== Literal) error('Second argument to indata must be a string literal.');
index(args[0].value, args[1].value, scope, params);
break;
}
});
// perform code generation
gen = generator(ast);
gen.globals.forEach(function(name) { signal(name, scope, params); });
// returned parsed expression
return {
$expr: preamble ? preamble + 'return(' + gen.code + ');' : gen.code,
$fields: gen.fields,
$params: params
};
}
|
JavaScript
| 0 |
@@ -920,16 +920,72 @@
Format';
+%0A fn.pad = 'this.pad';%0A fn.truncate = 'this.truncate';
%0A%0A // c
|
52cb3e23f8e47699c8d8a41bd6133546c9fb69d8
|
Allow projection type to be a signal.
|
src/parsers/projection.js
|
src/parsers/projection.js
|
import {error, isArray, isObject} from 'vega-util';
export default function(proj, scope) {
var params = {
type: proj.type || 'mercator'
};
for (var name in proj) {
if (name === 'name' || name === 'type') continue;
params[name] = parseParameter(proj[name], scope);
}
scope.addProjection(proj.name, params);
}
function parseParameter(_, scope) {
return isArray(_) ? _.map(function(_) { return parseParameter(_, scope); })
: !isObject(_) ? _
: _.signal ? scope.signalRef(_.signal)
: error('Unsupported parameter object: ' + JSON.stringify(_));
}
|
JavaScript
| 0 |
@@ -105,45 +105,8 @@
= %7B
-%0A type: proj.type %7C%7C 'mercator'%0A
%7D;%0A%0A
@@ -159,27 +159,8 @@
ame'
- %7C%7C name === 'type'
) co
|
344d52ede5792429debd5cbc42a1d1865cff8567
|
Remove log
|
src/renderer/renderer.js
|
src/renderer/renderer.js
|
import {
WebGLRenderer, OrthographicCamera, Scene, Group, Vector3, Ray, Math as ThreeMath
} from "../../node_modules/three/build/three.module.js";
import MapRenderer from "./map-renderer.js";
import Tileset from "./tileset.js";
import { RenderObject } from "./object.js";
export { ObjectType } from "./object.js";
let testing = false;
export class Renderer {
static enableTesting() {
testing = true;
console.info("[dtile-renderer] Testing mode enabled; WebGL will not be used.");
}
constructor(canvas) {
this._canvas = canvas;
this._width = 1;
this._height = 1;
if (!testing) {
this.renderer = new WebGLRenderer({
canvas,
alpha: true
});
}
this.camera = new OrthographicCamera(0, 0, 0, 25, 0.1, 1000);
this.resetView();
this.scene = new Scene();
this._mapSceneGroup = new Group();
this.scene.add(this._mapSceneGroup);
this.debugMode = false;
this.runProfile = false;
this._tilesets = [];
this._mapRenderer = new MapRenderer(this.tilesets, this._mapSceneGroup);
}
async updateMap(map) {
this._mapRenderer.map = map;
this._map = map;
}
async updateTilesets(tilesets) {
this._tilesets = {};
await Promise.all(Object.entries(tilesets).map(async ([id, tileset]) => {
this._tilesets[id] = await Tileset.load(tileset);
}));
this._mapRenderer.tilesets = this._tilesets;
}
setCameraBoundOffsets(x1, x2, y1, y2) {
this._cameraBoundOffsets = { x1, x2, y1, y2 };
}
getTileXY(layer, mouseX, mouseY) {
const ray = (() => {
if (this.camera.isOrthographicCamera) {
const position = this._screenToWorldPosition(mouseX, mouseY);
const direction = this.camera.getWorldDirection();
direction.z = -direction.z;
return new Ray(position, direction);
} else {
console.warn("This type of camera is not supported for raycasting");
}
})();
return this._mapRenderer.castRayOnLayer(layer, ray);
}
render() {
if (testing) return;
if (this.debugMode) console.time("Render Time");
this.renderer.render(this.scene, this.camera);
if (this.debugMode) {
this.printDebugInfo("Render Time");
}
}
setGhosts(ghosts) {
this._mapRenderer.setGhosts(ghosts);
}
createObject(type, params) {
const [mapWidth, mapHeight] = (() => {
if (this._map) return [this._map.width, this._map.height];
else return [0, 0];
})();
params.x -= mapWidth / 2 - 0.5;
params.y = -params.y + mapHeight / 2 - 0.5;
return new RenderObject(type, params, this.scene);
}
updateRendererSize(width, height) {
if (!testing) {
this.renderer.setSize(width, height);
}
this._width = width;
this._height = height;
this._updateOrhtographicCamera();
}
zoom(mouseX, mouseY, amount) {
amount *= -1;
amount /= 100;
const targetOrtho = ThreeMath.clamp(this.camera.bottom - amount, 0.1, 100);
const moveTowards = this._screenToWorldPosition(mouseX, mouseY);
const distance = new Vector3().subVectors(moveTowards, this.camera.position);
const scaledDistance = distance.clone().multiplyScalar(targetOrtho / this.camera.bottom);
const offset = new Vector3().subVectors(distance, scaledDistance);
offset.setZ(0);
this.camera.position.add(offset);
this.camera.bottom = targetOrtho;
this._updateOrhtographicCamera();
}
pan(dx, dy) {
const worldDelta = this._screenToWorldUnits(-dx, -dy);
console.log(worldDelta);
this.camera.position.add(worldDelta);
this._updateOrhtographicCamera();
}
resetView() {
this.camera.position.set(0, 0, -100);
this.camera.position.z = -100;
this.camera.rotation.y = Math.PI;
this.camera.rotation.z = Math.PI;
this.camera.bottom = 25;
this._updateOrhtographicCamera();
}
_updateOrhtographicCamera() {
const he = this.camera.bottom;
const a = this._width / this._height;
this.camera.top = -he;
this.camera.left = -he * a;
this.camera.right = he * a;
if (this._map) {
// Clamp to map position
const c = this.camera;
const cp = c.position;
const hw = this._map.width / 2;
const hh = this._map.height / 2;
const { x1, x2, y1, y2 } = (this._cameraBoundOffsets || {
x1: 0, x2: 0, y1: 0, y2: 0
});
const p1 = this._screenToWorldUnits(x1, y1);
const p2 = this._screenToWorldUnits(x2, y2);
this.camera.position.set(
ThreeMath.clamp(
cp.x,
Math.min(-hw - c.left - p1.x, 0),
Math.max(hw - c.right + p2.x, 0)
),
ThreeMath.clamp(
cp.y,
Math.min(-hh - c.top - p1.y, 0),
Math.max(hh - c.bottom + p2.y, 0)
),
cp.z
);
}
this.camera.updateProjectionMatrix();
}
_screenToWorldPosition(sx, sy) {
const screen3D = new Vector3();
screen3D.x = (sx / this._width) * 2 - 1;
screen3D.y = -(sy / this._height) * 2 + 1;
screen3D.z = 1.0;
screen3D.unproject(this.camera);
return screen3D;
}
_screenToWorldUnits(sx, sy) {
return new Vector3(
sx / this._width * (this.camera.right * 2),
-sy / this._height * (this.camera.right * 2),
0
);
}
printDebugInfo(consoleTimer) {
console.group("Render info");
console.log(`
Draw Calls: ${this.renderer.info.render.calls}
Vertex Count: ${this.renderer.info.render.vertices}
Face Count: ${this.renderer.info.render.faces}
---
Textures Count: ${this.renderer.info.memory.textures}
Shader Program Count: ${this.renderer.info.programs.length}
`.replace(/[ ]{2,}/g, "").trim());
if (consoleTimer) {
console.log("---");
console.timeEnd(consoleTimer);
}
console.groupEnd();
}
}
|
JavaScript
| 0.000001 |
@@ -3884,41 +3884,8 @@
dy);
-%0A console.log(worldDelta);
%0A%0A
|
056bf62e70084d0a4d0e91363f4563ec25d50b5f
|
Fix issue where a dojo-admin would not be able to use manage-event-us… (#163)
|
lib/perm/is-ticketing-admin.js
|
lib/perm/is-ticketing-admin.js
|
'use strict';
var _ = require('lodash');
function isTicketingAdmin (args, cb) {
var seneca = this;
var plugin = args.role;
var userId, dojoId;
if(args.user) userId = args.user.id;
if (args.params) {
if(args.params.query) dojoId = args.params.query.dojoId;
if(args.params.eventInfo && _.isUndefined(dojoId)) dojoId = args.params.eventInfo.dojoId;
if(args.params.query && _.isUndefined(dojoId)) dojoId = args.params.query.id;
} else {
if(args.query) dojoId = args.query.dojoId;
if(args.eventInfo && _.isUndefined(dojoId)) dojoId = args.eventInfo.dojoId;
if(args.query && _.isUndefined(dojoId)) dojoId = args.query.id;
}
var isTicketingAdmin = false;
// Could also check the opposite way, from child to Parent
seneca.act({role: 'cd-dojos', cmd: 'load_usersdojos', query: { userId: userId, dojoId: dojoId }},
function (err, response) {
var userDojoEntity = response[0];
if (err) {
seneca.log.error(seneca.customValidatorLogFormatter('cd-events', 'isTicketingAdmin', err, {userId: userId, dojoId: dojoId}));
return cb(null, {'allowed': false});
}
isTicketingAdmin = _.find(userDojoEntity.userPermissions, function (userPermission) {
return userPermission.name === 'ticketing-admin';
});
return cb(null, {'allowed': !!isTicketingAdmin});
});
}
module.exports = isTicketingAdmin;
|
JavaScript
| 0 |
@@ -34,17 +34,46 @@
dash');%0A
+var async = require('async');
%0A
-
%0Afunctio
@@ -167,24 +167,44 @@
erId, dojoId
+, eventId, sessionId
;%0A if(args.
@@ -491,16 +491,222 @@
ery.id;%0A
+ if(args.params.query && _.isUndefined(dojoId)) eventId = args.params.query.eventId;%0A if(args.params.query && _.isUndefined(dojoId) && _.isUndefined(eventId)) sessionId = args.params.query.sessionId;%0A
%7D else
@@ -1002,16 +1002,1308 @@
Parent%0A
+ function checkPrerequisites (wfCb) %7B%0A function getEventFromSession (_wCb) %7B%0A if (sessionId) %7B // We need to get the dojoId associated%0A seneca.act(%7Brole: 'cd-events', cmd: 'loadSession', id: sessionId%7D, function (err, session) %7B%0A if (err) return cb(err);%0A if (session.eventId) %7B%0A eventId = session.eventId;%0A return _wCb();%0A %7D else %7B%0A return cb(null, %7B'allowed': false%7D);%0A %7D%0A %7D);%0A %7D else %7B%0A return _wCb();%0A %7D%0A %7D%0A function getDojoFromEvent (_wCb) %7B%0A if (eventId) %7B // We need to get the dojoId associated%0A seneca.act(%7Brole: 'cd-events', cmd: 'getEvent', id: eventId%7D, function (err, event) %7B%0A if (err) return cb(err);%0A if (event.dojoId) %7B%0A dojoId = event.dojoId;%0A return _wCb();%0A %7D else %7B%0A return cb(null, %7B'allowed': false%7D);%0A %7D%0A %7D);%0A %7D else %7B%0A return _wCb();%0A %7D%0A %7D%0A if (_.isUndefined(dojoId) && (eventId %7C%7C sessionId)) %7B%0A async.waterfall(%5B%0A getEventFromSession,%0A getDojoFromEvent%0A %5D, wfCb);%0A %7D else %7B%0A return wfCb();%0A %7D%0A %7D%0A function verifyPermissions(wfCb) %7B%0A if (_.isUndefined(dojoId)) return cb(null, %7B'allowed': false%7D);%0A
seneca
@@ -2389,16 +2389,28 @@
: dojoId
+, deleted: 0
%7D%7D,%0A
@@ -2897,22 +2897,100 @@
dmin%7D);%0A
+
%7D);%0A
+ %7D%0A async.waterfall(%5B%0A checkPrerequisites,%0A verifyPermissions%0A %5D);%0A
%7D%0A%0Amodul
|
b5ceb5aea7398c07da477405f8ccf3ae11406000
|
fix error _routes
|
lib/presentationTier/routes.js
|
lib/presentationTier/routes.js
|
/*jshint node: true, -W106 */
'use strict';
/*
* Name : socket.js
* Module : Lib::PresentationTier::Routes
* Location : /lib/presentationTier
*
* History :
*
* Version Date Programmer Description
* =========================================================
* 0.0.1 2015-05-20 Matteo Furlan Working version with addRoutingPath
* 0.0.1 2015-05-18 Samuele Zanella Initial code
* =========================================================
*/
var Express = require('express');
function Routes(exprApp, norrisNamespace) {
if(exprApp===undefined || norrisNamespace===undefined || exprApp.lazyrouter===undefined ||
typeof norrisNamespace !=='string' || norrisNamespace.length < 1 ||
norrisNamespace.indexOf('/')!==0) {
console.log('Error: 911');
return;
}
this._baseURL='';
this._norrisNamespace = norrisNamespace;
this._exprApp=exprApp;
this._routes.addRoutingPath(norrisNamespace,'pageList'); //page is pageList.ejs;
}
Routes.prototype.addRoutingPath = function(namespace, filename) {
if(namespace===undefined || typeof namespace !=='string' || namespace.length < 1 ||
namespace.indexOf('/')!==0 || filename === undefined || typeof filename !== 'string' ||
filename.length <= 0) {
console.log('Error: 912');
return false;
}
var app = Express();
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use('/',Express.static(__dirname + '/../../frontend/app/views'));
var nspNorris=this._norrisNamespace;
var baseURL='';
var handle = function (req, res) {
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
baseURL=req.protocol + '://' + req.get('host');
var norrisNamespace=req.protocol + '://' + req.get('host')+nspNorris;
res.render(filename,{fullURL:fullUrl, norrisNamespace : norrisNamespace});
};
this._baseURL=baseURL;
app.get(namespace, handle);
this._exprApp.use(namespace, app);
return true;
};
module.exports = Routes;
|
JavaScript
| 0.000001 |
@@ -891,16 +891,8 @@
his.
-_routes.
addR
|
57e743713a4a86d8c228b24b3be40cbf8bcd768b
|
Fix add Operation
|
src/resource/resource.js
|
src/resource/resource.js
|
Vue.component('api-resource', {
props: ['key', 'path', 'index'],
computed: {
sanitisePath : function() {
return 'resource_'+this.index.split('/').join('').split('{').join('').split('}').join('');
},
pathEntry : {
get : function() {
return this.index
},
set : function(newVal) {
this.$parent.renamePath(this.index, newVal);
}
}
},
data: function() {
return {}
},
methods : {
removePath : function(target) {
this.$parent.removePath(target);
},
addOperation : function(template) {
var methods = ['get','post','put','delete','head','patch','options'];
var index = 0;
while (this.path[methods[index]] && index<methods.length) {
index++;
}
if (index<methods.length) {
var op = {};
op.summary = template.summary || '';
op.description = template.description || '';
op.parameters = template.parameters || [];
op.operationId = template.operationId || '';
Vue.set(this.path, methods[index], op);
}
},
removeOperation : function(target) {
this.$root.save();
Vue.delete(this.path, target);
},
renameOperation : function(oldMethod, newMethod) {
if (this.path[newMethod]) {
Vue.set(this.path, 'temp', this.path[newMethod]);
Vue.delete(this.path, newMethod);
}
Vue.set(this.path, newMethod, this.path[oldMethod]);
Vue.delete(this.path, oldMethod);
if (this.path.temp) {
Vue.set(this.path, oldMethod, this.path.temp);
Vue.delete(this.path, 'temp');
}
}
},
template: '#template-resource'
});
|
JavaScript
| 0.000002 |
@@ -957,16 +957,28 @@
ummary =
+ template &&
templat
@@ -1026,16 +1026,28 @@
iption =
+ template &&
templat
@@ -1098,16 +1098,28 @@
meters =
+ template &&
templat
@@ -1170,16 +1170,28 @@
tionId =
+ template &&
templat
|
777b0ff1e561ecacf0835f752f45989728ab20fc
|
Use properties where it makes sense
|
embark-ui/src/containers/ApplicationPreviewContainer.js
|
embark-ui/src/containers/ApplicationPreviewContainer.js
|
import React from 'react';
class ApplicationPreviewContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
previewUrl: 'http://localhost:8000'
};
}
render() {
return (
<div>
<div className="input-group mb-3">
<input type="text" className="form-control" placeholder="URL" value={this.state.previewUrl} onChange={(e) => this.handlePreviewUrlChange(e)} />
<div className="input-group-append">
<button className="btn btn-outline-secondary" type="button" onClick={(e) => this.handlePreviewGo(e)}>Go</button>
</div>
</div>
<iframe width="100%" height="500" title="Preview" ref={(iframe) => this.previewIframe = iframe} onLoad={(e) => this.handlePreviewChange(e)} src="http://localhost:8000"></iframe>
</div>
);
}
handlePreviewUrlChange(ev) {
this.setState({previewUrl: ev.target.value});
}
handlePreviewChange(ev) {
try {
let url = ev.target.contentWindow.location.toString();
this.setState({previewUrl: url});
} catch(e) {
// Nothing here.
}
}
handlePreviewGo() {
this.previewIframe.src = this.previewUrl;
}
}
export default ApplicationPreviewContainer;
|
JavaScript
| 0.000005 |
@@ -1,8 +1,44 @@
+import PropTypes from 'prop-types';%0A
import R
@@ -188,43 +188,126 @@
-previewUrl: 'http://loc
+// TODO(andremedeiros): Figure out how to pull this from the actu
al
+
host
-:8000'
+.%0A previewUrl: this.props.previewHomepage
%0A
@@ -910,31 +910,36 @@
src=
-%22http://localhost:8000%22
+%7Bthis.props.previewHomepage%7D
%3E%3C/i
@@ -1298,24 +1298,30 @@
.src = this.
+state.
previewUrl;%0A
@@ -1327,16 +1327,190 @@
%0A %7D%0A%7D%0A%0A
+ApplicationPreviewContainer.propTypes = %7B%0A previewHomepage: PropTypes.string%0A%7D;%0A%0AApplicationPreviewContainer.defaultProps = %7B%0A previewHomepage: 'http://localhost:8000'%0A%7D;%0A%0A
export d
|
8aa66e20badf947f3d4698d2cadb578ed65344cf
|
Fix in SurfaceManager.
|
editor/SurfaceManager.js
|
editor/SurfaceManager.js
|
import { platform, isArrayEqual, getKeyForPath } from '../util'
const DEBUG = false
export default class SurfaceManager {
constructor (editorState) {
this.editorState = editorState
this.surfaces = new Map()
editorState.addObserver(['selection', 'document'], this._onSelectionOrDocumentChange, this, { stage: 'pre-position' })
// editorState.addObserver(['selection', 'document'], this._scrollSelectionIntoView, this, { stage: 'finalize' })
}
dispose () {
this.editorState.off(this)
}
getSurface (name) {
if (name) {
return this.surfaces.get(name)
}
}
getFocusedSurface () {
console.error("DEPRECATED: use 'context.editorState.focusedSurface instead")
return this.editorState.focusedSurface
}
registerSurface (surface) {
const id = surface.getId()
if (DEBUG) console.log(`Registering surface ${id}.`, surface.__id__)
if (this.surfaces.has(id)) {
throw new Error(`A surface with id ${id} has already been registered.`)
}
this.surfaces.set(id, surface)
}
unregisterSurface (surface) {
const id = surface.getId()
if (DEBUG) console.log(`Unregistering surface ${id}.`, surface.__id__)
const registeredSurface = this.surfaces.get(id)
if (registeredSurface === surface) {
this.surfaces.delete(id)
}
}
// TODO: would be good to have an index of surfaces by path
_getSurfaceForProperty (path) {
// first try the canonical one
const canonicalId = getKeyForPath(path)
if (this.surfaces.has(canonicalId)) {
return this.surfaces.get(canonicalId)
}
for (const surface of this.surfaces.values()) {
let surfacePath = null
if (surface._isContainerEditor) {
surfacePath = surface.getContainerPath()
} else if (surface.getPath) {
surfacePath = surface.getPath()
}
if (surfacePath && isArrayEqual(path, surfacePath)) {
return surface
}
}
}
_onSelectionOrDocumentChange () {
// console.log('SurfaceManager._onSelectionChange()')
// Reducing state.focusedSurface (only if selection has changed)
if (this.editorState.isDirty('selection')) {
const selection = this.editorState.selection
if (!selection || selection.isNull()) {
// blur the focused surface to make sure that it does not remain focused
// e.g. if DOM selection is not set for some reasons.
// HACK: not all surfaces implement _blur()
const focusedSurface = this.editorState.focusedSurface
if (focusedSurface && focusedSurface._blur) {
focusedSurface._blur()
}
}
// update state.focusedSurface
this._reduceFocusedSurface(selection)
// HACK: removing DOM selection *and* blurring when having a CustomSelection
// otherwise we will receive events on the wrong surface
// instead of bubbling up to GlobalEventManager
if (selection && selection.isCustomSelection() && platform.inBrowser) {
window.getSelection().removeAllRanges()
window.document.activeElement.blur()
}
}
// TODO: this still needs to be improved. The DOM selection can be affected by other updates than document changes
this._recoverDOMSelection()
}
_reduceFocusedSurface (sel) {
const editorState = this.editorState
let surface = null
if (sel && sel.surfaceId) {
surface = this.surfaces.get(sel.surfaceId)
}
editorState.focusedSurface = surface
}
/*
At the end of the update flow, make sure the surface is focused
and displays the right DOM selection
*/
_recoverDOMSelection () {
// console.log('SurfaceManager._recoverDOMSelection()')
const editorState = this.editorState
// do not rerender the selection if the editorSession has
// been blurred, e.g., while some component, such as Find-And-Replace
// dialog has the focus
if (editorState.isBlurred) return
const focusedSurface = editorState.focusedSurface
// console.log('focusedSurface', focusedSurface)
if (focusedSurface && !focusedSurface.isDisabled()) {
// console.log('Rendering selection on surface', focusedSurface.getId(), this.editorState.selection.toString())
focusedSurface._focus()
focusedSurface.rerenderDOMSelection()
} else {
// NOTE: Tried to add an integrity check here
// for valid sel.surfaceId
// However this is problematic, when an editor
// is run headless, i.e. when there are no surfaces rendered
// On the long run we should separate these to modes
// more explicitly. For now, any code using surfaces need
// to be aware of the fact, that this might be not availabls
// while in the model it is referenced.
}
}
_scrollSelectionIntoView () {
const editorState = this.editorState
const focusedSurface = editorState.focusedSurface
if (focusedSurface && !focusedSurface.isDisabled()) {
focusedSurface.send('scrollSelectionIntoView', editorState.selection)
}
}
}
|
JavaScript
| 0 |
@@ -3016,32 +3016,54 @@
Ranges()%0A
+ const activeElement =
window.document
@@ -3080,15 +3080,78 @@
ment
-.blur()
+%0A if (activeElement) %7B%0A activeElement.blur()%0A %7D
%0A
|
85ce486246d48ecd36079fa3f6a7503ce728995c
|
Add a dmmd-preview-stale css class when preview is stale; #444
|
resources/dmmd-preview.js
|
resources/dmmd-preview.js
|
$(function () {
window.register_dmmd_preview = function ($preview) {
var $update = $preview.find('.dmmd-preview-update');
var $content = $preview.find('.dmmd-preview-content');
var preview_url = $preview.attr('data-preview-url');
var $textarea = $('#' + $preview.attr('data-textarea-id'));
$update.click(function () {
var text = $textarea.val();
if (text) {
$.post(preview_url, {
preview: text,
csrfmiddlewaretoken: $.cookie('csrftoken')
}, function (result) {
$content.html(result);
$preview.addClass('dmmd-preview-has-content');
var $jax = $content.find('.require-mathjax-support');
if ($jax.length) {
if (!('MathJax' in window)) {
$.ajax({
type: 'GET',
url: $jax.attr('data-config'),
dataType: 'script',
cache: true,
success: function () {
$.ajax({
type: 'GET',
url: '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML',
dataType: 'script',
cache: true,
success: function () {
MathJax.Hub.Queue(function () {
$content.find('.tex-image').hide();
$content.find('.tex-text').show();
});
}
});
}
});
} else {
MathJax.Hub.Queue(['Typeset', MathJax.Hub, $content[0]], function () {
$content.find('.tex-image').hide();
$content.find('.tex-text').show();
});
}
}
});
} else {
$content.empty();
$preview.removeClass('dmmd-preview-has-content');
}
}).click();
var timeout = $preview.attr('data-timeout');
var last_event = null;
if (timeout) {
$textarea.on('keyup', function () {
if (last_event)
clearTimeout(last_event);
last_event = setTimeout(function () {
$update.click();
last_event = null;
}, timeout);
});
}
};
$('.dmmd-preview').each(function () {
register_dmmd_preview($(this));
});
if ('django' in window && 'jQuery' in window.django)
django.jQuery(document).on('formset:added', function(event, $row) {
var $preview = $row.find('.dmmd-preview');
if ($preview.length) {
var id = $row.attr('id');
id = id.substr(id.lastIndexOf('-') + 1);
$preview.attr('data-textarea-id', $preview.attr('data-textarea-id').replace('__prefix__', id));
register_dmmd_preview($preview);
}
});
});
|
JavaScript
| 0 |
@@ -703,16 +703,50 @@
ontent')
+.removeClass('dmmd-preview-stale')
;%0A%0A
@@ -2699,32 +2699,89 @@
, function () %7B%0A
+ $preview.addClass('dmmd-preview-stale');%0A
|
b8bfe8d5edb140b61ed03fae646fe7519d4700f4
|
modify view state of hydrator detail to hydrator++ detail view
|
cdap-ui/app/features/hydrator/services/create/actions/config-actions.js
|
cdap-ui/app/features/hydrator/services/create/actions/config-actions.js
|
/*
* Copyright © 2015 Cask Data, Inc.
*
* 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.
*/
class ConfigActionsFactory {
constructor(ConfigDispatcher, myPipelineApi, $state, ConfigStore, mySettings, ConsoleActionsFactory, EventPipe, myAppsApi, GLOBALS, myHelpers, $stateParams) {
this.ConfigStore = ConfigStore;
this.mySettings = mySettings;
this.$state = $state;
this.myPipelineApi = myPipelineApi;
this.ConsoleActionsFactory = ConsoleActionsFactory;
this.EventPipe = EventPipe;
this.myAppsApi = myAppsApi;
this.GLOBALS = GLOBALS;
this.myHelpers = myHelpers;
this.$stateParams = $stateParams;
this.dispatcher = ConfigDispatcher.getDispatcher();
}
initializeConfigStore(config) {
this.dispatcher.dispatch('onInitialize', config);
}
setMetadataInfo(name, description) {
this.dispatcher.dispatch('onMetadataInfoSave', name, description);
}
setDescription(description) {
this.dispatcher.dispatch('onDescriptionSave', description);
}
setConfig(config) {
this.dispatcher.dispatch('onConfigSave', config);
}
savePlugin(plugin, type) {
this.dispatcher.dispatch('onPluginSave', {plugin: plugin, type: type});
}
saveAsDraft(config) {
this.dispatcher.dispatch('onSaveAsDraft', config);
}
setArtifact(artifact) {
this.dispatcher.dispatch('onArtifactSave', artifact);
}
addPlugin (plugin, type) {
this.dispatcher.dispatch('onPluginAdd', plugin, type);
}
editPlugin(pluginId, pluginProperties) {
this.dispatcher.dispatch('onPluginEdit', pluginId, pluginProperties);
}
propagateSchemaDownStream(pluginId) {
this.dispatcher.dispatch('onSchemaPropagationDownStream', pluginId);
}
setSchedule(schedule) {
this.dispatcher.dispatch('onSetSchedule', schedule);
}
setInstance(instance) {
this.dispatcher.dispatch('onSetInstance', instance);
}
publishPipeline() {
this.ConsoleActionsFactory.resetMessages();
let error = this.ConfigStore.validateState(true);
if (!error) { return; }
this.EventPipe.emit('showLoadingIcon', 'Publishing Pipeline to CDAP');
let removeFromUserDrafts = (adapterName) => {
let draftId = this.ConfigStore.getState().__ui__.draftId;
this.mySettings
.get('hydratorDrafts', true)
.then(
(res) => {
var savedDraft = this.myHelpers.objectQuery(res, this.$stateParams.namespace, draftId);
if (savedDraft) {
delete res[this.$stateParams.namespace][draftId];
return this.mySettings.set('hydratorDrafts', res);
}
},
(err) => {
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: err
});
return this.$q.reject(false);
}
)
.then(
() => {
this.EventPipe.emit('hideLoadingIcon.immediate');
this.$state.go('hydrator.detail', { pipelineId: adapterName });
}
);
};
let publish = (pipelineName) => {
this.myPipelineApi.save(
{
namespace: this.$state.params.namespace,
pipeline: pipelineName
},
config
)
.$promise
.then(
removeFromUserDrafts.bind(this, pipelineName),
(err) => {
this.EventPipe.emit('hideLoadingIcon.immediate');
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: angular.isObject(err) ? err.data : err
});
}
);
};
var config = this.ConfigStore.getConfigForExport();
// Checking if Pipeline name already exist
this.myAppsApi
.list({ namespace: this.$state.params.namespace })
.$promise
.then( (apps) => {
var appNames = apps.map( (app) => { return app.name; } );
if (appNames.indexOf(config.name) !== -1) {
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: this.GLOBALS.en.hydrator.studio.error['NAME-ALREADY-EXISTS']
});
this.EventPipe.emit('hideLoadingIcon.immediate');
} else {
publish(config.name);
}
});
}
}
ConfigActionsFactory.$inject = ['ConfigDispatcher', 'myPipelineApi', '$state', 'ConfigStore', 'mySettings', 'ConsoleActionsFactory', 'EventPipe', 'myAppsApi', 'GLOBALS', 'myHelpers', '$stateParams'];
angular.module(`${PKG.name}.feature.hydrator`)
.service('ConfigActionsFactory', ConfigActionsFactory);
|
JavaScript
| 0 |
@@ -3430,16 +3430,24 @@
hydrator
+plusplus
.detail'
|
7618334db8a60b9c8f7f9ef71f5ed0cf5a0343f5
|
Use helper function for casting to string in PHP-compatible way
|
src/php/strings/substr.js
|
src/php/strings/substr.js
|
module.exports = function substr (str, start, len) {
// discuss at: https://locutus.io/php/substr/
// original by: Martijn Wieringa
// bugfixed by: T.Wild
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// revised by: Theriault (https://github.com/Theriault)
// note 1: Handles rare Unicode characters if 'unicode.semantics' ini (PHP6) is set to 'on'
// example 1: substr('abcdef', 0, -1)
// returns 1: 'abcde'
// example 2: substr(2, 0, -6)
// returns 2: false
// example 3: ini_set('unicode.semantics', 'on')
// example 3: substr('a\uD801\uDC00', 0, -1)
// returns 3: 'a'
// example 4: ini_set('unicode.semantics', 'on')
// example 4: substr('a\uD801\uDC00', 0, 2)
// returns 4: 'a\uD801\uDC00'
// example 5: ini_set('unicode.semantics', 'on')
// example 5: substr('a\uD801\uDC00', -1, 1)
// returns 5: '\uD801\uDC00'
// example 6: ini_set('unicode.semantics', 'on')
// example 6: substr('a\uD801\uDC00z\uD801\uDC00', -3, 2)
// returns 6: '\uD801\uDC00z'
// example 7: ini_set('unicode.semantics', 'on')
// example 7: substr('a\uD801\uDC00z\uD801\uDC00', -3, -1)
// returns 7: '\uD801\uDC00z'
// test: skip-3 skip-4 skip-5 skip-6 skip-7
str += ''
var end = str.length
var ini_get = require('../info/ini_get')
var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/
var multibyte = ini_get('unicode.semantics') === 'on' && surrogatePair.test(str)
if (!multibyte) {
// assumes there are no non-BMP characters;
// if there may be such characters, then it is best to turn it on (critical in true XHTML/XML)
if (start < 0) {
start += end
}
if (typeof len !== 'undefined') {
if (len < 0) {
end = len + end
} else {
end = len + start
}
}
// PHP returns false if start does not fall within the string.
// PHP returns false if the calculated end comes before the calculated start.
// PHP returns an empty string if start and end are the same.
// Otherwise, PHP returns the portion of the string from start to end.
if (start >= str.length || start < 0 || start > end) {
return false
}
return str.slice(start, end)
}
// Full-blown Unicode including non-Basic-Multilingual-Plane characters
var i = 0
var es = 0
var el = 0
var se = 0
var ret = ''
if (start < 0) {
for (i = end - 1, es = (start += end); i >= es; i--) {
if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
start--
es--
}
}
} else {
var surrogatePairs = RegExp(surrogatePair.source, 'g')
while ((surrogatePairs.exec(str)) !== null) {
var li = surrogatePairs.lastIndex
if (li - 2 < start) {
start++
} else {
break
}
}
}
if (start >= end || start < 0) {
return false
}
if (len < 0) {
for (i = end - 1, el = (end += len); i >= el; i--) {
if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
end--
el--
}
}
if (start > end) {
return false
}
return str.slice(start, end)
} else {
se = start + len
for (i = start; i < se; i++) {
ret += str.charAt(i)
if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
// Go one further, since one of the "characters" is part of a surrogate pair
se++
}
}
return ret
}
}
|
JavaScript
| 0 |
@@ -1313,17 +1313,133 @@
%0A%0A
-str += ''
+var _php_cast_string = require('../_helpers/_phpCastString') // eslint-disable-line camelcase%0A%0A str = _php_cast_string(str)%0A
%0A v
@@ -1500,16 +1500,49 @@
ni_get')
+ // eslint-disable-line camelcase
%0A var s
|
cf4e24496e311fae6ce7fbd6fa68518d4804a0e0
|
Fix home link
|
lib/share/components/header.js
|
lib/share/components/header.js
|
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import styles from './header.css'
export default class Header extends Component {
static propTypes = {
loginUser: PropTypes.string.isRequired,
}
static defaultProps = {
loginUser: 'DUMMY_USER',
}
render = () => {
const { loginUser } = this.props
return (
<div className={styles.container}>
<div className={styles.innerContainer}>
<div className={styles.headerLogo}>
<a href="#">logo</a>
</div>
<form className={styles.headerForm}>
<label htmlFor="input-search-query">
This repository
</label>
<input
id="input-search-query"
type="text"
placeholder="Search"
/>
</form>
<nav className={styles.headerNavLeft}>
<ul>
<li>
<Link to="/pulls">Pull requests</Link>
</li>
<li>
<Link to="/issues">Issues</Link>
</li>
</ul>
</nav>
<nav className={styles.headerNavRight}>
<ul className={styles.otherClassName}>
<li>
<Link to="/notifications">Notifications</Link>
</li>
<li>
<Link to="/new">New</Link>
</li>
<li>
<Link to={`/${loginUser}`}>Sign in as {loginUser}</Link>
</li>
</ul>
</nav>
</div>
</div>
)
}
}
|
JavaScript
| 0.000001 |
@@ -518,25 +518,26 @@
%3C
-a href=%22#
+Link to=%22/
%22%3Elogo%3C/
a%3E%0A
@@ -532,17 +532,20 @@
%22%3Elogo%3C/
-a
+Link
%3E%0A
|
a4699ace30729f44e5312b19fd4aae96221f451e
|
add init function
|
src/sap/a/map/MapView.js
|
src/sap/a/map/MapView.js
|
import View from "../view/View";
export default class MapView extends View
{
metadata = {
properties: {
defaultCenterLocation: {
type: "object",
defaultValue: [ 32.04389, 118.77881 ]
},
defaultZoom: {
type: "int",
defaultValue: 15
},
minZoom: {
type: "int",
defaultValue: 11
},
maxZoom: {
type: "int",
defaultValue: 17
},
allowZoom: {
type: "boolean",
defaultValue: true
},
allowDrag: {
type: "boolean",
defaultValue: true
}
}
};
init()
{
super.init();
this.addStyleClass("sap-a-map-view");
this._initMap();
this.attachAddedToParent(() => {
setTimeout(() => {
this.invalidateSize();
});
});
}
_initMap()
{
const options = {
zoomControl: false,
attributionControl: false,
center: this.getDefaultCenterLocation(),
zoom: this.getDefaultZoom(),
minZoom: this.getMinZoom(),
maxZoom: this.getMaxZoom(),
dragging: this.getAllowDrag(),
scrollWheelZoom: this.getAllowZoom(),
doubleClickZoom: this.getAllowZoom()
};
this.map = L.map(this.$element[0], options);
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png").addTo(this.map);
}
invalidateSize(...args)
{
this.map.invalidateSize(...args);
}
}
|
JavaScript
| 0.000011 |
@@ -822,28 +822,27 @@
oomControl:
-fals
+tru
e,%0A%09%09%09attrib
@@ -1175,24 +1175,24 @@
, options);%0A
-
L.ti
@@ -1262,24 +1262,483 @@
ap);%0A %7D%0A%0A
+ getCenterLocation()%0A %7B%0A return this.getCenterLocation();%0A %7D%0A%0A setCenterLocation(centerLocation, zoom, options)%0A %7B%0A this.map.setView(centerLocation, zoom, options);%0A %7D%0A%0A getBounds()%0A %7B%0A return this.map.getBounds();%0A %7D%0A%0A setBounds(bounds)%0A %7B%0A this.map.fitBounds(bounds);%0A %7D%0A%0A getZoom()%0A %7B%0A return this.map.getZoom();%0A %7D%0A%0A setZoom(zoom)%0A %7B%0A this.map.setZoom();%0A %7D%0A%0A
invalida
|
eb55162b6efb8bd3b70d4fdcdb793c9a9a5d2566
|
take care of undefined case
|
src/schema/schemautil.js
|
src/schema/schemautil.js
|
'use strict';
var schemautil = module.exports = {},
util = require('../util');
var isEmpty = function(obj) {
return Object.keys(obj).length === 0;
};
schemautil.extend = function(instance, schema) {
return schemautil.merge(schemautil.instantiate(schema), instance);
};
// instantiate a schema
schemautil.instantiate = function(schema) {
var val;
if ('default' in schema) {
val = schema.default;
return util.isObject(val) ? util.duplicate(val) : val;
} else if (schema.type === 'object') {
var instance = {};
for (var name in schema.properties) {
val = schemautil.instantiate(schema.properties[name]);
if (val !== undefined) {
instance[name] = val;
}
}
return instance;
} else if (schema.type === 'array') {
return [];
}
return undefined;
};
// remove all defaults from an instance
schemautil.subtract = function(instance, defaults) {
var changes = {};
for (var prop in instance) {
var def = defaults[prop];
var ins = instance[prop];
// Note: does not properly subtract arrays
if (!defaults || def !== ins) {
if (typeof ins === 'object' && !util.isArray(ins) && def) {
var c = schemautil.subtract(ins, def);
if (!isEmpty(c))
changes[prop] = c;
} else if (!util.isArray(ins) || ins.length > 0) {
changes[prop] = ins;
}
}
}
return changes;
};
schemautil.merge = function(/*dest*, src0, src1, ...*/){
var dest = arguments[0];
for (var i=1 ; i<arguments.length; i++) {
dest = merge(dest, arguments[i]);
}
return dest;
};
// recursively merges src into dest
function merge(dest, src) {
if (typeof src !== 'object' || src === null) {
return dest;
}
for (var p in src) {
if (!src.hasOwnProperty(p)) {
continue;
}
if (src[p] === undefined) {
continue;
}
if (typeof src[p] !== 'object' || src[p] === null) {
dest[p] = src[p];
} else if (typeof dest[p] !== 'object' || dest[p] === null) {
dest[p] = merge(src[p].constructor === Array ? [] : {}, src[p]);
} else {
merge(dest[p], src[p]);
}
}
return dest;
}
|
JavaScript
| 0.998391 |
@@ -356,16 +356,75 @@
l;%0A if
+(schema === undefined) %7B%0A return undefined;%0A %7D else if
('defaul
|
837ec45e8c8e5716f979e86550cdeb010fca678a
|
Add modules selector
|
src/selectors/modules.js
|
src/selectors/modules.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
export const selectUsingSupplierCredits = ({ modules }) => {
const { usingSupplierCredits } = modules;
return usingSupplierCredits;
};
|
JavaScript
| 0.000001 |
@@ -199,8 +199,127 @@
its;%0A%7D;%0A
+%0Aexport const selectUsingPayments = (%7B modules %7D) =%3E %7B%0A const %7B usingPayments %7D = modules;%0A return usingPayments;%0A%7D;%0A
|
34a5f915a1adb82fc50123b142df8002f1424761
|
move summaryLocaleData to inner func
|
src/server/i18n/index.js
|
src/server/i18n/index.js
|
// @flow
import {readFileSync} from 'fs' // readFile
import path from 'path'
import {sync as globSync} from 'glob'
// import {addLocaleData} from 'react-intl'
import enLocaleData from 'react-intl/locale-data/en'
import ruLocaleData from 'react-intl/locale-data/ru'
import type {i18nConfigObject} from 'types'
const translations = globSync('locals/*.json')
.map((filename: string) => [
path.basename(filename, '.json'),
readFileSync(filename, 'utf8')
])
.map(([locale, file]) => [locale, JSON.parse(file)])
.reduce((acc, [locale, messages]) => {
acc[locale] = messages
return acc
}, {})
const summaryLocaleData = {
en: enLocaleData,
ru: ruLocaleData
}
export const defaultLanguage = 'en'
export const supportedLanguages = ['en', 'ru']
export default (lang: string): i18nConfigObject => {
console.log(lang)
return {
lang,
localeData: summaryLocaleData[lang],
locale: lang,
messages: translations[lang]
}
}
|
JavaScript
| 0.000003 |
@@ -598,76 +598,8 @@
%7D)%0A%0A
-const summaryLocaleData = %7B%0A%09en: enLocaleData,%0A%09ru: ruLocaleData%0A%7D%0A%0A
expo
@@ -706,16 +706,34 @@
: string
+ = defaultLanguage
): i18nC
@@ -758,21 +758,73 @@
cons
-ole.log(lang)
+t summaryLocaleData = %7B%0A%09%09en: enLocaleData,%0A%09%09ru: ruLocaleData%0A%09%7D
%0A%09re
|
38344f76cdad6016a6c396555d66f946439424f0
|
fix lint
|
src/service/api/index.js
|
src/service/api/index.js
|
import {isEqual} from 'lodash'
import Action from '../../action'
import {http, websocket} from './network'
import Codec from './codec'
export default function API(getState, dispatch, next) {
return {
async fetchUser() {
const user = await http('GET', '/api/user/userinfo')
next(Action.User.profile.create(
Codec.User.decode(user)
))
},
async fetchPlaylist() {
const state = getState()
const sync = state.user.preferences.sync
if (!sync) return
const urls = sync.split('\n').filter(line => line)
if (!urls.length) return
const lists = await Promise.all(urls.map(url =>
http('POST', '/provider/songListWithUrl', {
url,
withCookie: state.user.preferences.cookie
})
))
const songs = [].concat(...lists.map(list => list.songs || []))
next(Action.Song.assign.create(
songs.map(Codec.Song.decode)
))
},
async sendChannel(prevState) {
const state = getState()
const channel = state.channel.name
if (!channel) return
const prevChannel = prevState && prevState.channel.name
if (channel == prevChannel) return
await http('POST', `/api/channel/join/${channel}`)
},
async sendUpnext(prevState) {
const state = getState()
if (!state.channel.name) return
const song = Codec.Song.encode(
state.user.preferences.listenOnly
? undefined
: state.song.playlist[0]
)
const prevSong = Codec.Song.encode(prevState && (
prevState.user.preferences.listenOnly
? undefined
: prevState.song.playlist[0]
))
if (prevState && isEqual(song, prevSong)) return
await http('POST', `/api/channel/updateNextSong`, {
...song,
withCookie: state.user.preferences.cookie
})
},
async sendSync() {
const state = getState()
if (!state.channel.name) return
const song = Codec.Song.encode(state.song.playing)
await http('POST', `/api/channel/finished`,
song.songId ? song : null
)
},
async sendDownvote() {
const state = getState()
if (!state.channel.name) return
const song = Codec.Song.encode(state.song.playing)
await http('POST', `/api/channel/downVote`,
song.songId ? song : null
)
},
async sendSearch() {
const state = getState()
const keyword = state.search.keyword
if (keyword) {
const results = await http('POST', '/provider/searchSongs', {
key: keyword,
withCookie: state.user.preferences.cookie
})
next(Action.Search.results.create(
results.map(Codec.Song.decode)
))
} else {
next(Action.Search.results.create([]))
}
},
receiveMessage(callback) {
websocket('/api/ws', ({connect, send}) => async (event, data) => {
switch (event) {
case 'open':
callback(event)
break
case 'close':
setTimeout(connect, 5000)
callback(event)
break
case 'error':
callback(event)
break
case 'UserListUpdated':
next(Action.Channel.members.create(
data.users.map(Codec.User.decode)
))
break
case 'Play':
next(Action.Player.reset.create())
if (data.downvote) {
next(Action.Player.downvote.create())
}
next(Action.Song.play.create(data.song && {
...Codec.Song.decode(data.song),
player: data.user || '',
time: (Date.now() / 1000) - (data.elapsed || 0)
}))
break
case 'NextSongUpdate':
next(Action.Song.preload.create(data.song && {
...Codec.Song.decode(data.song)
}))
break
}
})
}
}
}
|
JavaScript
| 0.000013 |
@@ -1743,33 +1743,33 @@
it http('POST',
-%60
+'
/api/channel/upd
@@ -1779,17 +1779,17 @@
NextSong
-%60
+'
, %7B%0A
@@ -2034,33 +2034,33 @@
it http('POST',
-%60
+'
/api/channel/fin
@@ -2064,17 +2064,17 @@
finished
-%60
+'
,%0A
@@ -2287,33 +2287,33 @@
it http('POST',
-%60
+'
/api/channel/dow
@@ -2317,17 +2317,17 @@
downVote
-%60
+'
,%0A
|
468f293ee61b6941a917a433a2b092f8bb327404
|
fix modalStore bug
|
src/stores/modalStore.js
|
src/stores/modalStore.js
|
import { computed, observable, action } from 'mobx';
import { omitBy, reduce } from 'lodash';
class ModalStore {
@observable modalProps = {};
@observable state = {};
_prefix = '__';
getOmitPaths = (val, key) => {
return key.startsWith(this._prefix);
};
@computed
get name() {
return this.state.name;
}
@computed
get visible() {
return !!this.name;
}
close() {
this._clearLocation();
}
@action
setState(state, useLocation) {
if (useLocation) {
this._setLocation(state);
} else {
this.state = state;
}
}
@action
setModalProps(props) {
const ensureNumber = function ensureNumber(propName) {
const val = props[propName];
if (val && /^\d+$/.test(val)) {
props[propName] = +val;
}
};
const ensureBoolean = function ensureBoolean(propName) {
if (!props.hasOwnProperty(propName)) {
return;
}
const val = props[propName];
if (val === 'false' || val === 'no') {
props[propName] = false;
} else if (val) {
props[propName] = true;
}
};
ensureNumber('width');
ensureNumber('zIndex');
ensureBoolean('closable');
ensureBoolean('confirmLoading');
ensureBoolean('mask');
ensureBoolean('maskClosable');
this.modalProps = props;
}
bindRouter(router) {
if (this._router) {
return;
}
router.history.listen(({ query }) => {
const prefixLength = this._prefix.length;
this.state = reduce(
query,
(state, val, key) => {
if (key.startsWith(this._prefix)) {
const stateKey = key.substr(prefixLength);
state[stateKey] = val;
}
return state;
},
{}
);
});
this._setLocation = (state) => {
const modalQuery = reduce(
state,
(query, val, key) => {
query[`${this._prefix}${key}`] = val;
return query;
},
{}
);
const { location } = router;
location.query = { ...location.query, ...modalQuery };
};
this._clearLocation = () => {
const { location } = router;
location.query = omitBy(location.query, (val, key) =>
key.startsWith(this._prefix)
);
};
}
}
export default new ModalStore();
|
JavaScript
| 0 |
@@ -1281,32 +1281,37 @@
%09%09%7D%0A
+%0A
%09%09
-router.history.listen(
+const handleQueryChange =
(%7B q
@@ -1598,16 +1598,98 @@
%09%09);%0A%09%09%7D
+;%0A%0A%09%09router.history.listen(handleQueryChange);%0A%09%09handleQueryChange(router.location
);%0A%0A%09%09th
|
3f88bd2db871a8ecdf707d1fbccc98e034bc0a78
|
Remove dependency on react-native-match-media
|
src/styles/animations.js
|
src/styles/animations.js
|
import { Animated, Easing } from 'react-native-universal'
import matchMedia from 'react-native-match-media'
import { Breakpoints } from './Grid'
export const Curves = {
standard: Easing.bezier(0.4, 0, 0.2, 1),
deceleration: Easing.bezier(0, 0, 0.2, 1),
acceleration: Easing.bezier(0.4, 0, 1, 1),
sharp: Easing.bezier(0.4, 0, 0.6, 1),
}
// MD spec only specifies a range of durations for desktop, so I created a function
// to interpolate the desktop value from the mobile value.
//
// 150 is the shortest desktop duration
// 0.28 is desktop ms per mobile ms, or
// (longest desktop - shortest desktop) / (longest mobile - shortest mobile)
// or (200 - 150) / (375 - 195)
// 195 is the shortest mobile duration
const interpolateDesktopValue = from => 150 + (0.28 * (from - 195))
// Creates a function that calculates the duration value for different screen
// sizes
// The resulting function accepts an "add" parameter that gets added to the value
// before interpolation
const getResponsiveDurationFn = value => () => {
const desktopMediaQuery = Breakpoints.ml.split('@media')[1]
const tabletMediaQuery = Breakpoints.md.split('@media')[1]
// Desktop, not in MD spec so I interpolated it
if (matchMedia(desktopMediaQuery).matches) return interpolateDesktopValue(value)
// Tablet, according to MD spec 30% longer than mobile
if (matchMedia(tabletMediaQuery).matches) return value * 1.3
// Mobile
return value
}
export const Durations = {
standard: getResponsiveDurationFn(300),
large: getResponsiveDurationFn(375),
entering: getResponsiveDurationFn(225),
leaving: getResponsiveDurationFn(195),
custom: getResponsiveDurationFn,
}
const Animations = {
standard: (av, toValue = 1, duration) => Animated.timing(av, {
duration: duration ? Durations.custom(duration)() : Durations.standard(),
easing: Curves.standard,
toValue,
}),
large: (av, toValue = 1, duration) => Animated.timing(av, {
duration: duration ? Durations.custom(duration)() : Durations.large(),
easing: Curves.standard,
toValue,
}),
entrance: (av, toValue = 1, duration) => Animated.timing(av, {
duration: duration ? Durations.custom(duration)() : Durations.entering(),
easing: Curves.deceleration,
toValue,
}),
exit: (av, toValue = 1, duration) => Animated.timing(av, {
duration: duration ? Durations.custom(duration)() : Durations.leaving(),
easing: Curves.acceleration,
toValue,
}),
tempExit: (av, toValue = 1, duration) => Animated.timing(av, {
duration: duration ? Durations.custom(duration)() : Durations.leaving(),
easing: Curves.sharp,
toValue,
}),
staggered: (av, staggerAV, toValue = 1, staggerAmount = 50) =>
Animated.stagger(staggerAmount, [
Animated.timing(toValue ? av : staggerAV, {
duration: Durations.custom(300 - staggerAmount)(),
easing: Curves.standard,
toValue,
}),
Animated.timing(toValue ? staggerAV : av, {
duration: Durations.custom(300 - staggerAmount)(),
easing: Curves.standard,
delay: Durations.custom(staggerAmount)(),
toValue,
}),
]),
}
export default Animations
|
JavaScript
| 0.000262 |
@@ -54,58 +54,8 @@
sal'
-%0Aimport matchMedia from 'react-native-match-media'
%0A%0Aim
@@ -1150,24 +1150,31 @@
ed it%0A if (
+global.
matchMedia(d
@@ -1301,16 +1301,23 @@
e%0A if (
+global.
matchMed
|
7f76491d8ce204ae70b4f9af2290bb6789842b11
|
Remove beforeunload event on component destroyed.
|
resources/assets/js/mixins/promptToSaveMixin.js
|
resources/assets/js/mixins/promptToSaveMixin.js
|
/**
* Mixin to display a suitable modal dialog to either allow navigating away from a page with unsaved changes
* or to cancel and stay on that page.
*
* The component using this mixin MUST:
* - Be a route-level component (used as part of a route) as the beforeRoute* callbacks only get called for these components.
* - Override the isUnsaved() computed property to return true or false depending on whether they have unsaved changes.
*
* The component using this mixin MAY:
* - Modify the dialog box title, message and button texts and type by specifying the relevant attributes in its own data
* - Use any method to determine what counts as unsaved(). One example strategy is:
* - Ensure the component isn't in its initialisation / loading state
* - JSON.stringify() the relevant data on initial load and on saving
* - Compare this with the JSON.stringify() version of the current version of the data
*/
export default {
beforeRouteLeave(to, from, next) {
this.promptToSave(next);
},
beforeRouteUpdate(to, from, next) {
this.promptToSave(next);
},
created() {
window.addEventListener('beforeunload', this.promptToSaveWindow);
},
data() {
return {
// override any of these in the component using this mixin's data() to modify the prompt messages
// vue only does a shallow merge https://vuejs.org/v2/guide/mixins.html#Option-Merging
savePromptTitle: 'Are you sure you want to leave?',
savePromptMessage: 'There are unsaved changes',
savePromptConfirmButtonText: 'OK',
savePromptCancelButtonText: 'Cancel',
savePromptType: 'warning'
};
},
computed: {
/**
* Override this wherever you use this mixin
* @returns {boolean}
*/
isUnsaved() {
return false;
}
},
methods: {
promptToSaveWindow(e) {
/* we are very limited as to what we can do when someone tries to leave
https://developer.mozilla.org/en/docs/Web/Events/beforeunload
*/
if (this.isUnsaved) {
const confirmationMessage = this.savePromptTitle + "\n\n" + this.savePromptMessage;
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
}
},
promptToSave(callback) {
if(this.isUnsaved) {
return this.$confirm(
this.savePromptMessage,
this.savePromptTitle,
{
confirmButtonText: this.savePromptConfirmButtonText,
cancelButtonText: this.savePromptCancelButtonText,
type: this.savePromptType
}
).then(() => {
if(callback) {
callback(true);
}
}).catch(() => {
if(callback) {
callback(false);
}
});
}
callback(true);
return true;
}
}
};
|
JavaScript
| 0 |
@@ -1160,16 +1160,107 @@
);%0A%09%7D,%0A%0A
+%09destroyed() %7B%0A%09%09window.removeEventListener('beforeunload', this.promptToSaveWindow);%0A%09%7D,%0A%0A
%09data()
|
b60a455efb11c65a2654fa23f7bec6bc929449d9
|
add help text to counter field
|
client/mobrender/widgets/adjustments/component.js
|
client/mobrender/widgets/adjustments/component.js
|
/**
* AdjustmentsForm
*
* Um componente para para submeter formulários de ajustes de widgets.
*/
import React from 'react'
import PropTypes from 'prop-types'
import {
FormGroup,
ControlLabel,
FormControl,
ColorPicker,
HelpBlock
} from '~client/components/forms'
import { SettingsForm } from '~client/ux/components'
const AdjustmentsSettingsForm = (props) => {
const {
children,
fields: {
call_to_action: callToAction,
button_text: buttonText,
count_text: countText,
main_color: mainColor
},
widget,
asyncWidgetUpdate,
// TODO: Remover essa dependencia da mobilização
dispatch,
colorScheme,
...formProps
} = props
return (
<SettingsForm
{...formProps}
onSubmit={values => {
const settings = widget.settings || {}
return asyncWidgetUpdate({
...widget,
settings: { ...settings, ...values }
})
}}
successMessage='Formulário configurado com sucesso!'
>
<FormGroup controlId='call-to-action-id' {...callToAction}>
<ControlLabel>Título do formulário</ControlLabel>
<FormControl
type='text'
placeholder='Ex: Preencha o formulário abaixo para assinar a petição.'
/>
</FormGroup>
<FormGroup controlId='button-text-id' {...buttonText}>
<ControlLabel>Botão</ControlLabel>
<FormControl
type='text'
placeholder='Defina o texto do botão de confirmação do formulário.'
/>
</FormGroup>
<FormGroup controlId='count-text-id' {...countText}>
<ControlLabel>Contador</ControlLabel>
<FormControl
type='text'
placeholder='Defina o texto que ficará ao lado do número de pessoas que agiram.'
/>
</FormGroup>
<FormGroup controlId='main-color-id' {...mainColor}>
<ControlLabel>Cor padrão</ControlLabel>
<HelpBlock>
Selecione a cor no box abaixo ou insira o valor em hex, por exemplo: #DC3DCE.
</HelpBlock>
<ColorPicker
dispatch={dispatch}
theme={colorScheme.replace('-scheme', '')}
/>
</FormGroup>
{children}
</SettingsForm>
)
}
AdjustmentsSettingsForm.propTypes = {
// Injected by redux-form
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired,
error: PropTypes.string,
// Injected by widgets/models/ModelForm
colorScheme: PropTypes.string,
// Injected by container
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
asyncWidgetUpdate: PropTypes.func.isRequired
}
export default AdjustmentsSettingsForm
|
JavaScript
| 0.000001 |
@@ -1774,32 +1774,118 @@
am.'%0A /%3E%0A
+ %3CHelpBlock%3EO contador ser%C3%A1 mostrado se existir um texto definido.%3C/HelpBlock%3E%0A
%3C/FormGrou
|
1a865895e8582181cf4820fbab1f90af681f285d
|
fix ground position
|
client/pages/examples/threejs/collisions/index.js
|
client/pages/examples/threejs/collisions/index.js
|
import React from 'react'
import * as THREE from 'three'
import * as OIMO from 'oimo'
import Example from '-/components/example'
import notes from './readme.md'
let rand = Math.random
const init = ({ canvas, container }) => {
let renderer = new THREE.WebGLRenderer({ canvas })
let scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(
75,
container.clientWidth / container.clientWidth,
0.1,
1000
)
camera.position.z = 10
camera.position.y = 5
const randInt = () =>{
return Math.floor(Math.random() * 10);
}
let world = new OIMO.World({
timestep: 1/30,
iterations: 8,
broadphase: 2, // 1: brute force, 2: sweep & prune, 3: volume tree
worldscale: 1,
random: true,
info:true,
gravity: [0,-9.8,0]
});
let ground = world.add({size:[50, 10, 50], pos:[0,0,0], density:1 });
var size = 1000;
var divisions = 1000;
var gridHelper = new THREE.GridHelper( size, divisions );
scene.add( gridHelper );
gridHelper.position.copy(ground.getPosition())
renderer.setSize(container.clientWidth, container.clientWidth)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshLambertMaterial({ color: 0xaaff00 })
const cube = new THREE.Mesh(geometry, material)
//scene.add(cube)
const light = new THREE.PointLight(0xffffff, 1, 100)
light.position.set(0, 3, 5)
scene.add(light)
let body1 = world.add({
type:'sphere', // type of shape : sphere, box, cylinder
size:[1,1,1], // size of shape
pos:[0,0,0], // start position in degree
rot:[0,0,90], // start rotation in degree
move:true, // dynamic or statique
density: 1,
friction: 0.2,
restitution: 0.2,
belongsTo: 1, // The bits of the collision groups to which the shape belongs.
collidesWith: 0xffffffff // The bits of the collision groups with which the shape collides.
});
world.step();
const sphere = new THREE.IcosahedronBufferGeometry(1, 1)
//hand.scale(0.2, 0.8, 1.5)
const spheremesh = new THREE.Mesh(
sphere,
new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff })
)
scene.add(spheremesh)
const animate = () => {
spheremesh.position.copy(body1.getPosition())
spheremesh.quaternion.copy( body1.getQuaternion() )
//cube.rotation.x += 0.01
//cube.rotation.y += 0.01
if (renderer) {
requestAnimationFrame(animate)
renderer.render(scene, camera)
}
}
world.postLoop = animate
world.play();
//animate()
return () => {
renderer.dispose()
scene.dispose()
scene = null
renderer = null
}
}
const Collisions = () => <Example notes={notes} init={init} />
export default React.memo(Collisions)
|
JavaScript
| 0.00004 |
@@ -813,18 +813,20 @@
ze:%5B50,
-1
0
+.01
, 50%5D, p
@@ -959,338 +959,179 @@
);%0A
+%0A
-scene.add( gridHelper );%0A gridHelper.position.copy(ground.getPosition())%0A%0A renderer.setSize(container.clientWidth, container.clientWidth)%0A const geometry = new THREE.BoxGeometry(1, 1, 1)%0A const material = new THREE.MeshLambertMaterial(%7B color: 0xaaff00 %7D)%0A const cube = new THREE.Mesh(geometry, material)%0A //scene.add(cube
+gridHelper.position.x=0%0A gridHelper.position.y=0%0A gridHelper.position.z=0%0A%0A scene.add( gridHelper );%0A%0A renderer.setSize(container.clientWidth, container.clientWidth
)%0A%0A
@@ -1368,24 +1368,25 @@
pos:%5B0,
+1
0,0%5D, // sta
@@ -1422,17 +1422,16 @@
ot:%5B0,0,
-9
0%5D, // s
|
fc124c21ebb31449d2e8f755a7b10e28c4e5bd13
|
Update index.js
|
apps/robot/index.js
|
apps/robot/index.js
|
'use strict';
module.change_code = 1;
var alexa = require("alexa-app");
var gcm = require("node-gcm");
var app = new alexa.app("robot");
const gcmServerKey = process.env.GCM_SERVER_KEY;
const registrationToken = process.env.REGISTRATION_TOKEN;
var sender = new gcm.Sender(gcmServerKey);
var registrationTokens = [registrationToken];
var n = ["north", "forward", "up"];
var ne = ["north east"];
var e = ["east", "right"];
var se = ["south east"];
var s = ["south", "back", "backward", "reverse", "down"];
var sw = ["south west"];
var w = ["west", "left"];
var nw = ["north west"];
// index is a code
var directionsCodes = [n, ne, e, se, s, sw, w, nw];
var directions = [].concat.apply([], directionsCodes);
function directionToCode(direction) {
for (var i = 0; i < directionsCodes.length; i++) {
for (var j = 0; j < directionsCodes[i].length; j++) {
if (directionsCodes[i][j] == direction) {
return i;
}
}
}
return -1;
}
var lightsCode = 9;
app.dictionary = {
"directions": directions
};
app.launch(function(request, response) {
response.shouldEndSession(false);
console.log("Session started");
response.say("Welcome to marks control service");
});
app.sessionEnded(function(request, response) {
console.log("Session ended");
});
app.intent("RobotLightsIntent", {
"utterances": [
"{toggle|switch|} lights"
// "red on",
]
},
function(request, response)
{
response.shouldEndSession(false);
// var message = new gcm.Message({
// data: { code: lightsCode }
// });
// sender.send(message, { registrationTokens: registrationTokens }, function (err, data)
// {
// if (err) {
// console.error(err);
// response.say("Sorry, there was an unexpected error. Could not send message to robot.");
// }
// else
// {
console.log(data);
response.say("Turning red light on");
//}
//response.send();
// });
// return false;
}
);
app.intent("RobotStatsIntent", {
"utterances": [
"{tell|give|say} {me|} stats",
]
},
function(request, response)
{
response.shouldEndSession(false);
if (request.hasSession())
{
var session = request.getSession();
console.log(session.details.attributes);
var stats = "";
for (var key in session.details.attributes)
{
var counter = session.get(key);
stats += ", " + key + " " + counter;
}
if (stats.length > 0)
{
response.say("The stats are " + stats);
}
else
{
response.say("No moves, yet");
}
}
else
{
response.say("Sorry, session is not active, no stats are available");
}
}
);
app.intent("RobotStopIntent", {
"utterances": [
"{exit|quit|stop|end|bye}",
]
},
function(request, response) {
response.say("It was a real pleasure talking to you. Have a good day!");
}
);
module.exports = app;
|
JavaScript
| 0.000002 |
@@ -1336,16 +1336,18 @@
%22: %5B%0A
+//
%22%7Btoggl
@@ -1369,19 +1369,16 @@
ts%22%0A
- //
%22red on
@@ -1927,32 +1927,34 @@
// %7B%0A
+//
console.log(da
@@ -1994,16 +1994,22 @@
ing red
+L E D
light on
|
8d3a9180086e7eed5c6059c3a841ab6678366586
|
Remove unused function.
|
compassion.counterfeiter/counterfeiter.generic.js
|
compassion.counterfeiter/counterfeiter.generic.js
|
module.exports = function (Colleague, Conduit) {
var cadence = require('cadence')
var abend = require('abend')
var Destructor = require('destructible')
var Colleague = require('../compassion.colleague/colleague')
var Kibitzer = require('kibitz')
var Conduit = require('../compassion.conduit/conduit')
var Vizsla = require('vizsla')
var Signal = require('signal')
var Procession = require('procession')
var Recorder = require('./recorder')
var interrupt = require('interrupt').createInterrupter('compassion.counterfeiter')
function Counterfeiter (address, port) {
this._colleagues = {}
// TODO Getting silly, just expose Denizen.
this.events = {}
this.kibitzers = {}
this.loggers = {}
this._port = port
this._address = address
this._destructible = new Destructor('counterfeiter')
this._destructible.markDestroyed(this, 'destroyed')
}
Counterfeiter.prototype._run = cadence(function (async, options) {
interrupt.assert(!this.destroyed, 'destroyed', {}, this._destructible.errors[0])
var kibitzer = this.kibitzer = new Kibitzer({ id: options.id, ping: 1000, timeout: 3000 })
var colleague = new Colleague(new Vizsla, kibitzer, null, 'island')
this._colleagues[options.id] = colleague
this.kibitzers[options.id] = colleague.kibitzer
this.events[options.id] = colleague.kibitzer.log.shifter()
this._destructible.addDestructor([ 'colleague', options.id ], colleague, 'destroy')
// Create loggers suitable for replaying.
var logger = new Procession
kibitzer.played.shifter().pump(new Recorder('kibitz', logger), 'push')
kibitzer.paxos.outbox.shifter().pump(new Recorder('paxos', logger), 'push')
kibitzer.islander.outbox.shifter().pump(new Recorder('islander', logger), 'push')
colleague.chatter.shifter().pump(new Recorder('colleague', logger), 'push')
this._destructible.addDestructor([ 'logger', options.id ], logger, 'push')
this.loggers[options.id] = logger.shifter()
// Connect colleague directly to conference.
colleague.read.shifter().pump(options.conference.write, 'enqueue')
options.conference.read.shifter().pump(colleague.write, 'enqueue')
// Start colleague.
var ready = new Signal
ready.wait(function () {
console.log('wait wait', arguments)
})
colleague.ready.wait(ready, 'unlatch')
colleague.listen(this._address, this._port, this._destructible.rescue([ 'colleague', options.id ], ready, 'unlatch'))
ready.wait(async())
})
Counterfeiter.prototype.bootstrap = cadence(function (async, options) {
async(function () {
this._run(options, async())
}, function (colleague) {
this._colleagues[options.id].bootstrap(async())
}, function () {
console.log('done')
})
})
Counterfeiter.prototype.join = cadence(function (async, options) {
async(function () {
this._run(options, async())
}, function (colleague) {
this._colleagues[options.id].join(options.republic, options.leader, async())
}, function () {
console.log('done')
})
})
Counterfeiter.prototype._join = cadence(function (async, options) {
interrupt.assert(!this.destroyed, 'destroyed', this._destructible.errors[0])
// TODO Fold UserAgent into Counterfeiter.
var denizen = this._denizens[options.id] = new Denizen(this, options, new UserAgent(this))
this.kibitzers[options.id] = denizen.kibitzer
this._destructible.addDestructor([ 'denizen', options.id ], denizen, 'destroy')
this.loggers[options.id] = denizen.logger.shifter()
console.log('JOIN')
denizen.join(this._port, this._address, options.leader, options.republic, this._destructible.rescue([ 'denizen', options.id ], denizen.ready, 'unlatch'))
async(function () {
denizen.ready.wait(async())
}, function () {
this.events[options.id] = denizen.shifter
})
})
Counterfeiter.prototype.leave = function (id) {
interrupt.assert(!this.destroyed, 'destroyed', {}, this._destructible.errors[0])
this._destructible.invokeDestructor([ 'colleague', id ])
}
Counterfeiter.prototype.destroy = function () {
this._destructible.destroy()
}
Counterfeiter.prototype.listen = cadence(function (async, port, address) {
this._address = address
this._port = port
var ready = new Signal
var conduit = new Conduit
this._destructible.addDestructor('conduit', conduit, 'destroy')
conduit.ready.wait(ready, 'unlatch')
conduit.listen(port, address, this._destructible.monitor('conduit', ready, 'unlatch'))
ready.wait(async())
})
Counterfeiter.prototype.completed = function (callback) {
this._destructible.completed(5000, callback)
}
return Counterfeiter
}
|
JavaScript
| 0 |
@@ -3338,874 +3338,8 @@
%7D)%0A%0A
- Counterfeiter.prototype._join = cadence(function (async, options) %7B%0A interrupt.assert(!this.destroyed, 'destroyed', this._destructible.errors%5B0%5D)%0A // TODO Fold UserAgent into Counterfeiter.%0A var denizen = this._denizens%5Boptions.id%5D = new Denizen(this, options, new UserAgent(this))%0A this.kibitzers%5Boptions.id%5D = denizen.kibitzer%0A%0A this._destructible.addDestructor(%5B 'denizen', options.id %5D, denizen, 'destroy')%0A this.loggers%5Boptions.id%5D = denizen.logger.shifter()%0A console.log('JOIN')%0A denizen.join(this._port, this._address, options.leader, options.republic, this._destructible.rescue(%5B 'denizen', options.id %5D, denizen.ready, 'unlatch'))%0A async(function () %7B%0A denizen.ready.wait(async())%0A %7D, function () %7B%0A this.events%5Boptions.id%5D = denizen.shifter%0A %7D)%0A %7D)%0A%0A
|
51593b02ceef46cb95a47df4962ae5d0b57d5400
|
fix switchPrevious selector
|
src/reducers/selectors.js
|
src/reducers/selectors.js
|
export const getComicManager = (state) => state.comics.comicManager;
export const getChapters = (state) => state.comics.chapters;
export const getNextChapterIndex = (chapters, cid) => {
var index = chapters.findIndex(item => cid == item.cid);
if (index != 0 && index-1 > -1) {
return index - 1;
} else {
return -1;
}
};
export const getPreviousChapterIndex = (chapters, cid) => {
var index = chapters.findIndex(item => cid == item.cid);
if (index != -1 && index+1 < chapters.length-1) {
return index + 1;
} else {
return -1;
}
};
export const getSearchState = (state) => state.searchState;
|
JavaScript
| 0 |
@@ -486,18 +486,16 @@
s.length
--1
) %7B%0A%09%09re
|
fd5657c76a3015c9efd27f960280735304d37a65
|
remove raf from onRender
|
src/render/dom/element.js
|
src/render/dom/element.js
|
import create from './create'
import { findParent, isFragment } from '../fragment'
import { tag } from '../../get'
import parent from './parent'
const createStatic = create.static
const createState = create.state
// check for null as well -- move this to get
const getRemove = t => t.remove || t.inherits && getRemove(t.inherits)
const hasRemove = t => t.emitters && getRemove(t.emitters) ||
t.inherits && hasRemove(t.inherits)
const getRender = t => t.render || t.inherits && getRender(t.inherits)
const hasRender = t => t.emitters && getRender(t.emitters) ||
t.inherits && hasRender(t.inherits)
const removeFragmentChild = (node, pnode) => {
for (let i = 1, len = node.length; i < len; i++) {
if (isFragment(node[i])) {
removeFragmentChild(node[i], pnode)
} else {
pnode.removeChild(node[i])
}
}
}
const injectable = {}
export default injectable
injectable.props = {
staticIndex: true,
_cachedNode: true
}
injectable.render = {
static: createStatic,
state (t, s, type, subs, tree, id, pid, order) {
var node = tree._ && tree._[id]
var pnode
if (type === 'remove') {
if (node) {
pnode = parent(tree, pid)
if (pnode) {
if (tag(t) === 'fragment') {
if (isFragment(pnode)) {
pnode = findParent(pnode)
}
removeFragmentChild(node, pnode)
} else if (!hasRemove(t)) {
if (isFragment(pnode)) {
// add tests for this
for (let i = 0, len = pnode.length; i < len; i++) {
if (pnode[i] === node) {
pnode.splice(i, 1)
break
}
}
pnode = pnode[0]
}
if (isFragment(pnode)) {
pnode = findParent(pnode)
}
node.parentNode.removeChild(node)
}
}
delete tree._[id]
}
} else if (!node) {
node = createState(t, s, type, subs, tree, id, pid, order)
const onrender = hasRender(t)
if (onrender && global.requestAnimationFrame) {
global.requestAnimationFrame(() => t.emit('render', { target: node, state: s }))
}
}
return node
}
}
|
JavaScript
| 0.000001 |
@@ -2113,43 +2113,8 @@
- global.requestAnimationFrame(() =%3E
t.e
@@ -2154,17 +2154,16 @@
te: s %7D)
-)
%0A %7D
|
77b2e527f02916ef8cca748308b463ff83421473
|
correct mistakes
|
askomics/static/js/link/AskomicsPositionableLink.js
|
askomics/static/js/link/AskomicsPositionableLink.js
|
/*jshint esversion: 6 */
class AskomicsPositionableLink extends AskomicsLink {
constructor(uriL,sourceN,targetN) {
super(uriL,sourceN,targetN);
this.type = 'included' ;
this.label = 'included in';
this.sameTax = true ;
this.sameRef = true ;
this.strict = true ;
}
setjson(obj) {
super.setjson(obj);
this.type = obj.type ;
this.label = obj.label;
this.sameTax = obj.sameTax ;
this.sameRef = obj.sameRef ;
this.strict = obj.strict ;
}
getPanelView() {
return new AskomicsPositionableLinkView(this);
}
getFillColor() { return 'darkgreen'; }
buildConstraintsSPARQL(constraintRelations) {
let node = this.target ;
let secondNode = this.source ;
let ua = userAbstraction;
let info = ua.getPositionableEntities();
/* constrainte to target the same ref/taxon */
constraintRelations.push(["?"+'URI'+node.SPARQLid+" :position_taxon ?taxon_"+node.SPARQLid]);
constraintRelations.push(["?"+'URI'+node.SPARQLid+" :position_ref ?ref_"+node.SPARQLid]);
constraintRelations.push(["?"+'URI'+secondNode.SPARQLid+" :position_taxon ?taxon_"+secondNode.SPARQLid]);
constraintRelations.push(["?"+'URI'+secondNode.SPARQLid+" :position_ref ?ref_"+secondNode.SPARQLid]);
/* manage start and end variates */
constraintRelations.push(["?"+'URI'+node.SPARQLid+" :position_start ?start_"+node.SPARQLid]);
constraintRelations.push(["?"+'URI'+node.SPARQLid+" :position_end ?end_"+node.SPARQLid]);
constraintRelations.push(["?"+'URI'+secondNode.SPARQLid+" :position_start ?start_"+secondNode.SPARQLid]);
constraintRelations.push(["?"+'URI'+secondNode.SPARQLid+" :position_end ?end_"+secondNode.SPARQLid]);
}
buildFiltersSPARQL(filters) {
let equalsign = '';
let ua = userAbstraction;
if (!this.strict) {
equalsign = '=';
}
let node = this.target ;
let secondNode = this.source ;
let info = ua.getPositionableEntities();
if (this.same_ref) {
//TODO: test which of the following line is the fastest
filters.push('FILTER(?ref_'+node.SPARQLid+' = ?ref_'+secondNode.SPARQLid+')');
//filters.push('FILTER(SAMETERM(?ref_'+node.SPARQLid+', ?ref_'+secondNode.SPARQLid+'))');
}
if (this.same_tax) {
//TODO: test which of the following line is the fastest
filters.push('FILTER(?taxon_'+node.SPARQLid+' = ?taxon_'+secondNode.SPARQLid+')');
//filters.push('FILTER(SAMETERM(?taxon_'+node.SPARQLid+', ?taxon_'+secondNode.SPARQLid+'))');
}
switch(this.type) {
case 'included' :
filters.push('FILTER((?start_'+secondNode.SPARQLid+' >'+equalsign+' start_'+node.SPARQLid+' ) && (?end_'+secondNode.SPARQLid+' <'+equalsign+' ?end_'+node.SPARQLid+'))');
//filters.push('FILTER((?'+startSecNodeId+' >'+equalsign+' ?'+startNodeId+') && (?'+endSecNodeId+' <'+equalsign+' ?'+endNodeId+'))');
break;
case 'excluded':
filters.push('FILTER(?end_'+node.SPARQLid+' <'+equalsign+' ?start_'+secondNode.SPARQLid+' || ?start_'+node.SPARQLid+' >'+equalsign+' ?end_'+secondNode.SPARQLid+')');
break;
case 'overlap':
filters.push('FILTER(((?end_'+secondNode.SPARQLid+' >'+equalsign+' ?start_'+node.SPARQLid+') && (?start_'+secondNode.SPARQLid+' <'+equalsign+' ?end_'+node.SPARQLid+')) || ((?start_'+secondNode.SPARQLid+' <'+equalsign+' ?end_'+node.SPARQLid+') && (?end_'+secondNode.SPARQLid+' >'+equalsign+' ?start_'+node.SPARQLid+')))');
break;
case 'near':
alert('sorry, near query is not implemanted yet !');
hideModal();
exit();
break;
default:
throw new Error("buildPositionableConstraintsGraph: unkown type :"+JSON.stringify(type));
}
}
instanciateVariateSPARQL(variates) {
}
}
|
JavaScript
| 0.999954 |
@@ -917,35 +917,35 @@
I'+node.SPARQLid
-+%22
+, %22
:position_taxon
@@ -935,33 +935,36 @@
%22:position_taxon
-
+%22, %22
?taxon_%22+node.SP
@@ -1018,35 +1018,35 @@
I'+node.SPARQLid
-+%22
+, %22
:position_ref ?r
@@ -1038,25 +1038,28 @@
position_ref
-
+%22, %22
?ref_%22+node.
@@ -1122,35 +1122,35 @@
ondNode.SPARQLid
-+%22
+, %22
:position_taxon
@@ -1148,17 +1148,20 @@
on_taxon
-
+%22, %22
?taxon_%22
@@ -1235,35 +1235,35 @@
ondNode.SPARQLid
-+%22
+, %22
:position_ref ?r
@@ -1259,17 +1259,20 @@
tion_ref
-
+%22, %22
?ref_%22+s
@@ -1379,35 +1379,35 @@
I'+node.SPARQLid
-+%22
+, %22
:position_start
@@ -1397,33 +1397,36 @@
%22:position_start
-
+%22, %22
?start_%22+node.SP
@@ -1480,35 +1480,35 @@
I'+node.SPARQLid
-+%22
+, %22
:position_end ?e
@@ -1500,25 +1500,28 @@
position_end
-
+%22, %22
?end_%22+node.
@@ -1584,35 +1584,35 @@
ondNode.SPARQLid
-+%22
+, %22
:position_start
@@ -1610,17 +1610,20 @@
on_start
-
+%22, %22
?start_%22
@@ -1709,11 +1709,11 @@
QLid
-+%22
+, %22
:pos
@@ -1721,17 +1721,20 @@
tion_end
-
+%22, %22
?end_%22+s
@@ -2565,24 +2565,25 @@
)');%0A %7D%0A%0A
+%0A
switch(t
@@ -2696,16 +2696,17 @@
lsign+'
+?
start_'+
|
0be3dbbc55d2dfab76d57328d4a0683bb82d3fb5
|
Send Content-Length with API requests.
|
ext/chat.js
|
ext/chat.js
|
var irc = require('irc');
var http = require('http');
var urllib = require('url');
var querystring = require('querystring');
(function checkConfig() {
var i;
var error = false;
var requiredConfigs = ['CT_IRC_SERVER', 'CT_IRC_NICK', 'CT_IRC_CHANNELS',
'CT_API_URL'];
for (i = 0; i < requiredConfigs.length; i++) {
var key = requiredConfigs[i];
if (process.env[key] === undefined) {
console.log('Error: ' + key + ' must be defined.');
error = true;
}
}
if (error) process.exit(-1);
})();
var config = {
server: process.env.CT_IRC_SERVER,
nick: process.env.CT_IRC_NICK,
channels: process.env.CT_IRC_CHANNELS.split(','),
apiUrl: process.env.CT_API_URL
};
function api(method, url, query, cb) {
var key, opts, res;
if (query !== undefined) {
url += '?' + querystring.stringify(query);
}
opts = urllib.parse(config.apiUrl + '/api' + url);
opts.method = method.toUpperCase();
res = http.request(opts, cb);
res.end();
}
// IRC Bot
var ircClient = new irc.Client(config.server, config.nick, {
channels: config.channels
});
// On connected to IRC server
ircClient.on('registered', function(message) {
// Store the nickname assigned by the server
config.nick = message.args[0];
});
// On receive IRC message.
ircClient.addListener('message', function(from, to, message) {
var match;
var screenName, url, opts;
// Only listen to messages targeted at the bot.
if (message.indexOf(config.nick + ': ') !== 0) {
if (from === 'dashbot') {
message = config.nick + ': ' + message;
} else {
return;
}
}
args = message.slice(config.nick.length + 2).split(' ');
if (args[0] === 'ohshit' || args[0] == 'reset' || args[0] === 'clear') {
opts = {};
screenName = args.slice(1).join(' ');
if (screenName !== '') {
opts.screen = screenName;
}
api('post', '/reset', opts);
} else {
opts = {
url: args[0]
};
screenName = args.slice(1).join(' ');
if (screenName) {
opts.screen = screenName;
}
api('post', '/sendurl', opts, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
try {
data = JSON.parse(data);
if (data.message) {
ircClient.say(to, data.message);
}
} catch(e) {
ircClient.say('Something went wrong (' + e + ')');
console.log('Error sending url: ' + data);
}
});
});
}
});
|
JavaScript
| 0 |
@@ -952,16 +952,65 @@
rCase();
+%0A opts.headers = %7B%0A 'Content-Length': 0,%0A %7D;
%0A%0A res
|
52cea5a46ca9bed8b53fd95a5afa64431f0a511c
|
Fix chunkname
|
src/routes/login/index.js
|
src/routes/login/index.js
|
import React from 'react';
import Layout from '../../components/Layout';
import Login from './Login';
const title = 'Log In';
function action({ store }) {
const { user } = store.getState();
if (user) {
return { redirect: '/login' };
}
return {
chunks: ['login'],
title,
component: (
<Layout>
<Login />
</Layout>
),
};
}
export default action;
|
JavaScript
| 0.001233 |
@@ -265,21 +265,21 @@
unks: %5B'
-login
+users
'%5D,%0A
|
20cdc3f1fbeec5431931ccf070ce1fb62746e25b
|
update docs
|
docs/layout/assets/app.js
|
docs/layout/assets/app.js
|
// stateless components
function Content (props) {
return h('div.content', {dangerouslySetInnerHTML: props.html});
}
function TableOfContents (props) {
return h('.table-of-contents',
h('ul',
props.nav.map(function (value) {
return h('li',
h('a[href='+ value.href +']',
{
class: value.active ? 'active' : '',
onClick: props.onClick
},
value.text
)
)
})
)
)
}
function Header () {
return h('.wrap',
h('.logo',
h('a[href=./]', {onClick: dio.curry(router.nav, '/', true)}, h('img[src=assets/logo.svg]'))
),
h('.nav',
h('ul', h('li', h('a[href=https://github.com/thysultan/dio.js]', 'Github')))
)
)
}
// state components
function Documentation () {
var
markdown = dio.stream();
function rawMarkup () {
return remarkable.render(markdown());
}
function getDocument (url, callback) {
dio.request.get(url)
.then(markdown)
.then(callback)
.catch(function () {
markdown('# 404 | document not found')
callback()
});
}
function update (self) {
return function () {
self.setProps({loading: false});
self.forceUpdate();
highlighter();
}
}
function activateLink (self, href) {
href = href || this.getAttribute('href');
if (this.className === 'active') return;
var
nav = [];
self.props.nav.forEach(function (value) {
var
item = Object.assign({}, value, {active: value.href !== href ? false : true});
nav.push(item);
});
hash = href.replace('../', '').replace('.md', '');
self.setProps({nav: nav, loading: true});
self.forceUpdate();
getDocument(href, update(self));
window.location.hash = hash;
}
return {
getDefaultProps: function () {
return {
nav: [
{text: 'Installation', href: '../installation.md'},
{text: 'Getting Started', href: '../getting-started.md'},
{text: 'Examples', href: '../examples.md'},
{text: 'API Reference', href: '../api.md'}
]
}
},
componentWillReceiveProps: function (props) {
activateLink(this, props.url);
},
render: function (props) {
return h('.documentation'+(props.loading ? '.loading' : ''),
Content({html: rawMarkup()}),
TableOfContents({
nav: props.nav,
onClick: dio.curry(activateLink, this, true)
})
)
}
}
}
function Welcome () {
var
rawMarkup = dio.stream('');
function Install (e) {
var
href = e.target.getAttribute('href');
if (href) {
router.nav(href.replace('.',''));
}
}
return {
componentDidMount: function (props, _, self) {
dio.request.get(props.url)
.then(rawMarkup)
.then(function () {
rawMarkup(remarkable.render(rawMarkup()))
self.forceUpdate();
});
},
componentDidUpdate: function () {
highlighter();
},
render: function () {
return h('.welcome', {
onClick: dio.curry(Install, true),
innerHTML: rawMarkup()
});
}
}
}
var
remarkable = new Remarkable();
var
router = dio.createRouter({
'/': function () {
dio.createRender(Welcome, '.container')({url: '../welcome.md'});
},
'/documentation': function () {
var
section = window.location.hash.toLowerCase().replace('#', '');
section = section || 'installation';
section = '../'+ section + '.md';
dio.createRender(Documentation, '.container')({url: section});
}
}, '/docs/layout');
dio.createRender(Header, '.header')();
|
JavaScript
| 0.000001 |
@@ -74,23 +74,9 @@
', %7B
-dangerouslySetI
+i
nner
|
de01a97d11b11f4aaea80af513c85423ec0cbbad
|
change pattern for info: logout seneca action
|
server/concorda-client.js
|
server/concorda-client.js
|
'use strict'
const _ = require('lodash')
let options = {name: 'concorda'}
// Hapi Plugin for wiring up Concorda
module.exports = function (server, opts, next) {
// Set up our seneca plugins
let seneca = server.seneca
options = _.extend({}, opts, options)
seneca.add('role: ' + options.name + ', cmd: closeSession', function(msg, done){
done()
})
seneca
.use('mesh',{auto:true, pin:'role:' + options.name + ', info: *'})
next()
}
// Hapi plugin metadata
module.exports.attributes = {
name: options.name
}
|
JavaScript
| 0 |
@@ -304,25 +304,20 @@
',
-cmd
+info
:
-c
lo
-seSession
+gout
', f
|
4e795885787e231e24033bf8e80bf03ebeb5b8af
|
set resave to false in passport
|
server/config/passport.js
|
server/config/passport.js
|
"use strict";
var passport = require('passport');
var session = require('express-session');
var pg = require('pg');
var pgSession = require('connect-pg-simple')(session);
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
var Strategies = require('./oauthStrategies');
var User = require('../models/users');
module.exports = (app,express) => {
let database_url = process.env.DATABASE_URL || 'postgresql://localhost/fairshare';
const sessionConfig = {
genid: () => uuid.v1(),
store: new pgSession({
pg : pg,
conString: database_url,
tableName: 'sessions'
}),
secret: 'kitkat',
resave: true,
saveUninitialized: true
};
app.use(session(sessionConfig));
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser('kitkat'));
passport.serializeUser((user, done) => {
return done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.getById({id: id})
.then( userObj => {
return done(null, userObj[0]);
})
.catch( err => {
console.warn("err at deserialize:", err);
});
});
passport.use(Strategies.facebook_strat);
passport.use(Strategies.google_strat);
passport.use(Strategies.paypal_strat);
};
|
JavaScript
| 0.000051 |
@@ -736,19 +736,20 @@
resave:
-tru
+fals
e,%0A s
@@ -770,11 +770,12 @@
ed:
-tru
+fals
e%0A
@@ -1345,8 +1345,9 @@
rat);%0A%7D;
+%0A
|
eb51d5d8070eb47b9d4a338e744d68b61afa2ea6
|
Add missing namespacing
|
src/rules/percent-placeholder-pattern/index.js
|
src/rules/percent-placeholder-pattern/index.js
|
import { isRegExp, isString } from "lodash"
import resolveNestedSelector from "postcss-resolve-nested-selector"
import { utils } from "stylelint"
import {
hasInterpolatingAmpersand,
isStandardRule,
isStandardSelector,
parseSelector,
} from "../../utils"
export const ruleName = "percent-placeholder-pattern"
export const messages = utils.ruleMessages(ruleName, {
expected: placeholder => `Expected %-placeholder "%${placeholder}" to match specified pattern`,
})
export default function (pattern) {
return (root, result) => {
const validOptions = utils.validateOptions(result, ruleName, {
actual: pattern,
possible: [ isRegExp, isString ],
})
if (!validOptions) { return }
const placeholderPattern = (isString(pattern))
? new RegExp(pattern)
: pattern
// Checking placeholder definitions (looking among regular rules)
root.walkRules(rule => {
const { selector } = rule
// Just a shorthand for calling `parseSelector`
function parse(selector) {
parseSelector(selector, result, rule, s => checkSelector(s, rule))
}
// If it's a custom prop or a less mixin
if (!isStandardRule(rule)) { return }
// If the selector has interpolation
if (!isStandardSelector(selector)) { return }
// Nested selectors are processed in steps, as nesting levels are resolved.
// Here we skip processing intermediate parts of selectors (to process only fully resolved selectors)
// if (rule.nodes.some(node => node.type === "rule" || node.type === "atrule")) { return }
// Only resolve selectors that have an interpolating "&"
if (hasInterpolatingAmpersand(selector)) {
resolveNestedSelector(selector, rule).forEach(parse)
} else {
parse(selector)
}
})
function checkSelector(fullSelector, rule) {
// postcss-selector-parser gives %placeholders' nodes a "tag" type
fullSelector.walkTags(compoundSelector => {
const { value, sourceIndex } = compoundSelector
if (value[0] !== "%") { return }
const placeholder = value.slice(1)
if (placeholderPattern.test(placeholder)) { return }
utils.report({
result,
ruleName,
message: messages.expected(placeholder),
node: rule,
index: sourceIndex,
})
})
}
}
}
|
JavaScript
| 0.006429 |
@@ -234,16 +234,29 @@
lector,%0A
+ namespace,%0A
%7D from %22
@@ -293,16 +293,26 @@
eName =
+namespace(
%22percent
@@ -332,16 +332,17 @@
pattern%22
+)
%0A%0Aexport
@@ -1313,22 +1313,16 @@
eturn %7D%0A
-
%0A /
@@ -2401,9 +2401,8 @@
%0A%0A %7D%0A%7D%0A
-%0A
|
c9903ee90b9c0723e67d00092a251dbf1a764bd8
|
Revert "One more dir to be cleaned by WAFD cleaner"
|
src/scripts/browser/components/wafd-cleaner.js
|
src/scripts/browser/components/wafd-cleaner.js
|
import {app} from 'electron';
import path from 'path';
import del from 'del';
const paths = [
path.join(app.getPath('desktop'), 'WhatsApp for Desktop.lnk'),
path.join(app.getPath('desktop'), 'WhatsApp.lnk'),
path.join(app.getPath('desktop'), 'Unofficial WhatsApp for Desktop.lnk'),
path.join(app.getPath('desktop'), 'Unofficial WhatsApp.lnk'),
path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop'),
path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp'),
path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop'),
path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp'),
path.join(app.getPath('appData'), 'WhatsApp'),
path.join(app.getPath('appData'), 'UnofficialWhatsApp'),
path.join(app.getPath('appData'), '..', 'Local', 'WhatsApp'),
path.join(app.getPath('appData'), '..', 'Local', 'UnofficialWhatsApp'),
path.join(app.getPath('appData'), '..', 'Local', 'whatsapp'),
path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop.lnk'),
path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp.lnk'),
path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop.lnk'),
path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp.lnk'),
path.join('C:', 'Program Files', 'WhatsApp for Desktop'),
path.join('C:', 'Program Files', 'Unofficial WhatsApp for Desktop'),
path.join('C:', 'Program Files (x86)', 'WhatsApp for Desktop'),
path.join('C:', 'Program Files (x86)', 'Unofficial WhatsApp for Desktop')
];
function check (callback) {
clean(callback, true);
}
function clean (callback, dryRun = false) {
del((paths), {force: true, dryRun})
.catch((err) => callback(err))
.then((paths) => callback(null, paths));
}
export default {
check,
clean
};
|
JavaScript
| 0 |
@@ -1038,72 +1038,8 @@
'),%0A
- path.join(app.getPath('appData'), '..', 'Local', 'whatsapp'),%0A
pa
|
1b640f87a3a482ee628d4f7cfdcbb50395258f60
|
Change reference to phantomjs package
|
src/services/account/strategies/itslearning.js
|
src/services/account/strategies/itslearning.js
|
'use strict';
const logger = require('winston');
const promisify = require('es6-promisify');
const errors = require('feathers-errors');
const path = require('path');
const childProcess = require('child_process');
const execFile = promisify(childProcess.execFile);
const phantomjs = require('phantomjs');
const binPath = phantomjs.path;
const AbstractLoginStrategy = require('./interface.js');
class ITSLearningLoginStrategy extends AbstractLoginStrategy {
login({username, password}, system) {
const itsLearningOptions = {
username: username,
password: password,
wwwroot: system,
logger: logger
};
if (!itsLearningOptions.username) return Promise.reject('No username set');
if (!itsLearningOptions.password) return Promise.reject(new errors.NotAuthenticated('No password set'));
if (!itsLearningOptions.wwwroot) return Promise.reject('No url for ITSLearning login provided');
var childArgs = [
path.join(__dirname, '/utils/itslearning_phantom.js'), itsLearningOptions.username, itsLearningOptions.password, itsLearningOptions.wwwroot
];
return execFile(binPath, childArgs)
.then(queryParams => {
let itsLearningResponse = {};
itsLearningResponse.username = this.getParameterByName('Username', queryParams);
itsLearningResponse.customerId = this.getParameterByName('CustomerId', queryParams);
itsLearningResponse.hash = this.getParameterByName('Hash', queryParams);
itsLearningResponse.timeStamp = this.getParameterByName('TimeStamp', queryParams);
itsLearningResponse.success = !itsLearningResponse.username ? false : true;
if(!itsLearningResponse.success) {
return Promise.reject(new errors.NotAuthenticated('Wrong username or password'));
}
return itsLearningResponse;
});
}
//Regex for the query string
getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
}
module.exports = ITSLearningLoginStrategy;
|
JavaScript
| 0 |
@@ -293,16 +293,25 @@
hantomjs
+-prebuilt
');%0Acons
|
2290d22bd45bc5172bdd5595a9b8a644b8f39dc9
|
update copyright dates from daily grunt work
|
js/MutableOptionsNode.js
|
js/MutableOptionsNode.js
|
// Copyright 2017-2021, University of Colorado Boulder
/**
* Assists "changing" options for types of nodes where the node does not support modifying the option.
* This will create a new copy of the node whenever the options change, and will swap it into place.
*
* Given a type that has an option that can only be provided on construction (e.g. 'color' option for NumberPicker),
* MutableOptionsNode can act like a mutable form of that Node. For example, if you have a color property:
*
* var colorProperty = new Property( 'red' );
*
* You can create a NumberPicker equivalent:
*
* var pickerContainer = new MutableOptionsNode( NumberPicker, [ arg1, arg2 ], {
* font: new PhetFont( 30 ) // normal properties that are passed in directly
* }, {
* color: colorProperty // values wrapped with Property. When these change, a new NumberPicker is created and swapped.
* }, {
* // Options passed to the wrapper node.
* } );
*
* Now pickerContainer will have a child that is a NumberPicker, and pickerContainer.nodeProperty will point to the
* current NumberPicker instance. The NumberPicker above will be created with like:
*
* new NumberPicker( arg1, arg2, {
* font: new PhetFont( 30 ),
* color: colorProperty.value
* } )
*
* @author Jonathan Olson (PhET Interactive Simulations)
*/
import Property from '../../axon/js/Property.js';
import merge from '../../phet-core/js/merge.js';
import { Node } from '../../scenery/js/imports.js';
import sun from './sun.js';
/**
* @deprecated Not a good fit for PhET-iO. Please design your component so that the item is mutable.
*/
class MutableOptionsNode extends Node {
/**
* @param {Function} nodeSubtype - The type of the node that we'll be constructing copies of.
* @param {Array.<*>} parameters - Arbitrary initial parameters that will be passed to the type's constructor
* @param {Object} staticOptions - Options passed in that won't change (will not unwrap properties)
* @param {Object} dynamicOptions - Options passed in that will change. Should be a map from key names to
* Property.<*> values.
* @param {Object} [wrapperOptions] - Node options passed to MutableOptionsNode itself (the wrapper).
*/
constructor( nodeSubtype, parameters, staticOptions, dynamicOptions, wrapperOptions ) {
super();
// @public {Property.<Node|null>} [read-only] - Holds our current copy of the node (or null, so we don't have a
// specific initial value).
this.nodeProperty = new Property( null );
// @private {function} - The constructor for our custom subtype, unwraps the Properties in dynamicOptions.
this._constructInstance = () => Reflect.construct( nodeSubtype, [
...parameters,
merge( _.mapValues( dynamicOptions, property => property.value ), staticOptions ) // options
] );
// @private {Multilink} - Make a copy, and replace it when one of our dyanmic options changes.
this.multilink = Property.multilink( _.values( dynamicOptions ), this.replaceCopy.bind( this ) );
// Apply any options that make more sense on the wrapper (typically like positioning)
this.mutate( wrapperOptions );
}
/**
* Creates a copy of our type of node, and replaces any existing copy.
* @private
*/
replaceCopy() {
const newCopy = this._constructInstance();
const oldCopy = this.nodeProperty.value;
this.nodeProperty.value = newCopy;
// Add first, so that there's a good chance we won't change bounds (depending on the type)
this.addChild( newCopy );
if ( oldCopy ) {
this.removeChild( oldCopy );
this.disposeCopy( oldCopy );
}
}
/**
* Attempt to dispose an instance of our node.
* @private
*
* @param {Node} copy
*/
disposeCopy( copy ) {
copy.dispose && copy.dispose();
}
/**
* @public
* @override
*/
dispose() {
this.multilink.dispose();
this.disposeCopy( this.nodeProperty.value );
this.nodeProperty.dispose();
super.dispose();
}
}
sun.register( 'MutableOptionsNode', MutableOptionsNode );
export default MutableOptionsNode;
|
JavaScript
| 0 |
@@ -14,17 +14,17 @@
2017-202
-1
+2
, Univer
|
e72f75636be0c9038dd66692d3ec2dee17983b5a
|
debug wechat
|
js/WeiXinJsSdkWrapper.js
|
js/WeiXinJsSdkWrapper.js
|
var WeiXinJsSdkWrapper = (function($, Hashes, wx, zHelper, ParseJsGlobalCache){
//TODO(zzn): to be replaced by a real secret after development.
var CONST_APPID = "wx4bf3130f55a3352d";
var CONST_APPSECRET = "d15f5121f0047d288f1ba81dd0fe7cca";
var CACHE_DB_NAME = "AuthCache";
var ACCESS_TOKEN_CACHE_KEY = "ACCESS_TOKEN";
var JS_API_TICKET_CACHE_KEY = "JSAPI_TICKET";
var Authenticator = function() {
this.cacheDb_ = new ParseJsGlobalCache.CacheDb(CACHE_DB_NAME, 600);
this.nonceStr_ = "85NRI02249025822X184ndd"; //TODO(zzn): use random string each time
};
Authenticator.prototype.getAccessTokenAsync_ = function(cb) {
var that = this;
this.cacheDb_.cacheReadAsync(ACCESS_TOKEN_CACHE_KEY,
function(dataRead) {
if (dataRead !== null) {
zHelper.log("Cache hit, already have access token");
zHelper.track("CacheHitWeChatAccessToken");
cb(dataRead);
} else {
zHelper.log("Cached not hit, requesting access token");
zHelper.track("RequestWeChatAccessToken");
$.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + CONST_APPID
+ "&secret=" + CONST_APPSECRET, function (data) {
if ("access_token" in data) {
zHelper.log("access_token ret", "INFO", JSON.stringify(data));
that.cacheDb_.cacheWriteAsync(
ACCESS_TOKEN_CACHE_KEY,
data.access_token, 7200 * 1000,
function (wroteData) {
cb(wroteData);
});
} else if ("errcode" in data) {
zHelper.log("getAccessTokenAsync_ error", "ERROR", data);
cb(null);
}
});
}
});
};
Authenticator.prototype.getJsApiTokenAsync_ = function(cb) {
var that = this;
this.cacheDb_.cacheReadAsync(JS_API_TICKET_CACHE_KEY,
function(dataRead) {
if (dataRead !== null) {
zHelper.log("Cache hit, already have jsapi_ticket");
zHelper.track("CacheHitWeChatJsApiTicket");
cb(dataRead);
return;
} else {
that.getAccessTokenAsync_(function (accessToken) {
zHelper.log("accessToken = " + accessToken);
var url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
zHelper.log("Cache not hit, requesting jsapi_ticket");
zHelper.track("RequestWeChatJsApiTicket");
$.get(url, function (data) {
zHelper.log("jsapi_ticket obj", "INFO", JSON.stringify(data));
that.cacheDb_.cacheWriteAsync(
JS_API_TICKET_CACHE_KEY,
data.ticket, 7200 * 1000,
function (wroteData) {
cb(wroteData);
});
cb(that.cachedJsapiToken_);
});
});
}
});
};
Authenticator.prototype.configAsync = function(cb){
var timestamp = Math.floor(Date.now()/1000);
var nonceStr = this.nonceStr_;
var that = this;
zHelper.log("Start configAsync");
that.getJsApiTokenAsync_(function(jsApiToken) {
zHelper.assert(jsApiToken, "jsApiToken should exist" );
zHelper.assert(nonceStr, "nonceStr should exist" );
zHelper.assert(timestamp, "timestamp should exist" );
var msg = [
"jsapi_ticket=" + jsApiToken,
"noncestr=" + nonceStr,
"timestamp=" + timestamp,
"url=" + window.location.href,
].join('&');
var SHA1 = new Hashes.SHA1;
var signature = SHA1.hex(msg);
zHelper.log(msg);
zHelper.log("XXX signature!");
zHelper.log(signature);
zHelper.log("XXX before wx.config ready");
wx.config({
debug: zHelper.isDebug(), // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: CONST_APPID, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr:nonceStr, // 必填,生成签名的随机串
signature: signature,// 必填,签名,见附录1
jsApiList: [
"onMenuShareTimeline",
"onMenuShareAppMessage"
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
zHelper.log("XXX before ready");
wx.error(function (res) {
zHelper.log(res.errMsg);
});
});
};
var authenticator = new Authenticator();
return {
authenticator : authenticator
};
})($, Hashes, wx, zHelper, ParseJsGlobalCache);
|
JavaScript
| 0.000001 |
@@ -4528,25 +4528,12 @@
ug:
-zHelper.isDebug()
+true
, //
|
1940b7f7682b1f4fd4fa05eb9391278df76f519c
|
Add Andrew's UTM codes
|
root/src/js/lib/social.js
|
root/src/js/lib/social.js
|
var Share = require("./share.min.js");
new Share(".share", {
ui: {
flyout: "bottom left"
},
networks: {
email: {
description: window.location.href
}
}
});
|
JavaScript
| 0.000002 |
@@ -37,146 +37,728 @@
);%0A%0A
-new Share(%22.share%22, %7B%0A ui: %7B%0A flyout: %22bottom left%22%0A %7D,%0A networks: %7B%0A email: %7B%0A description: window.location.href%0A %7D%0A %7D%0A%7D
+var addQuery = function(url, query) %7B%0A var joiner = url.indexOf(%22?%22) %3E -1 ? %22&%22 : %22?%22;%0A return url + joiner + query;%0A%7D;%0A%0Avar utm = function(source, medium) %7B%0A return %60utm_source=$%7Bsource%7D&utm_medium=$%7Bmedium %7C%7C %22social%22%7D&utm_campaign=projects%60;%0A%7D;%0A%0Avar here = window.location.href;%0A%0Avar s = new Share(%22.share%22, %7B%0A ui: %7B%0A flyout: %22bottom left%22%0A %7D,%0A networks: %7B%0A google_plus: %7B%0A url: addQuery(here, utm(%22google+%22))%0A %7D,%0A twitter: %7B%0A url: addQuery(here, utm(%22twitter%22))%0A %7D,%0A facebook: %7B%0A url: addQuery(here, utm(%22facebook%22))%0A %7D,%0A pinterest: %7B%0A url: addQuery(here, utm(%22pinterest%22))%0A %7D%0A %7D%0A%7D);%0A%0As.config.email.description += %22 %22 + addQuery(here, utm(%22email_share%22, %22email%22)
);%0A
|
cd785de7aca2d4e6044daeaa958bb7f0bc77432f
|
Load current permission user edit
|
js/adminEditViewModel.js
|
js/adminEditViewModel.js
|
function pageViewModel(gvm) {
// Page specific i18n bindings
gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);
gvm.edituserid = $("#usereditHeader").data('value');
gvm.loggedinuser = ko.observable();
getLoggedInUser();
gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);
gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);
gvm.currentUserRole = ko.observable();
gvm.oldUserRole = ko.observable();
gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);
gvm.rights = ko.observableArray([]);
gvm.allRights = ko.observableArray([]);
gvm.userRights = ko.observableArray([]);
gvm.user = ko.observableArray([]);
gvm.updateUser = function(user)
{
gvm.user.push(user);
},
gvm.updatePermissions = function(permission)
{
gvm.rights.push(permission);
},
gvm.updateAllPermissions = function(permission)
{
gvm.allRights.push(permission);
},
gvm.removeUser = function(user) {
gvm.user.remove(user);
removeUser(user);
},
gvm.clearStructure = function() {
gvm.rights.destroyAll();
gvm.user.destroyAll();
}
}
function initPage() {
getAllUserDataById(viewModel.edituserid);
viewModel.oldUserRole = getUserPermission();
$('#userEditForm').on('submit', function(e)
{
e.preventDefault();
if(viewModel.loggedinuser != viewModel.edituserid)
{
saveChanges();
saveUserPermissions();
} else {
saveChanges();
}
});
}
function getUserPermission(){
$.ajax({
type: "POST",
url: "/api/getUserRolesById/" + viewModel.edituserid,
success: function(data) {
console.log(data);
if (data.length > 0) {
var role = "GUEST";
for (i = 0; i < data.length; i++) {
if (data[i] == "SUPERUSER" && data[i] != null){
console.log("SUPERUSER");
role = "SUPERUSER";
}
if (data[i] == "USER" && data[i] != null){
console.log("USER");
role = "USER";
}
if (data[i] == "STUDENT" && data[i] != null){
console.log("STUDENT");
role = "STUDENT";
}
if (data[i] == "GUEST" && data[i] != null){
console.log("guest");
role = "GUEST";
}
}
console.log("role: " + role);
return role;
} else {
console.log("guest else");
return "GUEST";
}
},
error: function() {
alert("Error while getting user info, please contact your administrator");
}
});
}
function getLoggedInUser(){
$.getJSON("/api/loggedinuser", function(data){
viewModel.loggedinuser = data;
});
}
function saveChanges(){
saveUserEdits(viewModel.edituserid);
}
function saveUserEdits(id){
$.ajax({
type: "POST",
url: "/api/saveedit/" + id,
data: $('#userEditForm').serialize(),
success: function() {
},
error: function() {
console.log("Error saving user changes");
}
});
}
function saveUserPermissions(){
var role = viewModel.currentUserRole();
var permissions = "GUEST ";
if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
permissions += "STUDENT ";
if(role == 'USER' || role == 'SUPERUSER'){
permissions += "USER ";
if(role == 'SUPERUSER'){
permissions += "SUPERUSER";
}
}
}
//SAVE NEW PERMISSIONS
$.ajax({
type: "POST",
url: "/api/addrole/" + viewModel.edituserid,
data: { 'permissions': permissions },
success: function() {
alert('Changes saved correctly');
},
error: function() {
alert('Error saving user. Please contact the Administrator');
}
});
}
function getAllUserDataById(edituserid){
$.getJSON("/api/edituser/" + edituserid, function(data)
{
var addedUsername = "";
$.each(data, function(i, item){
var current = item.username;
$.each(data, function(i, item)
{
if(item.username == current && addedUsername != current){
viewModel.updatePermissions(item.role)
}
});
if (addedUsername != current) {
addedUsername = current;
viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
}
});
});
}
function User(id, username, firstname, lastname, status, permissions) {
return {
id: ko.observable(id),
username: ko.observable(username),
firstname: ko.observable(firstname),
lastname: ko.observable(lastname),
status: ko.observable(status),
permissions: ko.observableArray(permissions),
userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),
removeThisUser: function() {
if(confirm('Are you sure you want to remove this user?'))
{
viewModel.removeUser(this);
}
},
changeStatus: function() {
if (this.status() == "ACTIVE"){
this.status("DISABLED");
} else if (this.status() == "DISABLED") {
this.status("ACTIVE");
} else if (this.status() == "WAIT_ACTIVATION") {
this.status("ACTIVE");
}
updateUserStatus(this);
}
};
}
|
JavaScript
| 0.000001 |
@@ -1184,32 +1184,39 @@
= ko.observable(
+%22GUEST%22
);%0A gvm.avail
|
88219de90b9c052ad57aac7e091dce3050f2ecc8
|
Replace log with error
|
js/app/engine/ui/Menu.js
|
js/app/engine/ui/Menu.js
|
define([
'engine/graphics/DisplayObject',
'./UiEventType'
],
function(
DisplayObject,
UiEventType
) {
'use strict';
/**
* @type {string}
*/
var BACKGROUND_COLOR = '#000000';
/**
* @type {string}
*/
var BACKGROUND_BORDER_COLOR = '#FFFFFF';
/**
* @type {Number}
*/
var MENU_PADDING_HORIZONTAL = 20;
/**
* @param {Graphics} graphics
*
* @constructor
* @extends DisplayObject
*/
function Menu(graphics) {
DisplayObject.call(this, 0, 0, 0, 0);
this.graphics = graphics;
this.items = [];
this.focusedItemId = 0;
this.itemSelectedListener = null;
this.itemSelectedListenerArguments = null;
this.backgroundColor = BACKGROUND_COLOR;
this.backgroundBorderColor = BACKGROUND_BORDER_COLOR;
this.html = document.createElement('div');
addItemAddedEventListener(this);
this.updateHtmlStyle();
this.hide();
}
Menu.prototype = Object.create(DisplayObject.prototype);
Menu.prototype.constructor = Menu;
/**
* @param {Menu} menu
*/
function addItemAddedEventListener(menu) {
menu.html.addEventListener(UiEventType.DOM_NODE_INSERTED, createDomNodeInsertedEventListener(menu), false);
}
/**
* @param {Menu} menu
*
* @returns {function}
*/
function createDomNodeInsertedEventListener(menu) {
return function() {
rescale(menu);
};
}
/**
* @param {Menu} menu
*/
function rescale(menu) {
var width = determineMenuWidth(menu);
menu.setWidth(width);
var height = determineMenuHeight(menu);
menu.setHeight(height);
}
/**
* @param {Menu} menu
* @returns {Number}
*/
function determineMenuWidth(menu) {
var graphics = menu.graphics;
var menuWidth = 0;
var itemsCount = menu.getItemsCount();
for (var i = 0; i < itemsCount; i += 1) {
var focusedItem = getFocusedItem(menu);
var focusedItemWidth = focusedItem.determineWidth(graphics);
if (menuWidth < focusedItemWidth) {
menuWidth = focusedItemWidth;
}
menu.focusNextItem();
}
return Math.round(menuWidth) + MENU_PADDING_HORIZONTAL;
}
/**
* @param {Number} width
*/
Menu.prototype.setWidth = function(width) {
DisplayObject.prototype.setWidth.call(this, width);
this.html.style.width = width + 'px';
};
/**
* @param {Menu} menu
*
* @returns {Number}
*/
function determineMenuHeight(menu) {
var height = 0;
var itemsCount = menu.getItemsCount();
for (var i = 0; i < itemsCount; i += 1) {
var item = menu.getItemById(i);
var itemHTML = item.getHtml();
height += itemHTML.offsetHeight;
}
return height;
}
/**
* @param {Number} height
*/
Menu.prototype.setHeight = function(height) {
DisplayObject.prototype.setHeight.call(this, height);
this.html.style.height = height + 'px';
};
/**
* @param {Menu} menu
* @param {Number} itemId
*/
function focusItemById(menu, itemId) {
var focusedItem = getFocusedItem(menu);
if (focusedItem) {
focusedItem.unfocus();
}
var itemsCount = menu.getItemsCount();
if (itemsCount !== 0) {
menu.focusedItemId = (itemId + itemsCount) % itemsCount;
} else {
console.log('COULD NOT FOCUS A MENU ITEM: NO ITEMS ADDED');
}
var itemToFocus = getFocusedItem(menu);
if (itemToFocus) {
itemToFocus.focus();
}
}
/**
*/
Menu.prototype.focusNextItem = function() {
focusItemById(this, this.focusedItemId + 1);
};
/**
*/
Menu.prototype.focusPreviousItem = function() {
focusItemById(this, this.focusedItemId - 1);
};
/**
*/
Menu.prototype.focusFirstItem = function() {
focusItemById(this, 0);
};
/**
* @return {MenuItem}
*/
function getFocusedItem(menu) {
return menu.getItemById(menu.focusedItemId);
}
/**
*/
Menu.prototype.setItemSelectedListener = function() {
var args = Array.prototype.slice.call(arguments);
this.itemSelectedListener = args[0];
this.itemSelectedListenerArguments = args.slice(1, args.length);
};
/**
*/
Menu.prototype.selectCurrentItem = function() {
var itemSelectedListener = this.itemSelectedListener;
var itemSelectedListenerArguments = this.itemSelectedListenerArguments.slice(0);
var focusedItem = getFocusedItem(this);
var focusedItemActionCode = focusedItem.getActionCode();
itemSelectedListenerArguments.push(focusedItemActionCode);
this.itemSelectedListener.apply(itemSelectedListener, itemSelectedListenerArguments);
};
/**
* @param {MenuItem} item
*/
Menu.prototype.addItem = function(item) {
if (this.getItemsCount() === 0) {
item.focus();
}
this.items.push(item);
var itemHtml = item.getHtml();
this.html.appendChild(itemHtml);
};
/**
* @returns {Number}
*/
Menu.prototype.getItemsCount = function() {
return this.items.length;
};
/**
* @param {Number} index
*
* @returns {MenuItem}
*/
Menu.prototype.getItemById = function(index) {
return this.items[index];
};
/**
* @returns {Element}
*/
Menu.prototype.getHtml = function() {
return this.html;
};
/**
*/
Menu.prototype.hide = function() {
this.html.style.visibility = 'hidden';
};
/**
*/
Menu.prototype.reveal = function() {
this.html.style.visibility = 'visible';
};
/**
* @returns {boolean}
*/
Menu.prototype.isVisible = function() {
return this.html.style.visibility === 'visible';
};
/**
*/
Menu.prototype.updateHtmlStyle = function() {
var html = this.html;
html.className = 'menu unselectable default-cursor';
html.style.borderColor = this.backgroundBorderColor;
html.style.borderStyle = 'solid';
html.style.borderWidth = '1px';
html.style.padding = '10px 10px 15px 17px';
html.style.backgroundColor = this.backgroundColor;
html.style.position = 'absolute';
html.style.whiteSpace = 'nowrap';
html.style.left = '50%';
html.style.top = '50%';
};
/**
*/
Menu.prototype.center = function()
{
var html = this.html;
html.style.marginTop = '-' + this.getHeight() / 2 + 'px';
html.style.marginLeft = '-' + this.determineWidth() / 2 + 'px';
};
return Menu;
});
|
JavaScript
| 0.998854 |
@@ -4146,66 +4146,60 @@
-console.log('COULD NOT FOCUS A MENU ITEM: NO ITEMS ADDED')
+throw 'Could not focus a menu item: no items added!'
;%0A
|
a9e661a2b5cc96e2148d62fa5ccd41522197ceef
|
read data options in constructor for collapse
|
js/bootstrap-collapse.js
|
js/bootstrap-collapse.js
|
/* =============================================================
* bootstrap-collapse.js v2.2.3
* http://twitter.github.com/bootstrap/javascript.html#collapse
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* COLLAPSE PUBLIC CLASS DEFINITION
* ================================ */
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options.parent) {
this.$parent = $(this.options.parent)
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse
, dimension: function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
, show: function () {
var dimension
, scroll
, actives
, hasData
if (this.transitioning || this.$element.hasClass('in')) return
dimension = this.dimension()
scroll = $.camelCase(['scroll', dimension].join('-'))
actives = this.$parent && this.$parent.find('> .accordion-group > .in')
if (actives && actives.length) {
hasData = actives.data('collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', $.Event('show'), 'shown')
$.support.transition && this.$element[dimension](this.$element[0][scroll])
}
, hide: function () {
var dimension
if (this.transitioning) return
dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', $.Event('hide'), 'hidden')
this.$element[dimension](0)
}
, reset: function (size) {
var dimension = this.dimension()
this.$element
.removeClass('collapse')
[dimension](size || 'auto')
[0].offsetWidth
this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
return this
}
, transition: function (method, startEvent, completeEvent) {
var that = this
, complete = function () {
if (startEvent.type == 'show') that.reset()
that.transitioning = 0
that.$element.trigger(completeEvent)
}
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
this.transitioning = 1
this.$element[method]('in')
$.support.transition && this.$element.hasClass('collapse') ?
this.$element.one($.support.transition.end, complete) :
complete()
}
, toggle: function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
/* COLLAPSE PLUGIN DEFINITION
* ========================== */
var old = $.fn.collapse
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('collapse')
, options = typeof option == 'object' && option
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
/* COLLAPSE NO CONFLICT
* ==================== */
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
/* COLLAPSE DATA-API
* ================= */
$(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
, target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
, option = $(target).data('collapse') ? 'toggle' : $this.data()
$this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
$(target).collapse(option)
})
}(window.jQuery);
|
JavaScript
| 0 |
@@ -3698,16 +3698,67 @@
ptions =
+ $.extend(%7B%7D, $.fn.collapse.defaults, $this.data(),
typeof
@@ -3785,16 +3785,17 @@
& option
+)
%0A i
|
c7b5f85806ba6fc4123cc58c26f6ff000a2a9aa6
|
Update the API to https as github does not all http
|
js/common/dataFactory.js
|
js/common/dataFactory.js
|
(function(){
var dataFactory = function($http){
var url = "http://gateway-a.watsonplatform.net/calls/text/TextGetEmotion";
var APIkey = "4d395301e1cf0abcae8548dfa07cfdad2b96f24c";
var confParam = "&outputMode=json&showSourceText=1&text=";
return {
getText: function(callback){
$http.get('asserts/docs/henry_iv.json').success(callback);
},
getEmotions: function(callback, keyword){
keyword = decodeURI(keyword)
url = url + APIkey + confParam + keyword;
$http.get(url).
success(callback).
error(function(data, status, headers, config) {
console.log('error')
});
}
};
};
dataFactory.$inject = ['$http']
angular.module('EmotionApp').factory('dataFactory', dataFactory);
}());
|
JavaScript
| 0.000007 |
@@ -68,16 +68,17 @@
= %22http
+s
://gatew
|
21c32c9fe49dc9fe507f88af8aeda941056bd123
|
Update map key (uppercase to lowercase)
|
js/components/map-key.js
|
js/components/map-key.js
|
import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import { magnitudeToRadius, depthToColor } from '../earthquake-properties'
import OverlayButton from './overlay-button'
import log from '../logger'
import '../../css/map-key.less'
import '../../css/modal-style.less'
@pureRender
export default class MapKey extends Component {
constructor(props) {
super(props)
this.state = {
opened: false
}
this.open = this.open.bind(this)
this.hide = this.hide.bind(this)
}
open() {
this.setState({opened: true})
log('MapKeyOpened')
}
hide() {
this.setState({opened: false})
}
render() {
const { showBoundariesInfo, volcanoes, earthquakes} = this.props
const { opened } = this.state
return !opened ?
<OverlayButton title='Information about the symbols used on this map' onClick={this.open}>Key</OverlayButton>
:
< div className= 'modal-style map-key-content' >
<i onClick={this.hide} className='close-icon fa fa-close' />
{ earthquakes &&
<table className='magnitude-density'>
<tbody>
<tr><th colSpan='2'>Magnitude</th><th colSpan='2'>Depth</th></tr>
<tr><td>{circle(3)}</td><td>3</td><td>{earthquakeColor(20)}</td><td>0-30 km</td></tr>
<tr><td>{circle(5)}</td><td>5</td><td>{earthquakeColor(50)}</td><td>30-100 km</td></tr>
<tr><td>{circle(6)}</td><td>6</td><td>{earthquakeColor(150)}</td><td>100-200 km</td></tr>
<tr><td>{circle(7)}</td><td>7</td><td>{earthquakeColor(250)}</td><td>200-300 km</td></tr>
<tr><td>{circle(8)}</td><td>8</td><td>{earthquakeColor(400)}</td><td>300-500 km</td></tr>
<tr><td>{circle(9)}</td><td>9</td><td>{earthquakeColor(550)}</td><td>> 500 km</td></tr>
</tbody>
</table>
}
{ showBoundariesInfo &&
<table className='boundaries'>
<tbody>
<tr><th colSpan='2'>Plate boundaries</th></tr>
<tr><td>{boundaryColor('#ffffff')}</td><td>Continental Convergent Boundary</td></tr>
<tr><td>{boundaryColor('#a83800')}</td><td>Continental Transform Fault</td></tr>
<tr><td>{boundaryColor('#ffff00')}</td><td>Continental Rift Boundary</td></tr>
<tr><td>{boundaryColor('#e600a9')}</td><td>Oceanic Convergent Boundary</td></tr>
<tr><td>{boundaryColor('#38a800')}</td><td>Oceanic Transform Fault</td></tr>
<tr><td>{boundaryColor('#bf2026')}</td><td>Oceanic Spreading Rift</td></tr>
<tr><td>{boundaryColor('#508fcb')}</td><td>Subduction Zone</td></tr>
</tbody>
</table>
}
{ volcanoes &&
<table className='volcanoes'>
<tbody>
<tr><th colSpan='2'>Volcano - Time Since Last Eruption</th></tr>
<tr><td>{volcanoColor('#ff6600')}</td><td>Up to 100 years</td></tr>
<tr><td>{volcanoColor('#d26f2d')}</td><td>100-400 years</td></tr>
<tr><td>{volcanoColor('#ac7753')}</td><td>400-1600 years</td></tr>
<tr><td>{volcanoColor('#8c7d73')}</td><td>1600-6400 years</td></tr>
<tr><td>{volcanoColor('#808080')}</td><td>> 6400 years</td></tr>
</tbody>
</table>
}
</div>
}
}
function circle(magnitude) {
return <svg xmlns='http://www.w3.org/2000/svg' width='48' height='48'>
<circle cx='24' cy='24' r={magnitudeToRadius(magnitude)} stroke='black' fill='rgba(0,0,0,0)'/>
</svg>
}
function earthquakeColor(depth) {
return <div className='earthquake-color' style={{backgroundColor: toHexStr(depthToColor(depth))}}></div>
}
function boundaryColor(color) {
return <div className='boundary-color' style={{backgroundColor: color}}></div>
}
function volcanoColor(color) {
return <div className='volcano-marker' style={{borderBottomColor: color}}></div>
}
function toHexStr(d) {
const hex = Number(d).toString(16)
return "#000000".substr(0, 7 - hex.length) + hex
}
|
JavaScript
| 0 |
@@ -2069,17 +2069,17 @@
inental
-C
+c
onvergen
@@ -2072,33 +2072,33 @@
ntal convergent
-B
+b
oundary%3C/td%3E%3C/tr
@@ -2166,17 +2166,17 @@
inental
-T
+t
ransform
@@ -2168,33 +2168,33 @@
ental transform
-F
+f
ault%3C/td%3E%3C/tr%3E%0A
@@ -2263,14 +2263,14 @@
tal
-R
+r
ift
-B
+b
ound
@@ -2346,17 +2346,17 @@
Oceanic
-C
+c
onvergen
@@ -2357,17 +2357,17 @@
vergent
-B
+b
oundary%3C
@@ -2439,17 +2439,17 @@
Oceanic
-T
+t
ransform
@@ -2453,9 +2453,9 @@
orm
-F
+f
ault
@@ -2528,17 +2528,17 @@
Oceanic
-S
+s
preading
@@ -2538,17 +2538,17 @@
reading
-R
+r
ift%3C/td%3E
@@ -2623,9 +2623,9 @@
ion
-Z
+z
one%3C
@@ -2813,25 +2813,25 @@
o -
-T
+t
ime
-S
+s
ince
-L
+l
ast
-E
+e
rupt
|
a393654cd59cbc5d839c60a3c3819abbb2328ab7
|
Add error message on wallet import while the wallet is already open
|
js/controllers/import.js
|
js/controllers/import.js
|
'use strict';
angular.module('copayApp.controllers').controller('ImportController',
function($scope, $rootScope, walletFactory, controllerUtils, Passphrase) {
$scope.title = 'Import a backup';
var reader = new FileReader();
var _importBackup = function(encryptedObj) {
Passphrase.getBase64Async($scope.password, function(passphrase){
var w, errMsg;
try {
w = walletFactory.fromEncryptedObj(encryptedObj, passphrase);
} catch(e) {
errMsg = e.message;
}
if (!w) {
$scope.loading = false;
$rootScope.$flashMessage = { message: errMsg || 'Wrong password', type: 'error'};
$rootScope.$digest();
return;
}
$rootScope.wallet = w;
controllerUtils.startNetwork($rootScope.wallet);
});
};
$scope.openFileDialog = function() {
if (window.cshell) {
return cshell.send('backup:import');
}
$scope.choosefile = !$scope.choosefile;
};
$scope.openPasteArea = function() {
$scope.pastetext = !$scope.pastetext;
};
$scope.getFile = function() {
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var encryptedObj = evt.target.result;
_importBackup(encryptedObj);
}
};
};
$scope.import = function(form) {
if (form.$invalid) {
$scope.loading = false;
$rootScope.$flashMessage = { message: 'There is an error in the form. Please, try again', type: 'error'};
return;
}
var backupFile = $scope.file;
var backupText = form.backupText.$modelValue;
var password = form.password.$modelValue;
if (!backupFile && !backupText) {
$scope.loading = false;
$rootScope.$flashMessage = { message: 'Please, select your backup file or paste the text', type: 'error'};
$scope.loading = false;
return;
}
$scope.loading = true;
if (backupFile) {
reader.readAsBinaryString(backupFile);
}
else {
_importBackup(backupText);
}
};
});
|
JavaScript
| 0 |
@@ -807,24 +807,300 @@
pe.wallet);%0A
+ $rootScope.wallet.on('connectionError', function() %7B%0A var message = %22Looks like you are already connected to this wallet, please logout from it and try importing it again.%22;%0A $rootScope.$flashMessage = %7B message: message, type: 'error'%7D;%0A %7D);%0A
%7D);%0A
|
034312d3586547d57e5f6878c08c7f67beaa7b39
|
Rename showSearchCount_.
|
js/controllers/search.js
|
js/controllers/search.js
|
/**
* @constructor
*/
function SearchController(search) {
this.search_ = search;
$('#search-button').click(this.onSearchButton_.bind(this));
$('#search-input').bind('input', this.onChange_.bind(this));
$('#search-input').keydown(this.onKeydown_.bind(this));
$('#search-next-button').click(this.onFindNext_.bind(this));
$('#search-previous-button').click(this.onFindPrevious_.bind(this));
$('body').focusin(this.onChangeFocus_.bind(this));
}
SearchController.prototype.showSearchCount_ = function() {
if ($('#search-input').val().length === 0) {
$('#search-counting').text('');
return;
}
var searchCount = this.search_.getResultsCount();
var searchIndex = this.search_.getCurrentIndex();
$('#search-counting').text(chrome.i18n.getMessage('searchCounting',
[searchIndex, searchCount]));
if (searchCount === 0) {
$('#search-counting').addClass('nomatches');
} else {
$('#search-counting').removeClass('nomatches');
}
};
SearchController.prototype.findNext_ = function(opt_reverse) {
if (this.search_.getQuery()) {
this.search_.findNext(opt_reverse);
this.showSearchCount_(opt_reverse);
}
};
SearchController.prototype.onSearchButton_ = function() {
this.search_.clear();
var timeout = 200; // keep in sync with the CSS transition.
setTimeout(function() {$('#search-input').select();}, timeout);
$('header').addClass('search-active');
return false;
};
SearchController.prototype.onChangeFocus_ = function() {
if (document.activeElement === document.body ||
$(document.activeElement).parents('.search-container').length) {
return;
}
$('#search-input').val('');
$('#search-counting').text('');
$('header').removeClass('search-active');
this.search_.clear();
};
SearchController.prototype.onChange_ = function() {
var searchString = $('#search-input').val();
if (searchString === this.search_.getQuery())
return;
if (searchString) {
this.search_.find(searchString);
} else {
this.search_.clear();
}
this.showSearchCount_();
};
SearchController.prototype.onKeydown_ = function(e) {
switch (e.keyCode) {
case 13:
e.stopPropagation();
this.findNext_(e.shiftKey /* reverse */);
break;
case 27:
e.stopPropagation();
this.search_.unfocus();
break;
}
};
SearchController.prototype.onFindNext_ = function() {
this.findNext_();
};
SearchController.prototype.onFindPrevious_ = function() {
this.findNext_(true /* reverse */);
};
|
JavaScript
| 0 |
@@ -479,20 +479,22 @@
ototype.
-show
+update
SearchCo
|
2b1dc7280f7e8be28eb7b1ca583212e4ac25be88
|
Update enderecoController.js
|
js/enderecoController.js
|
js/enderecoController.js
|
app.controller('enderecoController', function ($scope, $http, toastr) {
$scope.Endereco = {
id: 0,
logradouro: '',
numero: '',
complemento: '',
bairro: '',
cidade_id: 0,
cidadeName: '',
cep: 0,
latitude: 0,
longetude: 0,
ponto_referencia: ''
};
$scope.EnderecoAdd = {
id: 0,
logradouro: '',
numero: '',
complemento: '',
bairro: '',
cidade_id: 0,
cidadeName: '',
cep: 0,
latitude: 0,
longetude: 0,
ponto_referencia: ''
};
$scope.lstEndereco = true;
$scope.addEndereco = false;
$scope.updtEndereco = false;
$scope.showEditarEndereco = function () {
$scope.addEndereco = false;
$scope.lstEndereco = false;
$scope.updtEndereco = true;
};
$scope.showAddEndereco = function () {
$scope.addEndereco = true;
$scope.lstEndereco = false;
$scope.updtEndereco = false;
};
$scope.showListEndereco = function () {
$scope.addEndereco = false;
$scope.lstEndereco = true;
$scope.updtEndereco = false;
};
$scope.inserirEndereco = function () {
$http.post('api/createEndereco', $scope.EnderecoAdd)
.success(function (data) {
console.log(data);
if (!data.erro) {
$scope.EnderecoAdd = {
id: 0,
descricao: ''
};
toastr.success('Endereço adicionado!', 'Sucesso');
$scope.listarEnderecos();
$scope.showListEndereco();
} else {
toastr.error('Erro no servidor', 'Erro');
}
})
.error(function () {
toastr.error('Erro no servidor', 'Erro');
});
}
$scope.listaEnderecos = {};
$scope.listarEnderecos = function () {
$http.get('api/listarEnderecos')
.success(function (data) {
if (data.result.length == 0) {
toastr.info('Não foram encontrados registos', 'Informação');
} else {
$scope.listaEnderecos = data.result;
}
})
.error(function (data) {
console.log(data);
toastr.error('Erro ao localizar Endereços', 'Erro');
});
};
$scope.editarEndereco = function (idEndereco) {
$http.get('api/getEndereco/' + idEndereco)
.success(function (data) {
$scope.Endereco = data.result;
$scope.showEditarEndereco();
})
.error(function (data) {
toastr.error('Falha em editar Endereço', 'Erro');
console.log(data);
});
};
$scope.excluirEndereco = function (idEndereco) {
$http.get('api/excluirEndereco/' + idEndereco)
.success(function (data) {
toastr.success('Endereço apagado com sucesso', 'Sucesso');
$scope.listarEnderecos();
console.log(data);
})
.error(function (data) {
toastr.error('Falha em excluir Perfil usuario', 'Erro');
console.log(data);
});
};
$scope.alterarEndereco = function () {
$http
.post('api/alterarEndereco/' + $scope.Endereco.id, $scope.Endereco)
.success(function (data) {
if (!data.erro) {
// deu certo a alteração
toastr.success('Endereço atualizado com sucesso', 'Sucesso');
$scope.listarEnderecos();
$scope.showListEndereco();
} else {
toastr.error('Falha em alterar Endereço', 'Erro');
console.log(data);
}
})
.error(function (data) {
toastr.error('Falha em alterar Endereço', 'Erro');
console.log(data);
});
};
$scope.ExibirEndereco = function (idEndereco, latitude, longetude) {
$http.get('api/getEndereco/' + idEndereco)
.success(function (data) {
$('#mapaPainel').show();
initialize(latitude, longetude, data.result);
})
.error(function (data) {
toastr.error('Falha em visualizar', 'Erro');
});
if ($scope.Endereco.id == 0) {
return false;
} else {
return true;
}
};
$scope.listaCidades = {};
$scope.listarCidades = function () {
$http.get('api/listarCidades')
.success(function (data) {
if (data.result.length == 0) {
toastr.info('Não foram encontrados registos', 'Informação');
} else {
$scope.listaCidades = data.result;
}
})
.error(function (data) {
//alert("Falha em obter usuarios");
console.log(data);
toastr.error('Erro ao localizar Usuarios', 'Erro');
});
};
$scope.listarEnderecos();
$scope.listarCidades();
})
|
JavaScript
| 0 |
@@ -1014,32 +1014,357 @@
ndereco = false;
+%0A%0A $scope.EnderecoAdd = %7B%0A id: 0,%0A logradouro: '',%0A numero: '',%0A complemento: '',%0A bairro: '',%0A cidade_id: 0,%0A cidadeName: '',%0A cep: 0,%0A latitude: 0,%0A longetude: 0,%0A ponto_referencia: ''%0A %7D;
%0A %7D;%0A%0A $sc
|
f05accb2f5c836e8d992006ad06b5bfdf705f37a
|
add unit test
|
src/web_client/test/unit/specs/sidebar.spec.js
|
src/web_client/test/unit/specs/sidebar.spec.js
|
/*
import dependencies
*/
import Vue from 'vue'
import Sidebar from '@/components/Sidebar'
import ElementUI from 'element-ui'
import VueResource from 'vue-resource'
import VueLocalStorage from 'vue-localstorage'
import VueRouter from 'vue-router'
/*
inject dependencies
*/
Vue.use(ElementUI)
Vue.use(VueLocalStorage)
Vue.use(VueResource)
Vue.use(VueRouter)
/*
test
*/
describe('Sidebar.vue', () => {
it('should successfully get report', () => {
Vue.localStorage.set('zeusId', 1)
const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
promiseCall.resolves({
body: {
report: {
accuracy: '0',
similar_case: '5',
similar_precedents: [
{
precedent: 'AZ-1',
outcomes: {
o1: true
},
facts: {
f1: true
}
}
],
curves: [],
data_set: '1000',
outcomes: {
o1: true
}
}
}
})
const spy = sinon.spy(Sidebar.methods, 'createPrecedentTable')
const vm = new Vue(Sidebar).$mount()
vm.view()
expect(spy.called).to.be.true
Sidebar.methods.createPrecedentTable.restore()
Vue.localStorage.remove('zeusId')
Vue.http.get.restore()
})
it('should successfully get report', () => {
Vue.localStorage.set('zeusId', 1)
const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
promiseCall.resolves({
body: {
report: {
accuracy: '0',
similar_case: '5',
similar_precedents: [
{
precedent: 'AZ-1',
outcomes: {
o1: true
},
facts: {
f1: true
}
}
],
curves: [{
name: {}
}],
data_set: '1000',
outcomes: {
o1: true
}
}
}
})
const spy = sinon.spy(Sidebar.methods, 'createPrecedentTable')
const vm = new Vue(Sidebar).$mount()
vm.view()
expect(spy.called).to.be.true
Sidebar.methods.createPrecedentTable.restore()
Vue.localStorage.remove('zeusId')
Vue.http.get.restore()
})
it('should fail to get report', () => {
Vue.localStorage.set('zeusId', 1)
const promiseCall = sinon.stub(Vue.http, 'get').returnsPromise()
promiseCall.rejects()
const spy = sinon.spy(Sidebar.methods, 'createPrecedentTable')
const vm = new Vue(Sidebar).$mount()
vm.view()
expect(spy.called).to.be.false
Sidebar.methods.createPrecedentTable.restore()
Vue.localStorage.remove('zeusId')
Vue.http.get.restore()
})
it('should successfully submit feedback', () => {
const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
promiseCall.resolves()
const vm = new Vue(Sidebar).$mount()
vm.openFeedbackModal = true
vm.feedback = 'Hello'
vm.submitFeedback()
expect(vm.connectionError).to.be.false
Vue.http.post.restore()
})
it('should fail to submit feedback', () => {
const promiseCall = sinon.stub(Vue.http, 'post').returnsPromise()
promiseCall.rejects()
const vm = new Vue(Sidebar).$mount()
vm.openFeedbackModal = true
vm.feedback = 'Hello'
vm.submitFeedback()
expect(vm.connectionError).to.be.true
Vue.http.post.restore()
})
it('should validate empty feedback', () => {
const vm = new Vue(Sidebar).$mount()
vm.openFeedbackModal = true
vm.feedback = ''
vm.submitFeedback()
expect(vm.connectionError).to.be.false
})
it('should reset chat', () => {
const Component = Vue.extend(Sidebar)
const vm = new Component({
router: new VueRouter({
routes: [
{
path: '/'
}
]
})
}).$mount()
Vue.localStorage.set('zeusId', 1)
Vue.localStorage.set('username', 'Bruce Wayne')
Vue.localStorage.set('usertype', 'tenant')
vm.resetChat()
expect(Vue.localStorage.get('zeusId')).to.be.equal(null)
expect(Vue.localStorage.get('username')).to.be.equal(null)
expect(Vue.localStorage.get('usertype')).to.be.equal(null)
Vue.localStorage.remove('zeusId')
Vue.localStorage.remove('username')
Vue.localStorage.remove('usertype')
})
})
|
JavaScript
| 0 |
@@ -240,16 +240,68 @@
-router'
+%0Aimport %7B EventBus %7D from '@/components/EventBus.js'
%0A%0A/*%0Ainj
@@ -451,16 +451,240 @@
) =%3E %7B%0A%0A
+ it('should successfully listen to event', () =%3E %7B%0A const vm = new Vue(Sidebar).$mount()%0A EventBus.$emit('hideSidebar', %7B%0A progress: 50%0A %7D)%0A expect(vm.progress).to.equal(50)%0A %7D)%0A%0A
it('
|
ff1c302ab2bd05129d13c4a6520f670632e6fb37
|
initialize MediaQuery in global Foundation entry
|
js/entries/foundation.js
|
js/entries/foundation.js
|
import $ from 'jquery';
import { Foundation } from '../foundation.core';
import * as CoreUtils from '../foundation.core.utils';
import { Box } from '../foundation.util.box'
import { onImagesLoaded } from '../foundation.util.imageLoader';
import { Keyboard } from '../foundation.util.keyboard';
import { MediaQuery } from '../foundation.util.mediaQuery';
import { Motion, Move } from '../foundation.util.motion';
import { Nest } from '../foundation.util.nest';
import { Timer } from '../foundation.util.timer';
import { Touch } from '../foundation.util.touch';
import { Triggers } from '../foundation.util.triggers';
import { Abide } from '../foundation.abide';
import { Accordion } from '../foundation.accordion';
import { AccordionMenu } from '../foundation.accordionMenu';
import { Drilldown } from '../foundation.drilldown';
import { Dropdown } from '../foundation.dropdown';
import { DropdownMenu } from '../foundation.dropdownMenu';
import { Equalizer } from '../foundation.equalizer';
import { Interchange } from '../foundation.interchange';
import { Magellan } from '../foundation.magellan';
import { OffCanvas } from '../foundation.offcanvas';
import { Orbit } from '../foundation.orbit';
import { ResponsiveMenu } from '../foundation.responsiveMenu';
import { ResponsiveToggle } from '../foundation.responsiveToggle';
import { Reveal } from '../foundation.reveal';
import { Slider } from '../foundation.slider';
import { SmoothScroll } from '../foundation.smoothScroll';
import { Sticky } from '../foundation.sticky';
import { Tabs } from '../foundation.tabs';
import { Toggler } from '../foundation.toggler';
import { Tooltip } from '../foundation.tooltip';
import { ResponsiveAccordionTabs } from '../foundation.responsiveAccordionTabs';
Foundation.addToJquery($);
// Add Foundation Utils to Foundation global namespace for backwards
// compatibility.
Foundation.rtl = CoreUtils.rtl;
Foundation.GetYoDigits = CoreUtils.GetYoDigits;
Foundation.transitionend = CoreUtils.transitionend;
Foundation.RegExpEscape = CoreUtils.RegExpEscape;
Foundation.onLoad = CoreUtils.onLoad;
Foundation.Box = Box;
Foundation.onImagesLoaded = onImagesLoaded;
Foundation.Keyboard = Keyboard;
Foundation.MediaQuery = MediaQuery;
Foundation.Motion = Motion;
Foundation.Move = Move;
Foundation.Nest = Nest;
Foundation.Timer = Timer;
// Touch and Triggers previously were almost purely sede effect driven,
// so no need to add it to Foundation, just init them.
Touch.init($);
Triggers.init($, Foundation);
Foundation.plugin(Abide, 'Abide');
Foundation.plugin(Accordion, 'Accordion');
Foundation.plugin(AccordionMenu, 'AccordionMenu');
Foundation.plugin(Drilldown, 'Drilldown');
Foundation.plugin(Dropdown, 'Dropdown');
Foundation.plugin(DropdownMenu, 'DropdownMenu');
Foundation.plugin(Equalizer, 'Equalizer');
Foundation.plugin(Interchange, 'Interchange');
Foundation.plugin(Magellan, 'Magellan');
Foundation.plugin(OffCanvas, 'OffCanvas');
Foundation.plugin(Orbit, 'Orbit');
Foundation.plugin(ResponsiveMenu, 'ResponsiveMenu');
Foundation.plugin(ResponsiveToggle, 'ResponsiveToggle');
Foundation.plugin(Reveal, 'Reveal');
Foundation.plugin(Slider, 'Slider');
Foundation.plugin(SmoothScroll, 'SmoothScroll');
Foundation.plugin(Sticky, 'Sticky');
Foundation.plugin(Tabs, 'Tabs');
Foundation.plugin(Toggler, 'Toggler');
Foundation.plugin(Tooltip, 'Tooltip');
Foundation.plugin(ResponsiveAccordionTabs, 'ResponsiveAccordionTabs');
export {
Foundation,
CoreUtils,
Box,
onImagesLoaded,
Keyboard,
MediaQuery,
Motion,
Nest,
Timer,
Touch,
Triggers,
Abide,
Accordion,
AccordionMenu,
Drilldown,
Dropdown,
DropdownMenu,
Equalizer,
Interchange,
Magellan,
OffCanvas,
Orbit,
ResponsiveMenu,
ResponsiveToggle,
Reveal,
Slider,
SmoothScroll,
Sticky,
Tabs,
Toggler,
Tooltip,
ResponsiveAccordionTabs
}
export default Foundation;
|
JavaScript
| 0.000005 |
@@ -2488,16 +2488,36 @@
dation);
+%0AMediaQuery._init();
%0A%0AFounda
|
d99ea4d427899c02fb97373a26fe7c803bd72507
|
Fix memento demo.
|
js/foam/demos/Memento.js
|
js/foam/demos/Memento.js
|
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
name: 'Memento',
package: 'foam.demos',
traits: [
'foam.memento.MemorableTrait'
],
requires: [
'foam.demos.MemorableObject',
'foam.demos.SubMemorableObject',
'foam.memento.FragmentMementoMgr',
'foam.ui.JSView'
],
properties: [
{
name: 'object',
memorable: true,
view: 'foam.ui.DetailView',
factory: function() {
return this.MemorableObject.create({
view: 'tree',
subProperty: this.SubMemorableObject.create({
title: 'hello',
mode: 'read-write',
zoomLevel: 0.543
})
});
}
},
{
name: 'memento',
view: 'foam.ui.JSView',
hidden: false
},
{
name: 'mementoMgr',
hidden: true,
factory: function() {
return this.FragmentMementoMgr.create({
mementoValue: this.memento$
});
}
}
]
});
|
JavaScript
| 0 |
@@ -871,16 +871,47 @@
.JSView'
+,%0A 'foam.ui.StringArrayView'
%0A %5D,%0A%0A
|
4f4cfa838cdb2d81455cf031b7485789d26d4629
|
change job getType to getJobType and add getType method that returns job so that job references can be properly built
|
js/gitana/cluster/Job.js
|
js/gitana/cluster/Job.js
|
(function(window)
{
var Gitana = window.Gitana;
Gitana.Job = Gitana.AbstractClusterObject.extend(
/** @lends Gitana.Job.prototype */
{
/**
* @constructs
* @augments Gitana.AbstractClusterObject
*
* @class Job
*
* @param {Gitana.Cluster} cluster
* @param [Object] object json object (if no callback required for populating)
*/
constructor: function(cluster, object)
{
this.base(cluster, object);
this.objectType = function() { return "Gitana.Job"; };
},
/**
* @override
*/
clone: function()
{
return new Gitana.Job(this.getCluster(), this);
},
/**
* @override
*/
getUri: function()
{
return "/jobs/" + this.getId();
},
/**
* @returns {String} the type id of the job
*/
getType: function()
{
return this.get("type");
},
/**
* @returns {String} the id of the principal that this job will run as
*/
getRunAsPrincipalId: function()
{
return this.get("runAsPrincipal");
},
/**
* @returns {String} the domain of the principal that this job will run as
*/
getRunAsPrincipalDomainId: function()
{
return this.get("runAsPrincipalDomain");
},
/**
* @returns {String} the state of the job
*/
getState: function()
{
return this.get("state");
},
/**
* @returns {String} the platform id
*/
getPlatformId: function()
{
return this.get("platformId");
},
/**
* @returns {Number} the priority of the job
*/
getPriority: function()
{
return this.get("priority");
},
/**
* @returns {Number} the number of attempts made to run this job
*/
getAttempts: function()
{
return this.get("attempts");
},
/**
* @returns {Object} when the job is scheduled to start (or null)
*/
getScheduledStartTime: function()
{
return this.get("schedule_start_ms");
},
/**
* @returns [Array] array of status log objects
*/
getLogEntries: function()
{
return this.get("log_entries");
},
getCurrentThread: function()
{
return this.get("current_thread");
},
getCurrentServer: function()
{
return this.get("current_server");
},
getCurrentServerTimeStamp: function()
{
return this.get("current_server_timestamp");
},
getSubmittedBy: function()
{
return this.get("submitted_by");
},
getSubmittedTimestamp: function()
{
return this.get("submitted_timestamp");
},
getStarted: function()
{
return this.get("started");
},
getStartedBy: function()
{
return this.get("started_by");
},
getStartedTimestamp: function()
{
return this.get("started_timestamp");
},
getStopped: function()
{
return this.get("stopped");
},
getStoppedTimestamp: function()
{
return this.get("stopped_timestamp");
},
getPaused: function()
{
return this.get("paused");
},
getPausedBy: function()
{
return this.get("paused_by");
},
getPausedTimestamp: function()
{
return this.get("paused_timestamp");
},
//////////////////////////////////////////////////////////////////////////////////////////
//
// ATTACHMENTS
//
//////////////////////////////////////////////////////////////////////////////////////////
/**
* Hands back an attachments map.
*
* @chained attachment map
*
* @param local
*
* @public
*/
listAttachments: Gitana.Methods.listAttachments(),
/**
* Picks off a single attachment
*
* @chained attachment
*
* @param attachmentId
*/
attachment: function(attachmentId)
{
return this.listAttachments().select(attachmentId);
},
/**
* Creates an attachment.
*
* When using this method from within the JS driver, it really only works for text-based content such
* as JSON or text.
*
* @chained attachment
*
* @param attachmentId (use null or false for default attachment)
* @param contentType
* @param data
*/
attach: Gitana.Methods.attach(),
/**
* Deletes an attachment.
*
* @param attachmentId
*/
unattach: Gitana.Methods.unattach(),
/**
* Generates a URI to a preview resource.
*/
getPreviewUri: Gitana.Methods.getPreviewUri()
});
})(window);
|
JavaScript
| 0 |
@@ -975,16 +975,19 @@
get
+Job
Type: fu
@@ -1046,32 +1046,135 @@
%22);%0A %7D,%0A%0A
+ getType: function()%0A %7B%0A return Gitana.TypedIDConstants.TYPE_JOB;%0A %7D,%0A%0A
/**%0A
|
f6506869907fab885713082ef5fb930776b500f7
|
Add method to get/set 'socketDisabled' property of a port in module-unit
|
js/models/module-unit.js
|
js/models/module-unit.js
|
(function(app) {
'use strict';
var helper = app.helper || require('../helper.js');
var ModuleUnit = function(props) {
this.module = props.module;
this.port = props.port;
};
ModuleUnit.prototype.equal = function(other) {
if (!other)
return false;
return Object.keys(this).every(function(key) {
return helper.equal(this[key], other[key]);
}.bind(this));
};
ModuleUnit.prototype.portType = function() {
return this.port.type();
};
ModuleUnit.prototype.portPlugDisabled = function(value) {
return this.port.plugDisabled(value);
};
ModuleUnit.prototype.portVisible = function(value) {
return this.port.visible(value);
};
ModuleUnit.prototype.portSocketConnected = function(value) {
return this.port.socketConnected(value);
};
ModuleUnit.prototype.portPlugHighlighted = function(value) {
return this.port.plugHighlighted(value);
};
ModuleUnit.prototype.portSocketHighlighted = function(value) {
return this.port.socketHighlighted(value);
};
ModuleUnit.prototype.circuitElementMember = function() {
return this.module.circuitElementMember(this.port.name());
};
ModuleUnit.prototype.plugPosition = function() {
return this.module.plugPosition(this.port);
};
ModuleUnit.prototype.socketPosition = function() {
return this.module.socketPosition(this.port);
};
ModuleUnit.prototype.labelHighlighted = function(value) {
this.port.labelHighlighted(value);
// module is deletable if all port labels are NOT highlighted
this.module.deletable(this.module.ports().every(function(port) {
return !port.labelHighlighted();
}));
};
ModuleUnit.prototype.addRelation = function(relation) {
this.module.relations().push(relation);
this.port.relations().push(relation);
};
ModuleUnit.prototype.removeRelation = function(relation) {
helper.remove(this.module.relations(), relation);
helper.remove(this.port.relations(), relation);
};
ModuleUnit.fromModuleAndPortName = function(module, portName) {
if (!module)
return null;
var port = module.port(portName);
if (!port)
return null;
return new ModuleUnit({ module: module, port: port });
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleUnit;
else
app.ModuleUnit = ModuleUnit;
})(this.app || (this.app = {}));
|
JavaScript
| 0 |
@@ -578,32 +578,144 @@
d(value);%0A %7D;%0A%0A
+ ModuleUnit.prototype.portSocketDisabled = function(value) %7B%0A return this.port.socketDisabled(value);%0A %7D;%0A%0A
ModuleUnit.pro
|
09734bac7e16fd0a71289f207a7d98339fd92769
|
Remove unnecessary frame callback function
|
js/popcorn.responsive.js
|
js/popcorn.responsive.js
|
(function (Popcorn) {
'use strict';
var instances = {},
resizeTimeout,
lastResize = 0,
windowWidth = 0,
windowHeight = 0,
RESIZE_THROTTLE = 30;
function resize(popcorn) {
var instance = instances[popcorn.id],
list,
videoAspect,
windowAspect,
options,
video,
scale,
min,
clipDim,
videoWidth,
videoHeight,
transform = '';
if (!instance) {
return;
}
list = instance.events;
//todo: loop, match min/max aspect. for (i = 0; )
options = list[0];
video = popcorn.media;
if (options) {
videoWidth = video.videoWidth;
videoHeight = video.videoHeight;
videoAspect = videoWidth / videoHeight;
windowAspect = windowWidth / windowHeight;
if (windowAspect > videoAspect) {
//window is not tall enough
scale = windowWidth / videoWidth;
min = options.y;
clipDim = videoWidth / windowAspect;
if (clipDim < options.height) {
//window is REALLY not tall enough, so we need to pillarbox
scale = windowHeight / options.height;
transform = 'scale(' + scale + ') translate(' +
(windowWidth - videoWidth * scale) / 2 + 'px, ' +
-min +
'px)';
} else {
transform = 'scale(' + scale + ') translateY(' +
-((videoHeight - clipDim) * min / (videoHeight - options.height)) +
'px)';
}
} else {
//window is not wide enough
scale = windowHeight / videoHeight;
min = options.x;
clipDim = videoHeight * windowAspect;
if (clipDim < options.width) {
//window is REALLY not wide enough, so we need to letterbox
scale = windowWidth / options.width;
transform = 'scale(' + scale + ') translate(' +
-min + 'px,' +
(windowHeight - videoHeight * scale) / 2 +
'px)';
} else {
transform = 'scale(' + scale + ') translateX(' +
-((videoWidth - clipDim) * min / (videoWidth - options.width)) +
'px)';
}
}
}
video.style.webkitTransform = transform;
video.style.msTransform = transform;
video.style.mozTransform = transform;
video.style.transform = transform;
}
function resizeAll() {
lastResize = Date.now();
if (windowHeight === window.innerHeight &&
windowWidth === window.innerWidth) {
return;
}
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
Popcorn.instances.forEach(resize);
}
function resizeWindow() {
if (Date.now() - lastResize < RESIZE_THROTTLE) {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeTimeout, RESIZE_THROTTLE);
} else {
resizeAll();
}
}
function sortEvents(a, b) {
if (a.minAspect !== b.minAspect) {
return b.minAspect - a.minAspect;
}
if (a.maxAspect !== b.maxAspect) {
return b.maxAspect - a.maxAspect;
}
}
function addEvent(popcorn, event) {
var instance = instances[popcorn.id];
if (!instance) {
instance = instances[popcorn.id] = {
events: [],
x: -1,
y: -1
};
popcorn.on('loadedmetadata', function () {
resize(popcorn);
});
}
if (instance.events.indexOf(event) < 0) {
instance.events.push(event);
instance.events.sort(sortEvents);
resize(popcorn);
}
return instance;
}
function removeEvent(popcorn, event) {
var instance = instances[popcorn.id],
list = instance && instance.events,
index;
if (list) {
index = list.indexOf(event);
if (index >= 0) {
list.splice(index, 1);
resize(popcorn);
}
}
}
/*
todo: only attach these if there is at least one event,
detach when the last event is destroyed
*/
window.addEventListener('resize', resizeWindow, false);
window.addEventListener('orientationchange', resizeAll, false);
resizeAll();
Popcorn.basePlugin('responsive', function (options, base) {
var popcorn = base.popcorn;
base.animate('x', function () {
resize(popcorn);
});
base.animate('y', function () {
resize(popcorn);
});
base.animate('width', function () {
resize(popcorn);
});
base.animate('height', function () {
resize(popcorn);
});
return {
start: function() {
addEvent(popcorn, base.options);
},
frame: function () {
/*
only update if this is the highest-priority active instance
that matches
*/
},
end: function() {
removeEvent(popcorn, base.options);
}
};
}, {
about: {
name: 'Popcorn Responsive Video Plugin',
version: '0.1',
author: 'Brian Chirls, @bchirls',
website: 'http://github.com/brianchirls'
}
});
}(window.Popcorn));
|
JavaScript
| 0.000006 |
@@ -4083,133 +4083,8 @@
%09%7D,%0A
-%09%09%09frame: function () %7B%0A%09%09%09%09/*%0A%09%09%09%09only update if this is the highest-priority active instance%0A%09%09%09%09that matches%0A%09%09%09%09*/%0A%09%09%09%7D,%0A
%09%09%09e
|
eb83c86eedd594f79f21b2e334187a4d752fa75a
|
update tests for new asset handling
|
packages/spec/serve.spec.js
|
packages/spec/serve.spec.js
|
/* eslint-env node, jest */
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var fetch = require('isomorphic-fetch');
var originalDir = process.cwd();
var appDir = path.resolve(__dirname, 'fixtures', 'integration');
var buildDir = path.resolve(appDir, 'build');
var cacheDir = path.resolve(appDir, 'node_modules', '.cache', 'hops');
describe('production server', function() {
jest.setTimeout(100000);
var app;
beforeAll(function(done) {
rimraf.sync(buildDir);
rimraf.sync(cacheDir);
mkdirp.sync(cacheDir);
process.chdir(appDir);
jest.resetModules();
require('hops-build').runBuild({ clean: true }, function() {
require('hops-express').runServer({}, function(error, _app) {
app = _app;
done(error);
});
});
});
afterAll(function() {
app.close();
process.chdir(originalDir);
});
it('should create server.js', function() {
var filePath = path.resolve(cacheDir, 'server.js');
expect(fs.existsSync(filePath)).toBe(true);
});
it('should create manifest file', function() {
var filePath = path.join(buildDir, 'stats.json');
expect(fs.existsSync(filePath)).toBe(true);
var manifest = require(filePath);
expect(manifest).toMatchObject({
assetsByChunkName: {
main: expect.any(Array),
},
});
});
it('should create build files', function() {
var fileNames = fs.readdirSync(buildDir);
expect(fileNames).toContainEqual(
expect.stringMatching(/^main-[0-9a-f]+\.js$/)
);
expect(fileNames).toContainEqual(
expect.stringMatching(/^vendor-[0-9a-f]+\.js$/)
);
expect(fileNames).toContainEqual(
expect.stringMatching(/^main-[0-9a-f]+\.css$/)
);
});
it('should deliver expected html page', function() {
return fetch('http://localhost:8080/')
.then(function(response) {
expect(response.ok).toBe(true);
return response.text();
})
.then(function(body) {
expect(body.length).toBeGreaterThan(0);
expect(body).toMatch('<!doctype html>');
expect(body).toMatch('Hello World!');
});
});
it('should deliver all asset files', function() {
var manifest = require(path.resolve(buildDir, 'stats.json'));
var assetsByChunkName = manifest.assetsByChunkName;
expect(manifest).toMatchObject({
assetsByChunkName: {
main: expect.any(Array),
vendor: expect.any(Array),
},
});
return Promise.all(
assetsByChunkName.main
.concat(assetsByChunkName.vendor)
.map(function(filename) {
return fetch('http://localhost:8080/' + filename)
.then(function(response) {
expect(response.ok).toBe(true);
return response.text();
})
.then(function(body) {
expect(body.length).toBeGreaterThan(0);
expect(body).not.toMatch('<!doctype html>');
expect(body).toBe(
fs.readFileSync(
path.resolve(buildDir, filename.replace(/^\/?/, '')),
'utf8'
)
);
});
})
);
});
it('should deliver 404 when route does not match', function() {
return expect(
fetch('http://localhost:8080/thisdoesnotexist')
).resolves.toMatchObject({
status: 404,
});
});
it('adds server-timing header', function() {
return fetch('http://localhost:8080/').then(function(response) {
expect(response.headers.get('server-timing')).toMatch('desc="Request"');
});
});
});
|
JavaScript
| 0.000001 |
@@ -1310,33 +1310,43 @@
%7B%0A
-assetsByChunkName
+entrypoints: %7B%0A main
: %7B%0A
@@ -1341,36 +1341,84 @@
main: %7B%0A
+
-main
+chunks: %5B'vendors~main', 'main'%5D,%0A assets
: expect.any(Arr
@@ -1414,32 +1414,43 @@
ect.any(Array),%0A
+ %7D,%0A
%7D,%0A %7D);
@@ -1722,16 +1722,22 @@
/%5Evendor
+s~main
-%5B0-9a-f
@@ -2381,318 +2381,54 @@
));%0A
- var assetsByChunkName = manifest.assetsByChunkName;%0A%0A expect(manifest).toMatchObject(%7B%0A assetsByChunkName: %7B%0A main: expect.any(Array),%0A vendor: expect.any(Array),%0A %7D,%0A %7D);%0A%0A return Promise.all(%0A assetsByChunkName.main%0A .concat(assetsByChunkName.vendor)%0A
+%0A return Promise.all(%0A manifest.assets
.map
@@ -2441,22 +2441,17 @@
ion(
-filename
+asset
) %7B%0A
-
@@ -2498,20 +2498,20 @@
' +
-file
+asset.
name)%0A
-
@@ -2551,26 +2551,24 @@
-
-
expect(respo
@@ -2595,26 +2595,24 @@
-
return respo
@@ -2619,26 +2619,24 @@
nse.text();%0A
-
%7D)
@@ -2638,34 +2638,32 @@
%7D)%0A
-
.then(function(b
@@ -2665,26 +2665,24 @@
ion(body) %7B%0A
-
@@ -2725,34 +2725,32 @@
0);%0A
-
-
expect(body).not
@@ -2782,34 +2782,32 @@
');%0A
-
expect(body).toB
@@ -2809,18 +2809,16 @@
).toBe(%0A
-
@@ -2856,18 +2856,16 @@
-
path.res
@@ -2879,20 +2879,22 @@
ildDir,
-file
+asset.
name.rep
@@ -2928,18 +2928,16 @@
-
'utf8'%0A
@@ -2949,18 +2949,16 @@
-
)%0A
@@ -2963,23 +2963,19 @@
-
-
);%0A
-
@@ -2980,18 +2980,16 @@
%7D);%0A
-
%7D)
|
310eb0a088e8d1d222c94e90f3fd4480bf702c31
|
Remove special query for vehicle type combobox
|
demo/js/components/dashboard/combobox-selector.js
|
demo/js/components/dashboard/combobox-selector.js
|
angular.module("yds").directive("ydsComboboxSelector", ["$timeout", "DashboardService", "Data",
function ($timeout, DashboardService, Data) {
return {
restrict: "E",
scope: {
title: "@", // Title
type: "@", // Field facet
dashboardId: "@", // ID to use for saving the value in DashboardService
selectionType: "@" // Selection type for DashboardService
},
templateUrl: Data.templatePath + "templates/dashboard/combobox-selector.html",
link: function (scope, element, attrs) {
var selectivityContainer = _.first(angular.element(element[0].querySelector(".selectivity-container")));
var type = scope.type;
var dashboardId = scope.dashboardId;
var selectionType = scope.selectionType;
// Check if dashboardId attribute is defined, else assign default value
if (_.isUndefined(dashboardId) || dashboardId.length === 0)
dashboardId = "default";
scope.selection = "";
// Set query depending on selection type
var query = "*";
if (selectionType === "trafficobservation.vehicle_type") {
query = "type:TrafficObservation AND -vehicleType.label.en:Total AND -vehicleType.label.en:MC " +
"AND -vehicleType.label.en:\"LGV/PSV 2Axle\" AND -vehicleType.label.en:\"M'Cycle \& P'Cycle\"" +
" AND -vehicleType.label.en:\"OGV1/PSV 3Axle\" AND -vehicleType.label.en:PC " +
"AND -vehicleType.label.en:OGV1 AND -vehicleType.label.en:OGV2 AND -vehicleType.label.en:PSV";
}
Data.getComboboxFacetItems(query, type)
.then(function (response) {
scope.selection = _.first(response);
var selectivity = $(selectivityContainer).selectivity({
items: response,
multiple: true,
placeholder: "Select " + scope.title
});
$(selectivity).on("change", function (e) {
var newValue = null;
if (e.value.length > 0) {
newValue = e.value.join(",");
}
scope.selectionChanged(newValue);
});
});
/**
* Save the new selection to the DashboardService with the given selection type
* @param newSelection New selected option
*/
scope.selectionChanged = function (newSelection) {
DashboardService.saveObject(selectionType, newSelection);
};
}
};
}
]);
|
JavaScript
| 0 |
@@ -1149,654 +1149,8 @@
%22;%0A%0A
- // Set query depending on selection type%0A var query = %22*%22;%0A if (selectionType === %22trafficobservation.vehicle_type%22) %7B%0A query = %22type:TrafficObservation AND -vehicleType.label.en:Total AND -vehicleType.label.en:MC %22 +%0A %22AND -vehicleType.label.en:%5C%22LGV/PSV 2Axle%5C%22 AND -vehicleType.label.en:%5C%22M'Cycle %5C& P'Cycle%5C%22%22 +%0A %22 AND -vehicleType.label.en:%5C%22OGV1/PSV 3Axle%5C%22 AND -vehicleType.label.en:PC %22 +%0A %22AND -vehicleType.label.en:OGV1 AND -vehicleType.label.en:OGV2 AND -vehicleType.label.en:PSV%22;%0A %7D%0A%0A
@@ -1188,21 +1188,19 @@
etItems(
-query
+%22*%22
, type)%0A
|
6684cde907da17ad26e9485e92e7431b18b4869f
|
Add new methods to tests in package
|
packages/youtube/package.js
|
packages/youtube/package.js
|
Package.describe({
name: 'pntbr:youtube',
version: '0.0.1',
summary: 'Manage Youtube\'s videos',
git: 'https://github.com/goacademie/fanhui',
documentation: 'README.md'
})
Package.onUse(function(api) {
api.versionsFrom('1.2.1')
api.use(['ecmascript', 'mongo'])
api.use(['iron:router', 'templating', 'session'], 'client')
api.addFiles('collection.js')
api.addFiles(['server/model.js'], 'server')
api.addFiles([
'client/youtube.html',
'client/style.css',
'client/router.js',
'client/list-vdos.html',
'client/list-vdos.js',
'client/insert-vdo.html',
'client/insert-vdo.js'
], 'client')
api.export(['notifBadYoutubeId'], 'client')
api.export('Vdos', 'server')
api.export(['Vdos', 'youtubeIdCheckLength'], 'client') // test
})
Package.onTest(function(api) {
api.use(['ecmascript', 'tinytest', 'pntbr:youtube'])
api.use(['iron:[email protected]', 'templating'], 'client')
api.addFiles('tests-stubs.js')
api.addFiles('tests-youtube.js')
})
|
JavaScript
| 0.000001 |
@@ -706,18 +706,16 @@
erver')%0A
-
api.ex
@@ -720,23 +720,32 @@
export(%5B
+%0A
'Vdos',
+%0A
'youtub
@@ -759,16 +759,124 @@
kLength'
+,%0A 'queryValueByFieldName',%0A 'checkTitle',%0A 'categoryByTitle',%0A 'dateByTitle',%0A 'rankByTitle'
%5D, 'clie
@@ -883,16 +883,8 @@
nt')
- // test
%0A%7D)%0A
|
24c35ee86b102e5c4fb5e28ffbdba14479db26a6
|
Add EditIdeaDialog state unit test
|
desktop/src/Idea/__tests__/EditIdeaDialog.spec.js
|
desktop/src/Idea/__tests__/EditIdeaDialog.spec.js
|
/* eslint-env mocha, jest */
import getDefault from '../../shared/testUtils';
import EditIdeaDialog from '../EditIdeaDialog';
const defaultProps = {
open: false,
idea: '',
onRequestClose() {},
onRequestEdit() {},
};
const getActualDialog = getDefault(EditIdeaDialog, defaultProps);
it('should render', () => {
getActualDialog();
});
it('should be a <div />', () => {
const wrapper = getActualDialog();
expect(wrapper.is('div.EditIdeaDialog')).toBe(true);
});
it('should have a <Dialog />', () => {
const wrapper = getActualDialog();
expect(wrapper.find('Dialog').length).toBe(1);
});
it('should show/hide <Dialog /> based on props', () => {
const wrapper = getActualDialog({
open: true,
});
expect(wrapper.find('Dialog').prop('open')).toBe(true);
});
it('should set text field default value based on props', () => {
const wrapper = getActualDialog({
idea: 'a cool idea',
});
expect(wrapper.find('TextField').prop('defaultValue')).toBe('a cool idea');
});
it('should call onRequestClose in handling close request', (done) => {
const wrapper = getActualDialog({
onRequestClose() {
done();
},
});
wrapper.instance().handleRequestClose();
});
it('should call onRequestEdit in handling edit request', (done) => {
const wrapper = getActualDialog({
onRequestEdit() {
done();
},
});
wrapper.instance().handleRequestEdit();
});
|
JavaScript
| 0 |
@@ -1385,16 +1385,282 @@
uestEdit();%0A%7D);%0A
+%0Ait('should set FlatButton disabled based on state', () =%3E %7B%0A const wrapper = getActualDialog();%0A wrapper.find('TextField').props().onChange(%7B target: %7B value: 'a cool idea' %7D %7D);%0A expect(wrapper.find('Dialog').prop('actions')%5B0%5D.props.disabled).toBe(false);%0A%7D);%0A
|
3ea4c1e80fa0b043e073efd5e4e0a159fd8401df
|
Add EditTaskDialog state unit test
|
desktop/src/Task/__tests__/EditTaskDialog.spec.js
|
desktop/src/Task/__tests__/EditTaskDialog.spec.js
|
/* eslint-env mocha, jest */
import getDefault from '../../shared/testUtils';
import EditTaskDialog from '../EditTaskDialog';
const defaultProps = {
open: false,
task: '',
onRequestClose() {},
onRequestEdit() {},
};
const getActualDialog = getDefault(EditTaskDialog, defaultProps);
it('should render', () => {
getActualDialog();
});
it('should be a <div />', () => {
const wrapper = getActualDialog();
expect(wrapper.is('div.EditTaskDialog')).toBe(true);
});
it('should have a <Dialog />', () => {
const wrapper = getActualDialog();
expect(wrapper.find('Dialog').length).toBe(1);
});
it('should show/hide <Dialog /> based on props', () => {
const wrapper = getActualDialog({ open: true });
expect(wrapper.find('Dialog').prop('open')).toBe(true);
});
it('should set text field default value based on props', () => {
const wrapper = getActualDialog({
task: 'a cool task',
});
expect(wrapper.find('TextField').prop('defaultValue')).toBe('a cool task');
});
it('should call onRequestClose in handling close request', (done) => {
const wrapper = getActualDialog({
onRequestClose() {
done();
},
});
wrapper.instance().handleRequestClose();
});
it('should call onRequestEdit in handling edit request', (done) => {
const wrapper = getActualDialog({
onRequestEdit() {
done();
},
});
wrapper.instance().handleRequestEdit();
});
|
JavaScript
| 0 |
@@ -1378,16 +1378,282 @@
uestEdit();%0A%7D);%0A
+%0Ait('should set FlatButton disabled based on state', () =%3E %7B%0A const wrapper = getActualDialog();%0A wrapper.find('TextField').props().onChange(%7B target: %7B value: 'a cool task' %7D %7D);%0A expect(wrapper.find('Dialog').prop('actions')%5B0%5D.props.disabled).toBe(false);%0A%7D);%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.