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
|
---|---|---|---|---|---|---|---|
84e4bbb8091c84660f304ee28e08263e821d9066
|
update CursorPopoverProvider
|
src/CursorPopoverProvider/CursorPopoverProvider.js
|
src/CursorPopoverProvider/CursorPopoverProvider.js
|
/**
* @file CursorPopoverProvider component
*/
import React, {Component, cloneElement, createRef} from 'react';
import PropTypes from 'prop-types';
// components
import CursorPopover from '../CursorPopover';
// statics
import Theme from '../Theme';
import Position from '../_statics/Position';
// vendors
import {findDOMNode} from 'react-dom';
import Util from '../_vendors/Util';
import ComponentUtil from '../_vendors/ComponentUtil';
class CursorPopoverProvider extends Component {
static Position = Position;
static Theme = Theme;
static getDerivedStateFromProps(props, state) {
return {
prevProps: props,
visible: ComponentUtil.getDerivedState(props, state, 'visible')
};
}
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.trigger = createRef();
this.triggerEl = null;
this.state = {
visible: props.visible
};
}
componentDidMount() {
this.triggerEl = findDOMNode(this.trigger?.current);
}
/**
* public
*/
show = () => {
if (this.state.visible) {
return;
}
this.setState({
visible: true
}, () => this.props.onRequestOpen?.());
};
/**
* public
*/
hide = () => {
if (!this.state.visible) {
return;
}
this.setState({
visible: false
}, () => this.props.onRequestClose?.());
};
/**
* public
*/
toggle = () => {
this.setState({
visible: !this.state.visible
}, () => {
if (!this.state.visible) {
this.props.onRequestClose?.();
} else {
this.props.onRequestOpen?.();
}
});
};
handleMouseEnter = e => {
this.props?.children?.props?.onMouseEnter?.(e);
this.show();
};
render() {
const {
children, popoverContent,
// not passing down these props
// eslint-disable-next-line no-unused-vars
onRequestOpen, onRequestClose,
...restProps
} = this.props;
const {visible} = this.state;
if (!popoverContent) {
return children;
}
return (
<>
{
cloneElement(children, {
ref: this.trigger,
onMouseEnter: this.handleMouseEnter
})
}
<CursorPopover {...restProps}
triggerEl={this.triggerEl}
visible={visible}
onRequestClose={this.hide}>
{popoverContent}
</CursorPopover>
</>
);
}
}
CursorPopoverProvider.propTypes = {
children: PropTypes.any,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The CSS class name of the content element.
*/
contentClassName: PropTypes.string,
modalClassName: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
parentEl: PropTypes.object,
/**
* This is the DOM element that will be used to set the position of the popover.
*/
triggerEl: PropTypes.object,
/**
* If true,the popover is visible.
*/
visible: PropTypes.bool,
/**
* The popover theme.Can be primary,highlight,success,warning,error.
*/
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The popover alignment.The value can be CursorPopover.Position.LEFT or CursorPopover.Position.RIGHT.
*/
position: PropTypes.oneOf(Util.enumerateValue(Position)),
/**
* If true, popover will have animation effects.
*/
isAnimated: PropTypes.bool,
enterable: PropTypes.bool,
/**
* The depth of Paper component.
*/
depth: PropTypes.number,
shouldFollowScroll: PropTypes.bool,
scrollEl: PropTypes.object,
resetPositionWait: PropTypes.number,
popoverContent: PropTypes.any,
/**
* The function of popover render.
*/
onRender: PropTypes.func,
/**
* The function of popover rendered.
*/
onRendered: PropTypes.func,
/**
* The function of popover destroy.
*/
onDestroy: PropTypes.func,
/**
* The function of popover destroyed.
*/
onDestroyed: PropTypes.func,
/**
* Callback function fired when the popover is requested to be opened.
*/
onRequestOpen: PropTypes.func,
/**
* Callback function fired when the popover is requested to be closed.
*/
onRequestClose: PropTypes.func,
/**
* Callback function fired when wrapper wheeled.
*/
onWheel: PropTypes.func,
onCursorMove: PropTypes.func,
onTargetChange: PropTypes.func
};
CursorPopoverProvider.defaultProps = {
parentEl: document.body,
visible: false,
theme: Theme.DEFAULT,
position: Position.BOTTOM_LEFT,
isAnimated: true,
enterable: false,
shouldFollowScroll: false,
resetPositionWait: 250
};
export default CursorPopoverProvider;
|
JavaScript
| 0 |
@@ -1835,19 +1835,18 @@
dleMouse
-Ent
+Ov
er = e =
@@ -1893,19 +1893,18 @@
.onMouse
-Ent
+Ov
er?.(e);
@@ -2478,19 +2478,18 @@
onMouse
-Ent
+Ov
er: this
@@ -2504,11 +2504,10 @@
ouse
-Ent
+Ov
er%0A
|
b4849c818fd319034b8911b5acee2d39c5bd1078
|
scale chart with group / raid size
|
src/Parser/Core/Modules/Features/RaidHealthTab/TabComponent/Graph.js
|
src/Parser/Core/Modules/Features/RaidHealthTab/TabComponent/Graph.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Chart from 'chart.js';
import { Line } from 'react-chartjs-2';
import fetchWcl from 'common/fetchWclApi';
import ManaStyles from 'Interface/Others/ManaStyles.js';
const formatDuration = (duration) => {
const seconds = Math.floor(duration % 60);
return `${Math.floor(duration / 60)}:${seconds < 10 ? `0${seconds}` : seconds}`;
};
const CLASS_CHART_LINE_COLORS = {
DeathKnight: 'rgba(196, 31, 59, 0.6)',
Druid: 'rgba(255, 125, 10, 0.6)',
Hunter: 'rgba(171, 212, 115, 0.6)',
Mage: 'rgba(105, 204, 240, 0.6)',
Monk: 'rgba(45, 155, 120, 0.6)',
Paladin: 'rgba(245, 140, 186, 0.6)',
Priest: 'rgba(255, 255, 255, 0.6)',
Rogue: 'rgba(255, 245, 105, 0.6)',
Shaman: 'rgba(36, 89, 255, 0.6)',
Warlock: 'rgba(148, 130, 201, 0.6)',
Warrior: 'rgba(199, 156, 110, 0.6)',
DemonHunter: 'rgba(163, 48, 201, 0.6)',
};
class Graph extends React.PureComponent {
static propTypes = {
reportCode: PropTypes.string.isRequired,
actorId: PropTypes.number.isRequired,
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
};
constructor() {
super();
this.state = {
data: null,
};
}
componentWillMount() {
this.load(this.props.reportCode, this.props.actorId, this.props.start, this.props.end);
}
componentWillReceiveProps(newProps) {
if (newProps.reportCode !== this.props.reportCode || newProps.actorId !== this.props.actorId || newProps.start !== this.props.start || newProps.end !== this.props.end) {
this.load(newProps.reportCode, newProps.actorId, newProps.start, newProps.end);
}
}
load(reportCode, actorId, start, end) {
return fetchWcl(`report/tables/resources/${reportCode}`, {
start,
end,
abilityid: 1000,
})
.then(json => {
console.log('Received player health', json);
this.setState({
data: json,
});
});
}
render() {
const data = this.state.data;
if (!data) {
return (
<div>
Loading...
</div>
);
}
const { start, end } = this.props;
const series = data.series;
const players = series.filter(item => !!CLASS_CHART_LINE_COLORS[item.type]);
const entities = [];
players.forEach(series => {
const newSeries = {
...series,
lastValue: 100, // fights start at full hp
data: {},
};
series.data.forEach((item) => {
const secIntoFight = Math.floor((item[0] - start) / 1000);
const health = item[1];
newSeries.data[secIntoFight] = Math.min(100, health);
});
entities.push(newSeries);
});
const deathsBySecond = {};
if (this.state.data.deaths) {
this.state.data.deaths.forEach((death) => {
const secIntoFight = Math.floor((death.timestamp - start) / 1000);
if (death.targetIsFriendly) {
deathsBySecond[secIntoFight] = true;
}
});
}
const fightDurationSec = Math.ceil((end - start) / 1000);
const labels = [];
for (let i = 0; i <= fightDurationSec; i += 1) {
labels.push(i);
entities.forEach((series) => {
series.data[i] = series.data[i] !== undefined ? series.data[i] : series.lastValue;
series.lastValue = series.data[i];
});
deathsBySecond[i] = deathsBySecond[i] !== undefined ? deathsBySecond[i] : undefined;
}
const chartData = {
labels,
datasets: [
...entities.map((series, index) => ({
label: series.name,
...ManaStyles['Boss-0'],
backgroundColor: CLASS_CHART_LINE_COLORS[series.type],
borderColor: CLASS_CHART_LINE_COLORS[series.type],
data: Object.keys(series.data).map(key => series.data[key]),
})),
{
label: `Deaths`,
...ManaStyles.Deaths,
data: Object.keys(deathsBySecond).map(key => deathsBySecond[key]),
},
],
};
const gridLines = ManaStyles.gridLines;
const options = {
responsive: true,
scales: {
yAxes: [{
gridLines: gridLines,
ticks: {
callback: (value, index, values) => {
return `${value}%`;
},
min: 0,
max: 20 * 100,
fontSize: 14,
},
stacked: true,
}],
xAxes: [{
gridLines: gridLines,
ticks: {
callback: (value, index, values) => {
if (value % 30 === 0) {
return formatDuration(value);
}
return null;
},
fontSize: 14,
},
}],
},
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
tooltips: {
enabled: false,
},
legend: ManaStyles.legend,
};
Chart.plugins.register({
id: 'specialEventIndiactor',
afterDatasetsDraw: (chart) => {
const ctx = chart.ctx;
chart.data.datasets.forEach(function (dataset, i) {
const meta = chart.getDatasetMeta(i);
if (dataset.label === 'Deaths' && !meta.hidden) {
meta.data.forEach(function (element, index) {
const position = element.tooltipPosition();
if (!isNaN(position.y)) {
ctx.strokeStyle = element._view.borderColor;
ctx.beginPath();
ctx.lineWidth = ManaStyles.Deaths.borderWidth;
ctx.moveTo(position.x, chart.chartArea.top);
ctx.lineTo(position.x, chart.chartArea.bottom);
ctx.stroke();
}
});
}
});
},
});
return (
<div className="graph-container">
<Line
data={chartData}
options={options}
width={1100}
height={400}
/>
</div>
);
}
}
export default Graph;
|
JavaScript
| 0 |
@@ -4287,18 +4287,30 @@
max:
-20
+players.length
* 100,%0A
|
7a02e16c5660683f2d6405fe106e68eaa599abed
|
Use enter and escape to stage changes to the cell name
|
ui/src/dashboards/components/VisualizationName.js
|
ui/src/dashboards/components/VisualizationName.js
|
import React, {Component, PropTypes} from 'react'
class VisualizationName extends Component {
constructor(props) {
super(props)
}
handleInputBlur = e => {
this.props.onCellRename(e.target.value)
}
render() {
const {defaultName} = this.props
return (
<div className="graph-heading">
<input
type="text"
className="form-control input-md"
defaultValue={defaultName}
onBlur={this.handleInputBlur}
placeholder="Name this Cell..."
/>
</div>
)
}
}
const {string, func} = PropTypes
VisualizationName.propTypes = {
defaultName: string.isRequired,
onCellRename: func,
}
export default VisualizationName
|
JavaScript
| 0 |
@@ -127,16 +127,62 @@
r(props)
+%0A%0A this.state = %7B%0A reset: false,%0A %7D
%0A %7D%0A%0A
@@ -198,16 +198,25 @@
utBlur =
+ reset =%3E
e =%3E %7B%0A
@@ -223,47 +223,403 @@
-this.props.onCellRename(e.target.value)
+console.log(reset, this.props.defaultName)%0A this.props.onCellRename(reset ? this.props.defaultName : e.target.value)%0A this.setState(%7Breset: false%7D)%0A %7D%0A%0A handleKeyDown = e =%3E %7B%0A if (e.key === 'Enter') %7B%0A this.inputRef.blur()%0A %7D%0A if (e.key === 'Escape') %7B%0A this.inputRef.value = this.props.defaultName%0A this.setState(%7Breset: true%7D, () =%3E this.inputRef.blur())%0A %7D
%0A %7D
@@ -669,16 +669,47 @@
is.props
+%0A const %7Breset%7D = this.state
%0A%0A re
@@ -909,16 +909,64 @@
nputBlur
+(reset)%7D%0A onKeyDown=%7Bthis.handleKeyDown
%7D%0A
@@ -1001,16 +1001,57 @@
ell...%22%0A
+ ref=%7Br =%3E (this.inputRef = r)%7D%0A
|
5e6791100e7f24ff2a31b4d1fc759ef80d12f9da
|
fix bad error handling in dev
|
api/policies/checkAndSetPost.js
|
api/policies/checkAndSetPost.js
|
module.exports = function checkAndSetPost (req, res, next) {
var postId = req.param('postId')
var fail = function (log, responseType) {
sails.log.debug(`policy: checkAndSetPost: ${log}`)
res[responseType || 'forbidden']()
}
return Post.find(postId, {withRelated: 'communities'})
.then(post => {
if (!post) return fail(`post ${postId} not found`, 'notFound')
res.locals.post = post
var ok = Admin.isSignedIn(req) ||
(res.locals.publicAccessAllowed && post.isPublic())
return (ok ? Promise.resolve(true)
: Post.isVisibleToUser(post.id, req.session.userId))
.then(allowed => {
if (allowed) {
next()
} else {
fail('not allowed')
}
return null
})
})
.catch(err => fail(err.message, 'serverError'))
}
|
JavaScript
| 0.000001 |
@@ -130,16 +130,21 @@
onseType
+, err
) %7B%0A
@@ -231,16 +231,19 @@
idden'%5D(
+err
)%0A %7D%0A%0A
@@ -794,13 +794,18 @@
erError'
+, err
))%0A%7D%0A
|
d71aad66b33fce1e90c0cbfb4497e3716a1205a6
|
Update CameraVideoPageController.js
|
scripts/CameraVideoPageController.js
|
scripts/CameraVideoPageController.js
|
/*
*
* Assignment 1 web app
*
* Copyright (c) 2016 Monash University
*
* Written by Michael Wybrow
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
function CameraVideoPageController(callback)
{
var self = this;
this.initialisationCallback = callback;
// Workaround a bug where the map canvas sometimes doesn't get
// the correct height: Delay setup of video for a tenth of a second.
setTimeout(initialiseCamera, 100);
self.setHeadsUpDisplayHTML = function(htmlString)
{
if (typeof(htmlString) == 'number')
{
// If argument is a number, convert to a string.
htmlString = htmlString.toString();
}
if (typeof(htmlString) != 'string')
{
console.log("setHeadsUpDisplayHTML: Argument is not a string.");
return;
}
if (htmlString.length == 0)
{
console.log("setHeadsUpDisplayHTML: Given an empty string.");
return;
}
document.getElementById("hud").innerHTML = htmlString;
}
self.displayMessage = function(message, timeout)
{
if (timeout === undefined)
{
// Timeout argument not specifed, use default.
timeout = 1000;
}
if (typeof(message) == 'number')
{
// If argument is a number, convert to a string.
message = message.toString();
}
if (typeof(message) != 'string')
{
console.log("displayMessage: Argument is not a string.");
return;
}
if (message.length == 0)
{
console.log("displayMessage: Given an empty string.");
return;
}
var snackbarContainer = document.getElementById('toast');
var data = {
message: message,
timeout: timeout
};
if (snackbarContainer && snackbarContainer.hasOwnProperty("MaterialSnackbar"))
{
snackbarContainer.MaterialSnackbar.showSnackbar(data);
}
};
function initialiseCamera()
{
var videoContainer = document.getElementById("video-container");
videoContainer.innerHTML = '<video autoplay class="bg-video"></video>' +
'<object class="crosshairs" type="image/svg+xml" data="crosshairs.svg"></object>';
// Support different browsers
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
if (typeof MediaStreamTrack !== 'undefined')
{
MediaStreamTrack.getSources(gotSources);
}
else
{
self.displayMessage("Camera not supported");
}
if (self.initialisationCallback)
{
self.initialisationCallback();
}
}
function successCallback(stream)
{
window.stream = stream; // make stream available to console
var videoElement = document.querySelector("video");
videoElement.src = window.URL.createObjectURL(stream);
videoElement.play();
}
function errorCallback(error)
{
self.displayMessage("Camera permission error");
console.log("navigator.getUserMedia error: ", error);
}
function sourceSelected(videoSource)
{
if (!!window.stream)
{
videoElement.src = null;
window.stream.stop();
}
var constraints = {
video: {
optional: [{sourceId: videoSource}]
},
audio: false
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
function gotSources(sourceInfos)
{
var videoSource = null;
for (var i = 0; i != sourceInfos.length; ++i)
{
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video')
{
videoSource = sourceInfo.id;
}
else
{
console.log('Some other kind of source: ', sourceInfo);
}
}
sourceSelected(videoSource);
}
}
|
JavaScript
| 0 |
@@ -3402,16 +3402,23 @@
%22 data=%22
+images/
crosshai
|
7cd84b6d032c21c1a3d96968908a4fe953014ace
|
Refactor hw2 Q16 & Q17 code
|
hw2/main.js
|
hw2/main.js
|
import generateData from './data-generator.js';
import train from './train.js';
let eInTotal = 0;
let eOutTotal = 0;
for (let i = 0; i < 5000; i++) {
let generatedData = generateData(20, true),
{ theta, s, eIn} = train(generatedData);
eInTotal += eIn;
eOutTotal += 0.5 + 0.3 * s * (Math.abs(theta) - 1);
}
console.log(`Ein: ${eInTotal / 5000}`);
console.log(`Eout: ${eOutTotal / 5000}`);
|
JavaScript
| 0 |
@@ -74,16 +74,66 @@
n.js';%0A%0A
+const CYCLE_COUNT = 5000;%0Aconst DATA_LENGTH = 20;%0A
let eInT
@@ -140,21 +140,21 @@
otal = 0
-;%0Alet
+,%0A
eOutTot
@@ -159,16 +159,35 @@
otal = 0
+,%0A generatedData
;%0A%0Afor (
@@ -201,20 +201,27 @@
0; i %3C
-5000
+CYCLE_COUNT
; i++) %7B
@@ -225,20 +225,16 @@
) %7B%0A
-let
generate
@@ -258,26 +258,29 @@
ata(
-20, true),
+DATA_LENGTH);
%0A
-
+let
%7B t
@@ -291,16 +291,17 @@
, s, eIn
+
%7D = trai
@@ -425,28 +425,35 @@
%7BeInTotal /
-5000
+CYCLE_COUNT
%7D%60);%0Aconsole
@@ -478,17 +478,24 @@
Total /
-5000
+CYCLE_COUNT
%7D%60);%0A
|
ae646fe1ac1bb1c9a4a0bdcaf0fa3e84bb18b6e3
|
fix minify issue when in jspm bundle no-mangel=false
|
src/libs/customelement.js
|
src/libs/customelement.js
|
let Register = {
/**
* Prefix of component if used
* e.g. com-foo
*/
prefix: 'com',
/**
* customElement
* @param Class {function}
* @param config {{extends: string, name: string}}
*/
customElement(Class, config = {}){
let name = config.name;
if(!name){
let className = this._getClassName(Class);
name = this._createComponentName(className, this.prefix);
} else {
delete config.name;
}
this._addExtends(Class, config);
this._registerElement(Class, name);
},
/**
* _classof
* @param value {*}
* @returns {string}
* @private
*/
_classof(value){
return Object.prototype.toString.call(value).slice(8, -1);
},
/**
* _addExtends
* @param Class {function}
* @param config {{extends: string, name: string}}
* @returns Class {function}
*/
_addExtends(Class, config = {}){
let inherit = config.extends;
if(inherit && !Class.extends){
Class.extends = inherit;
}
return Class;
},
/**
*
* @param Class {function}
* @returns className {string}
*/
_getClassName(Class){
return Class.prototype.constructor.name;
},
/**
*
* @param className {string}
* @param prefix {string}
* @returns componentName {string}
*/
_createComponentName(className, prefix = this.prefix){
return `${prefix}-${className.toLowerCase()}`;
},
/**
* _enableConstructorVars
* @param Class {function}
* @private
*/
_enableConstructorVars(Class){
let createdCallback = Class.prototype.createdCallback;
Class.prototype.createdCallback = function(...args){
if(!args.length && !this.parentElement){
return;
}
createdCallback ? this::createdCallback(...args) : null;
};
return Class;
},
/**
* registerElement
* @param Class {function}
* @param name {string}
* @returns Class {function}
*/
_registerElement(Class, name){
this._enableConstructorVars(Class);
// register element
let registeredElement = document.registerElement(name, Class);
/**
* create (add factory)
* @param vars {object}
*/
Class.create = function(vars) {
if(arguments.length > 1){
throw new Error('Its not allowd to pass more than one argument');
}
let classof = Register._classof(vars);
if(!(classof === 'Object' || classof === 'Undefined')) {
throw new Error('Passed argument must be an object or undefined');
}
let element = new registeredElement();
element.createdCallback(vars || "");
return element;
};
return Class;
}
};
export {
Register,
};
|
JavaScript
| 0.000272 |
@@ -1008,32 +1008,36 @@
assName %7Bstring%7D
+ls l
%0A%09 */%0A%09_getClass
@@ -1069,31 +1069,20 @@
ass.
-prototype.constructor.n
+$$componentN
ame;
|
34a696a480e29b281022b43eadee586d52ebaaf4
|
Fix tests for services generator
|
test/unit/services.test.js
|
test/unit/services.test.js
|
import path from 'path';
import os from 'os';
import { assert, test } from 'yeoman-generator';
describe('sails-rest-api:services', function () {
describe('Should properly handle default configuration', () => {
this.timeout(10000);
before(done => {
test
.run(path.join(__dirname, '../../generators/services'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.on('end', done);
});
it('Should properly create api files', () => {
assert.file([
'api/services/CipherService.js',
'api/services/HashService.js'
]);
assert.noFile([
'api/services/ImageService.js',
'api/services/LocationService.js',
'api/services/MailerService.js',
'api/services/PaymentService.js',
'api/services/PusherService.js',
'api/services/SmsService.js',
'api/services/SocialService.js',
'api/services/StorageService.js'
]);
});
it('Should properly create config files', () => {
assert.file([
'config/services/cipher.js',
'config/services/hash.js'
]);
assert.noFile([
'config/services/image.js',
'config/services/location.js',
'config/services/mailer.js',
'config/services/payment.js',
'config/services/pusher.js',
'config/services/sms.js',
'config/services/social.js',
'config/services/storage.js'
])
});
it('Should properly create test files', () => {
assert.file([
'test/unit/services/CipherService.test.js',
'test/unit/services/HashService.test.js'
]);
assert.noFile([
'test/unit/services/ImageService.test.js',
'test/unit/services/LocationService.test.js',
'test/unit/services/MailerService.test.js',
'test/unit/services/PaymentService.test.js',
'test/unit/services/PusherService.test.js',
'test/unit/services/SmsService.test.js',
'test/unit/services/SocialService.test.js',
'test/unit/services/StorageService.test.js'
]);
});
});
describe('Should properly handle full configuration', () => {
this.timeout(10000);
before(done => {
test
.run(path.join(__dirname, '../../generators/services'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({
'services': ['Cipher', 'Hash', 'Image', 'LocationService', 'Mailer', 'PaymentService', 'Pusher', 'Sms', 'Social', 'Storage'].join(','),
'image-provider': 'IM',
'location-provider': 'FreeGeoIP',
'mailer-provider': 'SMTP',
'payment-provider': 'BrainTree',
'sms-provider': 'Twilio',
'storage-provider': 'Local'
})
.on('end', done);
});
it('Should properly create api files', () => {
assert.file([
'api/services/CipherService.js',
'api/services/HashService.js',
'api/services/ImageService.js',
'api/services/LocationService.js',
'api/services/MailerService.js',
'api/services/PaymentService.js',
'api/services/PusherService.js',
'api/services/SmsService.js',
'api/services/SocialService.js',
'api/services/StorageService.js'
]);
assert.fileContent('api/services/ImageService.js', /image\.create\("IM"/);
assert.fileContent('api/services/LocationService.js', /location\.create\("FreeGeoIP"/);
assert.fileContent('api/services/MailerService.js', /mailer\.create\("SMTP"/);
assert.fileContent('api/services/PaymentService.js', /payment\.create\("BrainTree"/);
assert.fileContent('api/services/SmsService.js', /sms\.create\("Twilio"/);
assert.fileContent('api/services/StorageService.js', /storage\.create\("Local"/);
});
it('Should properly create config files', () => {
assert.file([
'config/services/cipher.js',
'config/services/hash.js',
'config/services/image.js',
'config/services/location.js',
'config/services/mailer.js',
'config/services/payment.js',
'config/services/pusher.js',
'config/services/sms.js',
'config/services/social.js',
'config/services/storage.js'
]);
});
it('Should properly create test files', () => {
assert.file([
'test/unit/services/CipherService.test.js',
'test/unit/services/HashService.test.js',
'test/unit/services/ImageService.test.js',
'test/unit/services/LocationService.test.js',
'test/unit/services/MailerService.test.js',
'test/unit/services/PaymentService.test.js',
'test/unit/services/PusherService.test.js',
'test/unit/services/SmsService.test.js',
'test/unit/services/SocialService.test.js',
'test/unit/services/StorageService.test.js'
]);
});
});
});
|
JavaScript
| 0 |
@@ -301,34 +301,27 @@
ame, '../../
-generators
+src
/services'))
@@ -1420,16 +1420,104 @@
%5D)
+;%0A%0A assert.fileContent('config/services/cipher.js', /secretOrKey: %22%5Ba-z0-9%5D%7B64%7D%22/);
%0A %7D);
@@ -2331,18 +2331,11 @@
/../
-generators
+src
/ser
@@ -2566,16 +2566,61 @@
n(','),%0A
+ 'cipher-secret-key': '1234567890',%0A
@@ -3442,24 +3442,16 @@
/image%5C
-.create%5C
(%22IM%22/);
@@ -3521,24 +3521,16 @@
ocation%5C
-.create%5C
(%22FreeGe
@@ -3603,24 +3603,16 @@
/mailer%5C
-.create%5C
(%22SMTP%22/
@@ -3682,24 +3682,16 @@
payment%5C
-.create%5C
(%22BrainT
@@ -3758,24 +3758,16 @@
', /sms%5C
-.create%5C
(%22Twilio
@@ -3843,16 +3843,8 @@
age%5C
-.create%5C
(%22Lo
@@ -4293,32 +4293,32 @@
ces/storage.js'%0A
-
%5D);%0A %7D)
@@ -4302,32 +4302,117 @@
ge.js'%0A %5D);
+%0A%0A assert.fileContent('config/services/cipher.js', /secretOrKey: %221234567890%22/);
%0A %7D);%0A%0A it
|
d9ce89d0fe9c5daa0c5d8be3d5ddb79784eb764d
|
remove 640x480 restriction
|
apps/pipeland/src/classes/vertices/DelayVertex.js
|
apps/pipeland/src/classes/vertices/DelayVertex.js
|
import BaseVertex from "./BaseVertex";
import SK from "../../sk";
export default class DelayVertex extends BaseVertex {
constructor({id}) {
super({id});
this.videoOutputURL = this.getUDP();
this.audioOutputURL = this.getUDP();
this.inputURL = this.getUDP() + "reuse=1";
SK.vertices.update(id, {
inputs: {
default: {
socket: this.inputURL,
}
},
outputs: {
video: {
socket: this.videoOutputURL
},
audio: {
socket: this.audioOutputURL
}
},
}).catch((err) => {
this.error(err);
});
}
init() {
try {
this.ffmpeg = this.createffmpeg()
.input(this.inputURL)
.inputFormat("mpegts")
// .inputOptions("-itsoffset 00:00:05")
.outputOptions([
])
.videoCodec("libx264")
.audioCodec("pcm_s16le")
.outputOptions([
"-preset ultrafast",
"-tune zerolatency",
"-x264opts keyint=5:min-keyint=",
"-pix_fmt yuv420p",
"-filter_complex",
[
`[0:a]asetpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_audio]`,
`[0:v]setpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[resize]`,
"[resize]scale=640:480[out_video]",
].join(";")
])
// Video output
.output(this.videoOutputURL)
.outputOptions([
"-map [out_video]",
])
.outputFormat("mpegts")
// Audio output
.output(this.audioOutputURL)
.outputOptions([
"-map [out_audio]",
])
.outputFormat("mpegts");
this.ffmpeg.run();
}
catch (err) {
this.error(err);
this.retry();
}
}
}
|
JavaScript
| 0.000017 |
@@ -1270,53 +1270,8 @@
0)'%5B
-resize%5D%60,%0A %22%5Bresize%5Dscale=640:480%5B
out_
@@ -1268,33 +1268,33 @@
000)'%5Bout_video%5D
-%22
+%60
,%0A %5D.jo
|
e62a7de612c527620b6963757f8bcbcfa46d004a
|
Remove beta suffix from mobile-experience package version.
|
packages/mobile-experience/package.js
|
packages/mobile-experience/package.js
|
Package.describe({
name: 'mobile-experience',
version: '1.0.5-beta.31',
summary: 'Packages for a great mobile user experience',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.imply([
// A nicer appearance for the status bar in PhoneGap/Cordova apps
"mobile-status-bar"
], "web.cordova");
api.imply([
// Show a nice splash image while your PhoneGap/Cordova app's UI is loading.
// Doesn't do anything without Cordova, but we include it everywhere so you
// don't need a ton of if statements around your LaunchScreen calls.
"launch-screen"
]);
});
|
JavaScript
| 0 |
@@ -62,16 +62,8 @@
.0.5
--beta.31
',%0A
|
3af2ab9022fb09fb5b355f494e3def4dec00b265
|
Handle when github api returns a null author, and other missing info
|
public/commits-widget/javascripts/commits-widget.js
|
public/commits-widget/javascripts/commits-widget.js
|
/*
* Parameters:
* limit: (integer) How many commits to render, starting with the most recent commit
* width: (integer) Width of the widget
* height: (integer) Height of the widget
* heading: (string) Text in the header of the widget
*/
$(function(){
var $commitsList = $('.commits-list');
var keyValuePairs = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&");
var x, params = {};
$.each(keyValuePairs, function(i, keyValue){
x = keyValue.split('=');
params[x[0]] = x[1];
});
if( params.width ) {
$('.widget-container').css('width', params.width + 'px');
}
if( params.height ) {
$('.widget-container').css('height', params.height + 'px');
$('.widget-container .commits-list').css('height', (params.height - 31) + 'px');
}
if( params.heading ) {
$('.widget-container h1').text( decodeURIComponent(params.heading) );
}
$('.widget-container .header').click(function(){
window.open('https://github.com/discourse/discourse');
});
$.ajax( "https://api.github.com/repos/discourse/discourse/commits?callback=callback", {
dataType: 'jsonp',
type: 'get',
data: {
per_page: params.limit || 10
},
success: function(response, textStatus, jqXHR) {
var data = response.data;
$.each(data, function(i, commit){
var $li = $('<li></li>').appendTo( $commitsList );
$('<div class="left"><img src="https://www.gravatar.com/avatar/' + commit.author.gravatar_id + '.png?s=38&r=pg&d=identicon"></div>').appendTo( $li );
$right = $('<div class="right"></div>').appendTo( $li );
$('<span class="commit-message"><a href="https://github.com/discourse/discourse/commit/' + commit.sha + '" target="_blank">' + commit.commit.message + '</a></span><br/>').appendTo( $right );
$('<span class="commit-meta">by <span class="committer-name">' + commit.committer.login + '</span> - <span class="commit-time">' + $.timeago(commit.commit.committer.date) + '</span></span>').appendTo( $right );
$('<div class="clearfix"></div>').appendTo( $li );
});
}
});
});
|
JavaScript
| 0 |
@@ -1419,158 +1419,569 @@
-$('%3Cdiv class=%22left%22%3E%3Cimg src=%22https://www.gravatar.com/avatar/' + commit.author.gravatar_id + '.png?s=38&r=pg&d=identicon%22%3E%3C/div%3E').appendTo( $li );%0A
+if( commit.sha && commit.commit && commit.commit.message && commit.commit.author && commit.commit.committer && commit.commit.committer.date ) %7B%0A if( commit.author && commit.author.gravatar_id ) %7B%0A $('%3Cdiv class=%22left%22%3E%3Cimg src=%22https://www.gravatar.com/avatar/' + commit.author.gravatar_id + '.png?s=38&r=pg&d=identicon%22%3E%3C/div%3E').appendTo( $li );%0A %7D else %7B%0A $('%3Cdiv class=%22left%22%3E%3Cimg src=%22https://www.gravatar.com/avatar/b30fff48d257cdd17c4437afac19fd30.png?s=38&r=pg&d=identicon%22%3E%3C/div%3E').appendTo( $li );%0A %7D%0A
@@ -2033,32 +2033,34 @@
ppendTo( $li );%0A
+
$('%3Cspan
@@ -2242,32 +2242,34 @@
ight );%0A
+
$('%3Cspan class=%22
@@ -2334,17 +2334,20 @@
mmit
-ter.login
+.author.name
+ '
@@ -2466,32 +2466,34 @@
ight );%0A
+
$('%3Cdiv class=%22c
@@ -2523,24 +2523,404 @@
dTo( $li );%0A
+ %7D else %7B%0A // Render nothing. Or render a message:%0A // $('%3Cdiv class=%22left%22%3E %3C/div%3E').appendTo( $li );%0A // $right = $('%3Cdiv class=%22right%22%3E%3C/div%3E').appendTo( $li );%0A // $('%3Cspan class=%22commit-meta%22%3Ethis commit cannot be rendered%3C/span%3E').appendTo( $right );%0A // $('%3Cdiv class=%22clearfix%22%3E%3C/div%3E').appendTo( $li );%0A %7D%0A
%7D);%0A
|
dd53f5a1309c96b5b8bde8899a8cdf1c8227e308
|
check for outdated release
|
assets/common.js
|
assets/common.js
|
var release = null;
function setRelease(release_) {
if (release_ == null) {
var node = $('#release-switch').find('.release-button').last();
release = node.id;
}
else
release = release_;
$.cookie('default-release', release, {expires: 365});
$('.release_name').html(release);
$('a[class*="release-button"]').on('click', function(evt) {
setRelease(this.id.split("-").pop());
window.location.reload(true);
});
}
function checkSessionCookie() {
return ($.cookie('sid') != null);
}
|
JavaScript
| 0 |
@@ -61,17 +61,17 @@
elease_
-=
+!
= null)
@@ -80,129 +80,450 @@
-var node = $('#release-switch').find('.release-button').last();%0A release = node.id;%0A %7D%0A else%0A release = release_;
+// check if release is still present in the list%0A var found = false;%0A $('#release-switch').find('.release-button').each(function() %7B%0A if (release_ == this.id.split(%22-%22).pop()) %7B%0A%09found = true;%0A %7D%0A %7D);%0A if (found)%0A release = release_;%0A else%0A release = null;%0A %7D%0A %0A if (release == null) %7B%0A var node = $('#release-switch').find('.release-button').last()%5B0%5D;%0A release = node.id.split(%22-%22).pop();%0A %7D%0A
%0A $
@@ -611,17 +611,16 @@
lease);%0A
-%0A
$('a%5Bc
|
3ad32e887216a414ecb08065493efc1eede56bc4
|
return on error
|
api/routes/data/members-list.js
|
api/routes/data/members-list.js
|
const request = require('request')
const series = require('run-series')
// does a small read to see if the members response has already been cached in
// leveldb. Used to determine if a request to the proPublica api is needed.
function checkCache(params, ctx, done) {
const session = ctx.localConfig.congressSession
const chamber = params.chamber
const delimiter = `members~${session}~${chamber}~`
const members = []
ctx.db.createReadStream({
gt: delimiter + '!',
lt: delimiter + '~',
limit: 3
})
.on('data', function (data) {
members.push(data.value)
})
.on('error', done)
.on('end', function () {
const hit = members.length === 3
if (hit) {
ctx.log.info('MEMBERS_CACHE_HIT')
} else {
ctx.log.info('MEMBERS_CACHE_MISS')
}
done(null, hit)
})
}
// after a request to the proPublica api for congressional members, cache the
// response in leveldb so another proPublica api request for
// this chamber/session isn't needed
function cacheMembers(ctx, members) {
const session = ctx.localConfig.congressSession
const chamber = ctx.params.chamber
const delimiter = `members~${session}~${chamber}~`
const ops = members.map(function (member) {
const op = {
type: 'put',
key: delimiter + member.id,
value: member
}
return op
})
ctx.log.debug('CATCHEING_MEMBERS')
ctx.db.batch(ops, function (err) {
if (err) {
return ctx.log.error(err, 'CACHE_MEMBERS_BATCH_ERROR')
}
return ctx.log.info('CACHE_MEMBERS_BATCH_SUCCESS')
})
}
// retrieve members froom leveldb
function getMembersCache(params, ctx, done) {
const session = ctx.localConfig.congressSession
const chamber = params.chamber
const delimiter = `members~${session}~${chamber}~`
const members = []
ctx.db.createReadStream({
gt: delimiter + '!',
lt: delimiter + '~'
})
.on('data', function (data) {
members.push(data.value)
})
.on('error', done)
.on('end', function () {
done(null, {members: members})
})
}
// retrieve members from proPublica api. This request will trigger
// a cache (cacheMembers) upon completion
function getMembersRequest(params, ctx, done) {
const session = ctx.localConfig.congressSession
const chamber = params.chamber
const payload = {
url: `https://api.propublica.org/congress/v1/${session}/${chamber}/members.json`,
headers: {
'X-API-Key': ctx.localConfig.proPublicaApiKey,
'Content-Type': 'application/json'
}
}
request(payload, function (err, resp, body) {
if (err) {
return done(err)
}
try {
cacheMembers(ctx, JSON.parse(body).results[0].members)
} catch (err) {
ctx.log.error('CACHE_ERROR', err)
}
try {
const results = JSON.parse(body).results[0]
return done(err, {members: results.members})
} catch (err) {
return done(err)
}
})
}
function membersList(params, ctx, done) {
let cacheHit = false
let result = {members: []}
series([
function (next) {
checkCache(params, ctx, function (err, _cacheHit) {
cacheHit = _cacheHit
next(err)
})
},
function (next) {
if (cacheHit) {
return getMembersCache(params, ctx, function (err, _result) {
result = _result
next(err)
})
}
return getMembersRequest(params, ctx, function (err, _result) {
result = _result
next(err)
})
}
], function (err) {
if (err) {
ctx.log.error(err, 'MEMBERS_REQUEST_ERROR')
}
done(err, result)
})
}
module.exports = membersList
|
JavaScript
| 0.000033 |
@@ -2606,24 +2606,44 @@
RROR', err)%0A
+%09%09%09return done(err)%0A
%09%09%7D%0A%09%09try %7B%0A
|
eae0393c5a1c5d2340d3f72044cc142baea88a8f
|
add normal mode
|
scripts/com.r2studio.popcat/index.js
|
scripts/com.r2studio.popcat/index.js
|
var run = false;
var x = 0;
var y = 0;
function loop() {
console.log('Start Clicking...');
var count = 0;
while (run) {
for (var i = 0; i < 5; i++) {
tapDown(x + i * 50, y + i * 50, 1, i);
}
sleep(5);
for (var i = 0; i < 5; i++) {
tapUp(x + i * 50, y + i * 50, 1, i);
}
sleep(5);
count++;
if (count % 50 === 0) {
console.log('click', count, '* 5 times');
sleep(1000);
}
}
}
function start() {
var wh = getScreenSize();
x = Math.floor(wh.width / 3) || 200;
y = Math.floor(wh.height / 2) || 200;
run = true;
loop();
}
function stop() {
run = false;
}
|
JavaScript
| 0.000008 |
@@ -31,16 +31,35 @@
r y = 0;
+%0Avar normal = true;
%0A%0Afuncti
@@ -84,17 +84,17 @@
ole.log(
-'
+%22
Start Cl
@@ -102,17 +102,17 @@
cking...
-'
+%22
);%0A var
@@ -135,24 +135,111 @@
ile (run) %7B%0A
+ if (normal) %7B%0A tap(x, y, 20);%0A count++;%0A sleep(160);%0A %7D else %7B%0A
for (var
@@ -252,32 +252,34 @@
; i %3C 5; i++) %7B%0A
+
tapDown(x
@@ -299,32 +299,34 @@
i * 50, 1, i);%0A
+
%7D%0A sleep(
@@ -311,32 +311,34 @@
i);%0A %7D%0A
+
sleep(5);%0A fo
@@ -327,24 +327,26 @@
sleep(5);%0A
+
for (var
@@ -373,16 +373,18 @@
%7B%0A
+
+
tapUp(x
@@ -416,22 +416,26 @@
i);%0A
+
%7D%0A
+
+
sleep(5)
@@ -436,24 +436,26 @@
eep(5);%0A
+
count++;%0A
@@ -447,24 +447,30 @@
count++;%0A
+ %7D%0A
if (coun
@@ -507,15 +507,15 @@
log(
-'
+%22
click
-'
+%22
, co
@@ -519,17 +519,17 @@
count,
-'
+%22
* 5 time
@@ -533,9 +533,9 @@
imes
-'
+%22
);%0A
@@ -580,16 +580,17 @@
n start(
+n
) %7B%0A va
@@ -706,16 +706,30 @@
= true;%0A
+ normal = n;%0A
loop()
|
dabcf1db320f97e66c57459d30a32de650e5f5bc
|
update broadcast mediator list on mediator status change
|
src/foam/nanos/medusa/ClusterConfigStatusDAO.js
|
src/foam/nanos/medusa/ClusterConfigStatusDAO.js
|
/**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.medusa',
name: 'ClusterConfigStatusDAO',
extends: 'foam.dao.ProxyDAO',
documentation: `Monitor the ClusterConfig status and call election when quorum changes`,
javaImports: [
'foam.dao.ArraySink',
'foam.dao.DAO',
'static foam.mlang.MLang.*',
'foam.nanos.logger.PrefixLogger',
'foam.nanos.logger.Logger',
'java.util.ArrayList',
'java.util.List',
'java.util.HashMap',
'java.util.Map'
],
properties: [
{
name: 'logger',
class: 'FObjectProperty',
of: 'foam.nanos.logger.Logger',
visibility: 'HIDDEN',
transient: true,
javaFactory: `
return new PrefixLogger(new Object[] {
this.getClass().getSimpleName()
}, (Logger) getX().get("logger"));
`
},
],
methods: [
{
name: 'put_',
javaCode: `
ClusterConfig nu = (ClusterConfig) obj;
getLogger().debug("put", nu.getName());
ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
if ( support.getStandAlone() ) {
return getDelegate().put_(x, nu);
}
ClusterConfig old = (ClusterConfig) find_(x, nu.getId());
Boolean hadQuorum = support.hasQuorum(x);
nu = (ClusterConfig) getDelegate().put_(x, nu);
if ( old != null &&
old.getStatus() != nu.getStatus() ) {
getLogger().info(nu.getName(), old.getStatus().getLabel(), "->", nu.getStatus().getLabel().toUpperCase());
if ( nu.getId() == support.getConfigId() ) {
support.setStatus(nu.getStatus());
}
if ( nu.getType() == MedusaType.MEDIATOR ) {
ElectoralService electoralService = (ElectoralService) x.get("electoralService");
if ( electoralService != null ) {
ClusterConfig config = support.getConfig(x, support.getConfigId());
if ( support.canVote(x, nu) &&
support.canVote(x, config) ) {
Boolean hasQuorum = support.hasQuorum(x);
if ( electoralService.getState() == ElectoralServiceState.IN_SESSION ||
electoralService.getState() == ElectoralServiceState.ADJOURNED) {
if ( hadQuorum && ! hasQuorum) {
getLogger().warning(this.getClass().getSimpleName(), "mediator quorum lost");
} else if ( ! hadQuorum && hasQuorum) {
getLogger().warning(this.getClass().getSimpleName(), "mediator quorum acquired");
} else {
getLogger().info(this.getClass().getSimpleName(), "mediator quorum membership change");
}
electoralService.dissolve(x);
}
}
}
} else if ( nu.getType() == MedusaType.NODE ) {
bucketNodes(x);
broadcast2Mediators(x);
}
}
return nu;
`
},
{
documentation: 'Assign nodes to buckets.',
synchronized: true,
name: 'bucketNodes',
args: [
{
name: 'x',
type: 'Context'
}
],
javaCode: `
ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
ClusterConfig myConfig = support.getConfig(x, support.getConfigId());
int groups = support.getNodeGroups();
List nodes = ((ArraySink)((DAO) getX().get("localClusterConfigDAO"))
.where(
AND(
EQ(ClusterConfig.ENABLED, true),
EQ(ClusterConfig.STATUS, Status.ONLINE),
EQ(ClusterConfig.TYPE, MedusaType.NODE),
EQ(ClusterConfig.ACCESS_MODE, AccessMode.RW),
EQ(ClusterConfig.ZONE, 0L),
EQ(ClusterConfig.REGION, myConfig.getRegion()),
EQ(ClusterConfig.REALM, myConfig.getRealm())
))
.select(new ArraySink())).getArray();
Map<Integer, List> buckets = new HashMap();
for ( int i = 0; i < nodes.size(); i++ ) {
ClusterConfig node = (ClusterConfig) nodes.get(i);
int index = i % groups;
List bucket = (List) buckets.get(index);
if ( bucket == null ) {
bucket = new ArrayList<String>();
buckets.put(index, bucket);
}
bucket.add(node.getId());
}
support.setNodeBuckets(buckets);
support.outputBuckets(x);
`
},
{
documentation: 'Update list of mediators to broadcast to.',
synchronized: true,
name: 'broadcast2Mediators',
args: [
{
name: 'x',
type: 'Context'
}
],
javaCode: `
getLogger().debug("broadcast2Mediators");
ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
ClusterConfig myConfig = support.getConfig(x, support.getConfigId());
long zone = myConfig.getZone() + 1;
if ( myConfig.getType() == MedusaType.NODE ) {
zone = myConfig.getZone();
}
List<ClusterConfig> arr = (ArrayList) ((ArraySink) ((DAO) x.get("localClusterConfigDAO"))
.where(
AND(
EQ(ClusterConfig.ZONE, zone),
EQ(ClusterConfig.TYPE, MedusaType.MEDIATOR),
EQ(ClusterConfig.STATUS, Status.ONLINE),
EQ(ClusterConfig.ENABLED, true),
EQ(ClusterConfig.REGION, myConfig.getRegion()),
EQ(ClusterConfig.REALM, myConfig.getRealm())
)
)
.select(new ArraySink())).getArray();
ClusterConfig[] configs = new ClusterConfig[arr.size()];
arr.toArray(configs);
support.setBroadcastMediators(configs);
`
}
]
});
|
JavaScript
| 0 |
@@ -1774,24 +1774,57 @@
EDIATOR ) %7B%0A
+ broadcastMediators(x);%0A
El
@@ -2969,42 +2969,8 @@
x);%0A
- broadcast2Mediators(x);%0A
@@ -4577,33 +4577,32 @@
name: 'broadcast
-2
Mediators',%0A
@@ -4739,17 +4739,16 @@
roadcast
-2
Mediator
|
de899463afcc64195f931ecc253257d5a42eaa15
|
Remove unreachable case when both trees do not have the same property
|
astraverse.js
|
astraverse.js
|
'use strict';
var patchSource = require('./source_replacer').patchSource;
function isLiteral(element) {
return Object(element) !== element;
}
function performOnParallellTraverse(action) {
var parallelTraverse = function parallellTraverse(actual, expected, actualLastFunctionScope, expectedLastFunctionScope) {
var attr;
if (isLiteral(actual)) {
if (actual !== expected) {
action(actualLastFunctionScope, expectedLastFunctionScope);
}
return;
}
if (actual.type === "BlockStatement") {
actualLastFunctionScope = actual;
expectedLastFunctionScope = expected;
}
if (Array.isArray(actual)) {
if (actual.length !== expected.length) {
action(actualLastFunctionScope, expectedLastFunctionScope);
} else {
actual.forEach(function (_, i) {
parallellTraverse(actual[i], expected[i], actualLastFunctionScope, expectedLastFunctionScope);
});
return;
}
}
for (attr in actual) {
if (attr !== 'type' && attr !== 'loc' && attr !== 'raw' && actual.hasOwnProperty(attr) && expected.hasOwnProperty(attr)) {
if (expected && attr in expected) {
parallellTraverse(actual[attr], expected[attr], actualLastFunctionScope, expectedLastFunctionScope);
} else {
action(actualLastFunctionScope, expectedLastFunctionScope);
}
}
}
};
return parallelTraverse;
}
function equalizeTrees(patchedTree, sourceCode, createAst) {
var treesAreDifferent = true,
originalTree = createAst(sourceCode);
function replaceOriginalSourceWithPatch(a, b) {
var sourceToBePatched = b.loc.source,
sourceCode = patchSource(a.loc, b.loc, sourceToBePatched),
patchedAST = createAst(sourceCode);
throw patchedAST;
}
while (treesAreDifferent) {
try {
performOnParallellTraverse(replaceOriginalSourceWithPatch)(patchedTree, originalTree, patchedTree, originalTree);
treesAreDifferent = false;
} catch (replacedTree) {
originalTree = replacedTree;
}
}
return originalTree.loc.source;
}
module.exports = {
equalizeTrees: equalizeTrees
};
|
JavaScript
| 0.000006 |
@@ -333,16 +333,204 @@
attr;%0A%0A
+ function shouldBeChecked(attr) %7B%0A return attr !== 'type' && attr !== 'loc' && attr !== 'raw' && actual.hasOwnProperty(attr) && expected.hasOwnProperty(attr);%0A %7D%0A%0A
@@ -1340,117 +1340,23 @@
if (
-attr !== 'type' && attr !== 'loc' && attr !== 'raw' && actual.hasOwnProperty(attr) && expect
+shouldBeCheck
ed
-.hasOwnProperty
(att
@@ -1538,113 +1538,8 @@
e);%0A
- %7D else %7B%0A action(actualLastFunctionScope, expectedLastFunctionScope);%0A
|
8361ff9b8136b010b2cea45f21c49f558f90e63d
|
update copyright dates from daily grunt work
|
js/layout/constraints/ManualConstraintTests.js
|
js/layout/constraints/ManualConstraintTests.js
|
// Copyright 2021, University of Colorado Boulder
/**
* ManualConstraint tests
*
* @author Jonathan Olson <[email protected]>
*/
import Node from '../../nodes/Node.js';
import Rectangle from '../../nodes/Rectangle.js';
import ManualConstraint from './ManualConstraint.js';
QUnit.module( 'ManualConstraint' );
QUnit.test( 'Identity', assert => {
const a = new Rectangle( 0, 0, 100, 50, { fill: 'red' } );
const b = new Rectangle( 0, 0, 100, 50, { fill: 'blue' } );
const aContainer = new Node( { children: [ a ] } );
const bContainer = new Node( { children: [ b ] } );
const root = new Node( { children: [ aContainer, bContainer ] } );
ManualConstraint.create( root, [ a, b ], ( aProxy, bProxy ) => {
bProxy.left = aProxy.right;
} );
root.validateBounds();
assert.equal( b.x, 100, 'x' );
a.x = 100;
root.validateBounds();
assert.equal( b.x, 200, 'x after 100' );
} );
QUnit.test( 'Translation', assert => {
const a = new Rectangle( 0, 0, 100, 50, { fill: 'red' } );
const b = new Rectangle( 0, 0, 100, 50, { fill: 'blue' } );
const aContainer = new Node( { children: [ a ] } );
const bContainer = new Node( { children: [ b ], x: 50 } );
const root = new Node( { children: [ aContainer, bContainer ] } );
ManualConstraint.create( root, [ a, b ], ( aProxy, bProxy ) => {
bProxy.left = aProxy.right;
} );
root.validateBounds();
assert.equal( b.x, 50, 'x' );
a.x = 100;
root.validateBounds();
assert.equal( b.x, 150, 'x after 100' );
} );
QUnit.test( 'Scale', assert => {
const a = new Rectangle( 0, 0, 100, 50, { fill: 'red' } );
const b = new Rectangle( 0, 0, 100, 50, { fill: 'blue' } );
const aContainer = new Node( { children: [ a ], scale: 2 } );
const bContainer = new Node( { children: [ b ] } );
const root = new Node( { children: [ aContainer, bContainer ] } );
ManualConstraint.create( root, [ a, b ], ( aProxy, bProxy ) => {
bProxy.left = aProxy.right;
} );
root.validateBounds();
assert.equal( b.x, 200, 'x' );
a.x = 100;
root.validateBounds();
assert.equal( b.x, 400, 'x after 100' );
} );
|
JavaScript
| 0 |
@@ -10,16 +10,21 @@
ght 2021
+-2022
, Univer
|
2eb0c963c594904bb78f9ed0be89b94bae4a00d4
|
debug f
|
api/src/commands/_debug-feed.js
|
api/src/commands/_debug-feed.js
|
import program from 'commander';
import '../loadenv';
import '../utils/db';
import { ParseFeed, ParsePodcast } from '../parsers/feed';
import chalk from 'chalk';
import logger from '../utils/logger';
import Podcast from '../models/podcast';
import RSS from '../models/rss';
import config from '../config';
import normalize from 'normalize-url';
import async_tasks from '../async_tasks';
// do stuff
export async function debugFeed(feedType, feedUrls) {
// This is a small helper tool to quickly help debug issues with podcasts or RSS feeds
logger.info(`Starting the ${feedType} Debugger \\0/`);
logger.info(
'Please report issues with RSS feeds here https://github.com/getstream/winds',
);
logger.info('Note that pull requests are much appreciated!');
logger.info(`Handling ${feedUrls.length} urls`);
for (let target of feedUrls) {
target = normalize(target);
logger.info(`Looking up the first ${program.limit} articles from ${target}`);
function validate(response) {
// validate the podcast or RSS feed
logger.info('========== Validating Publication ==========');
logger.info(`Title: ${response.title}`);
logger.info(`Link: ${response.link}`);
if (response.image && response.image.og) {
logger.info(chalk.green('Image found :)'));
logger.info(`Image: ${response.image.og}`);
} else {
logger.info(chalk.red('Image missing :('));
}
logger.info('========== Validating episodes/articles now ==========');
// validate the articles or episodes
let articles = response.articles ? response.articles : response.episodes;
let selectedArticles = articles.slice(0, program.limit);
logger.info(`Found ${articles.length} articles showing ${program.limit}`);
if (selectedArticles.length) {
for (let article of selectedArticles) {
logger.info('======================================');
logger.info(chalk.green(`Title: ${article.title}`));
logger.info(`URL: ${article.url}`);
logger.info(`Description: ${article.description}`);
logger.info(`Publication Date: ${article.publicationDate}`);
if (article.commentUrl) {
logger.info(`Comments: ${article.commentUrl}`);
}
if (article.content) {
logger.info(`Content: ${article.content}`);
}
// for RSS we rely on OG scraping, for podcasts the images are already in the feed
if (article.images && article.images.og) {
logger.info(chalk.green('Image found :)'));
logger.info(`Image: ${article.images.og}`);
} else {
logger.info(chalk.red('Image missing :('));
}
if (feedType === 'podcast') {
if (article.enclosure) {
logger.info(chalk.green('Enclosure found :)'));
logger.info(article.enclosure);
} else {
logger.info(chalk.red('Missing enclosure :('));
}
}
}
} else {
logger.info(chalk.red('Didn\'t find any articles or episodes.'));
}
let schema = feedType === 'rss' ? RSS : Podcast;
let lookup = { feedUrl: target };
if (program.task) {
logger.info('trying to create a task on the bull queue');
schema
.findOne(lookup)
.catch(err => {
console.log('failed', err);
})
.then(instance => {
let queuePromise;
if (!instance) {
logger.info('failed to find publication');
return;
}
if (feedType == 'rss') {
queuePromise = async_tasks.RssQueueAdd(
{
rss: instance._id,
url: instance.feedUrl,
},
{
priority: 1,
removeOnComplete: true,
removeOnFail: true,
},
);
} else {
queuePromise = async_tasks.PodcastQueueAdd(
{
podcast: instance._id,
url: instance.feedUrl,
},
{
priority: 1,
removeOnComplete: true,
removeOnFail: true,
},
);
}
queuePromise
.then(() => {
if (feedType === 'rss') {
logger.info(
`Scheduled RSS feed to the queue for parsing ${target} with id ${
instance._id
}`,
);
} else {
logger.info(
`Scheduled Podcast to the queue for parsing ${target}`,
);
}
})
.catch(err => {
logger.error('Failed to schedule task on og queue');
});
});
}
}
if (feedType === 'rss') {
let feedContent = await ParseFeed(target);
validate(feedContent)
} else {
let podcastContent = await ParsePodcast(target);
validate(podcastContent)
}
logger.info('Note that upgrading feedparser can sometimes improve parsing.');
}
}
|
JavaScript
| 0.000006 |
@@ -949,16 +949,22 @@
%7D%60);%0A%0A%09%09
+async
function
@@ -2987,16 +2987,49 @@
rget %7D;%0A
+%09%09%09console.log(feedType, lookup)%0A
%09%09%09if (p
@@ -3101,24 +3101,99 @@
ll queue');%0A
+%09%09%09%09let instance = await schema.findOne(lookup)%0A%09%09%09%09console.log(instance)%0A%0A
%09%09%09%09schema%0A%09
|
de51aad8963977ef6704c7b19ec0637adf4edd6f
|
Update events-counter.js
|
scripts/components/events-counter.js
|
scripts/components/events-counter.js
|
(function ($) {
var apiKey = apiKeyService.getApiExploreKey();
var initialValObj;
function initialVal(config) {
var values = {};
config.forEach(function (el) {
values[el] = $('#js-'+el+'-counter').text();
});
initialValObj = values;
}
$(function() {
initEventCountersPanel(); // Counter panel init
});
/**
* Initialization of counter panel
*/
function initEventCountersPanel() {
var intervals = [],
config = ['events', 'venues', 'attractions', 'countries'],
timeLeap = 60000;
initialVal(config);
config.forEach(function (el) {
var val = el === 'countries' && 7,
quantityStorage = getSessionStorage(el);
renderValue(el, val);
if(val !== null || val !== false) {
if(!quantityStorage) {
updateEventpanelCounters(el,intervals);
}else{
countAnimate(el, quantityStorage);
}
//intervals.push(setInterval(updateEventpanelCounters.bind(null, el), timeLeap));
}
});
//clear requests when user leave current page
$(window).on('unload', function(){
for(var i = 1; i < intervals.length; i++) {
clearTimeout(i);
}
});
}
/**
* Get date for Counter Panel
* @param url {string}
*/
function updateEventpanelCounters(url) {
if (url !== 'countries') {
$.ajax({
method: 'GET',
url: ['https://app.ticketmaster.com/discovery/v2/', url, '.json?apikey=', apiKey].join(''),
async: true,
dataType: "json"
}).then(function (data) {
var quantity = data.page && data.page.totalElements || 'none';
setSessionStorage(url, quantity);
renderValue(url, quantity);
countAnimate(url, quantity);
}).fail(function (err) {
onFailHandler(url, 0.15);
console.error('Error: ', err);
})
}
}
/**
* Handler for invalid apiKey
* @param selector {string} - 'events', 'venues', 'attractions'
* @param minutes {number} - time to resend request if storage empty
*/
function onFailHandler(selector, minutes) {
var delay = minutes * 60000;
if(getSessionStorage(selector)) {
renderValue(selector, getSessionStorage(selector));
countAnimate(selector, getSessionStorage(selector));
}else{
setTimeout(function() {
updateEventpanelCounters(selector);
},delay);
}
}
function setSessionStorage(key, val) {
if (Storage) {
localStorage.setItem(key, val);
}
}
function getSessionStorage(key) {
if (localStorage[key]) {
return localStorage.getItem(key);
}
return null;
}
function addCommas(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
function renderValue(el, val) {
var value = getSessionStorage(el) || val || initialValObj[el] || '';
var formattedNumber = addCommas(value);
$(['#js-', el,'-counter'].join('')).text(formattedNumber);
}
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
parseInt(str,10);
return str;
}
function countAnimate(selectorEl,val) {
$('#js-'+selectorEl+'-counter').prop('Counter', initialValObj[selectorEl] ).animate({
Counter: val
}, {
duration: 3000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now).toLocaleString());
}
});
//RemoveCommas from recived values to parse as integer
//Update values after animation is finished (animation duration: 3000)
setTimeout(function () {
initialValObj[selectorEl] = removeCommas ( $('#js-'+selectorEl+'-counter').text() );
}, 3100
);
}
}(jQuery));
|
JavaScript
| 0.000001 |
@@ -647,9 +647,10 @@
&&
-7
+83
,%0A
@@ -720,24 +720,28 @@
e(el, val);%0A
+%09%09%09%0A
if(val
@@ -1645,16 +1645,82 @@
%7C 'none'
+, quantityObj = %7Bvalue: quantity, timestamp: new Date().getTime()%7D
;%0A
@@ -1740,32 +1740,47 @@
torage(url,
+JSON.stringify(
quantity
);%0A r
@@ -1759,32 +1759,36 @@
ringify(quantity
+Obj)
);%0A rende
@@ -2681,69 +2681,452 @@
-return localStorage.getItem(key);%0A %7D%0A return null;%0A %7D%0A
+var object = JSON.parse(localStorage.getItem(key)),%0A %09%09 dateString = object.timestamp,%0A now = new Date().getTime().toString(),%0A %09%09%09 shiftMinutes = 1,%0A %09%09%09 value;%0A %0A %09%09%09 value=(compareTime(dateString, now , shiftMinutes)) ? JSON.parse(localStorage.getItem(key)).value : null;%0A %0A return value;%0A %7D%0A return null;%0A %7D%0A%0A%09function compareTime(dateString, now , shiftMinutes) %7B%0A %09 return dateString+(shiftMinutes*60000) %3E now;%0A %7D%0A%09
%0A f
|
48a798fd6bca973c7eefa3dc4fcfc46694cb4ac0
|
Correct pick component.
|
src/framework/components/pick/pick_component.js
|
src/framework/components/pick/pick_component.js
|
pc.extend(pc.fw, function () {
/**
* @component
* @name pc.fw.PickComponent
* @constructor Create a new PickComponent
* @class Allows an Entity to be picked from the scene using a pc.fw.picking.Picker Object
* @param {pc.fw.PickComponentSystem} system The ComponentSystem that created this Component
* @param {pc.fw.Entity} entity The Entity that this Component is attached to.
* @extends pc.fw.Component
*/
var PickComponent = function PickComponent(system, entity) {
};
PickComponent = pc.inherits(PickComponent, pc.fw.Component);
pc.extend(PickComponent.prototype, {
addShape: function (shape, shapeName) {
var material = this.data.material;
var mesh = null;
switch (shape.type) {
case pc.shape.Type.BOX:
mesh = pc.scene.procedural.createBox(system.context.graphicsDevice, {
halfExtents: shape.halfExtents
});
break;
case pc.shape.Type.SPHERE:
mesh = pc.scene.procedural.createSphere(system.context.graphicsDevice, {
radius: shape.radius
});
break;
case pc.shape.Type.TORUS:
mesh = pc.scene.procedural.createTorus(system.context.graphicsDevice, {
tubeRadius: shape.iradius,
ringRadius: shape.oradius
});
break;
}
var node = new pc.scene.GraphNode();
var meshInstance = new pc.scene.MeshInstance(node, mesh, material);
meshInstance._entity = this.entity;
var model = new pc.scene.Model();
model.graph = node;
model.meshInstances = [ meshInstance ];
var shape = {
shape: shape,
shapeName: shapeName,
model: model
};
this.data.shapes.push(shape);
this.system.addShape(this.data.layer, shape);
},
deleteShapes: function () {
this.system.deleteShapes(this.data.layer, this.data.shapes);
this.data.shapes = [];
}
});
return {
PickComponent: PickComponent
};
}());
|
JavaScript
| 0 |
@@ -882,16 +882,21 @@
eateBox(
+this.
system.c
@@ -912,32 +912,32 @@
aphicsDevice, %7B%0A
-
@@ -1129,16 +1129,21 @@
eSphere(
+this.
system.c
@@ -1305,16 +1305,16 @@
.TORUS:%0A
-
@@ -1364,16 +1364,21 @@
teTorus(
+this.
system.c
|
a611c5b4ac851d626167df4bedee33fe1e587e10
|
add timeout to before hook
|
api/content-items/models/ContentItem.test.js
|
api/content-items/models/ContentItem.test.js
|
'use strict';
const mongoose = require('mongoose');
mongoose.Promise = Promise;
const Mockgoose = require('mockgoose').Mockgoose;
const mockgoose = new Mockgoose(mongoose);
const expect = require('chai').expect;
const ContentItem = require('./ContentItem');
describe('ContentItem Model', function() {
//extend timeout for mockgoose
this.timeout(120000);
before(function(done) {
mockgoose.prepareStorage().then(function() {
mongoose.connect('mongodb://example.com/TestingDB', function(err) {
done(err);
});
});
});
it('should require title', function (done) {
const testContentItem = new ContentItem({
description: 'the quick brown fox jumped over the lazy brown dog'
});
testContentItem.save((err) => {
expect(err).to.exist;
expect(err.message).to.equal('ContentItem validation failed: title: Path `title` is required.');
done();
});
});
it('should create a ContentItem when title is included title', function (done) {
const testContentItem = new ContentItem({
title: 'Gulliver\'s Travels'
});
testContentItem.save((err, item) => {
expect(err).to.not.exist;
expect(item.title).to.equal(testContentItem.title);
done();
});
});
it('should create a ContentItem and set the uniqueTitle', function (done) {
const testContentItem = new ContentItem({
title: 'Gulliver\'s Travels'
});
testContentItem.save((err, item) => {
expect(err).to.not.exist;
expect(item.uniqueTitle).to.contain('gulliver-s-travels-');
expect(item.uniqueTitle.length).to.equal(32);
done();
});
});
// restoring everything back
after( (done) => {
mockgoose.helper.reset().then(() => {
done();
});
});
});
|
JavaScript
| 0.000001 |
@@ -380,16 +380,42 @@
(done) %7B
+%0A this.timeout(120000);
%0A%0A mo
|
c277aedadd9fde4f4cfab0990cfcecdbf0f50531
|
Update for line and text -v7
|
scripts/JSRootPainter.v7more.js
|
scripts/JSRootPainter.v7more.js
|
/// @file JSRootPainter.v7more.js
/// JavaScript ROOT v7 graphics for different classes
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ['JSRootPainter', 'd3'], factory );
} else
if (typeof exports === 'object' && typeof module !== 'undefined') {
factory(require("./JSRootCore.js"), require("./d3.min.js"));
} else {
if (typeof d3 != 'object')
throw new Error('This extension requires d3.js', 'JSRootPainter.v7hist.js');
if (typeof JSROOT == 'undefined')
throw new Error('JSROOT is not defined', 'JSRootPainter.v7hist.js');
if (typeof JSROOT.Painter != 'object')
throw new Error('JSROOT.Painter not defined', 'JSRootPainter.v7hist.js');
factory(JSROOT, d3);
}
} (function(JSROOT, d3) {
"use strict";
JSROOT.sources.push("v7more");
// =================================================================================
function drawText() {
var text = this.GetObject(),
opts = text.fOpts,
pp = this.canv_painter(),
w = this.pad_width(),
h = this.pad_height(),
use_frame = false,
text_font = 42,
text_size = opts.fTextSize.fAttr,
text_angle = -opts.fTextAngle.fAttr;
//console.log(text_angle);
var textcolor = pp.GetNewColor(opts.fTextColor);
this.CreateG(use_frame);
var arg = { align: 13, x: Math.round(text.fX*w), y: Math.round(text.fY*h), text: text.fText, rotate: text_angle, color: textcolor, latex: 1 };
// if (text.fTextAngle) arg.rotate = -text.fTextAngle;
// if (text._typename == 'TLatex') { arg.latex = 1; fact = 0.9; } else
// if (text._typename == 'TMathText') { arg.latex = 2; fact = 0.8; }
this.StartTextDrawing(text_font, text_size);
this.DrawText(arg);
this.FinishTextDrawing();
}
function drawLine() {
}
// ================================================================================
JSROOT.v7.drawText = drawText;
JSROOT.v7.drawLine = drawLine;
return JSROOT;
}));
|
JavaScript
| 0 |
@@ -984,24 +984,26 @@
text
+
= this.GetOb
@@ -1031,16 +1031,18 @@
s
+
= text.f
@@ -1064,24 +1064,26 @@
pp
+
= this.canv_
@@ -1106,32 +1106,34 @@
w
+
= this.pad_width
@@ -1149,32 +1149,34 @@
h
+
= this.pad_heigh
@@ -1201,16 +1201,18 @@
_frame
+
= false,
@@ -1231,18 +1231,38 @@
ext_
-font = 42
+size = opts.fTextSize.fAttr
,%0A
@@ -1278,16 +1278,19 @@
ext_
-size
+angle
=
+-
opts
@@ -1287,35 +1287,36 @@
= -opts.fText
-Siz
+Angl
e.fAttr,%0A
@@ -1328,16 +1328,17 @@
xt_a
-ngle
+lign
=
--
opts
@@ -1348,20 +1348,67 @@
extA
-ngle
+lign.fAttr,%0A text_font = opts.fTextFont
.fAttr;%0A
%0A
@@ -1403,17 +1403,16 @@
.fAttr;%0A
-%0A
@@ -1558,10 +1558,18 @@
gn:
-13
+text_align
, x:
@@ -2042,23 +2042,826 @@
Line() %7B
+%0A%0A var line = this.GetObject(),%0A opts = line.fOpts,%0A pp = this.canv_painter(),%0A w = this.pad_height(),%0A h = this.pad_height(),%0A line_width = opts.fLineWidth.fAttr,%0A line_style = opts.fLineStyle.fAttr,%0A line_opacity = opts.fLineOpacity.fAttr;%0A%0A var linecolor = pp.GetNewColor(opts.fLineColor);%0A%0A this.CreateG();%0A%0A this.draw_g%0A .append(%22svg:line%22)%0A .attr(%22x1%22, line.fX1*w)%0A .attr(%22y1%22, h - line.fY1*h)%0A .attr(%22x2%22, line.fX2*w)%0A .attr(%22y2%22, h - line.fY2*h)%0A .style(%22stroke%22, linecolor)%0A .attr(%22stroke-width%22, line_width)%0A .style(%22stroke-dasharray%22, JSROOT.Painter.root_line_styles%5Bline_style%5D)%0A .attr(%22stroke-opacity%22, line_opacity)%0A%0A%0A
%0A %7D%0A%0A
+%0A%0A%0A
// ==
|
109886bf8171a1d02841af2aec39fcb303ec5ef0
|
Update release notes template
|
scripts/printReleaseNotesTemplate.js
|
scripts/printReleaseNotesTemplate.js
|
const CHANGELOG_COMMAND =
"git log --pretty=format:'%aN | %s | %h' --abbrev-commit --reverse origin/master..origin/next"
const execa = require('execa')
const TEMPLATE = `
Upgrade with:
sanity upgrade
And install the latest Command Line Interface (CLI) with:
npm install --global @sanity/cli
# ✨ Highlights
## Awesome feature X
A few words about the awesome feature X, preferably with screengifs
## Awesome feature Y
A few words about the awesome feature Y, preferably with screengifs
## Other features
- This is feature is not that important, but worth mentioning anyway
# 🐛 Notable bugfixes
- Fixed 🐞
- Fixed 🐛
- Fixed 🦗
# 📓 Full changelog
Author | Message | Commit
------------ | ------------- | -------------
${execa.shellSync(CHANGELOG_COMMAND).stdout}
`
console.log(`
-------- SANITY RELEASE NOTES TEMPLATE --------
Use the following template as a starting point for next release:
A draft can be created here: https://github.com/sanity-io/sanity/releases/new
-------- BEGIN TEMPLATE --------
${TEMPLATE}
-------- END TEMPLATE --------`)
|
JavaScript
| 0 |
@@ -179,57 +179,11 @@
ade
-with:%0A%0A sanity upgrade%0A%0AAnd install the latest
+the
Com
@@ -212,17 +212,16 @@
LI) with
-:
%0A%0A np
@@ -252,16 +252,70 @@
ty/cli%0A%0A
+Upgrade the Content Studio with:%0A%0A sanity upgrade%0A%0A
# %E2%9C%A8 High
|
d394493eea15170743c1b6864bcbf2509ed3b001
|
remove extraneous jasmine code in klassy-spec.js
|
spec/klassy-spec.js
|
spec/klassy-spec.js
|
;(function() {
'use strict';
describe('Klassy', function() {
describe('#isEmpty', function() {
it('exists as a function', function() {
expect(window.Klassy.isEmpty).toEqual(jasmine.any(Function));
});
it('takes an object as a parameter and returns true if the object is empty', function() {
expect(window.Klassy.isEmpty({})).toBe(true);
});
it('takes an object as a parameter and returns false if the object is not empty', function() {
var obj = { test: 'test' };
expect(window.Klassy.isEmpty(obj)).toBe(false);
});
});
});
})();
// describe('The `implements` method on the constructor function returned from invoking the Klass function', function() {
// var FooClass;
// beforeEach(function() {
// FooClass = Klass({
// initialInstanceMethod: function() {}
// }).extends({
// parentMethod: function() {}
// });
// });
// it('exists (as a function)', function() {
// expect(typeof FooClass.implements).toBe('function');
// });
// describe('`implements` method\'s ArgumentTypeErrors', function() {
// it('throws an ArgumenTypeError when passed with undefined: `ArgumentTypeError in .implements: expected array, got undefined`', function() {
// expect(function() { FooClass.implements(); }).toThrow('ArgumentTypeError in .implements: expected array, got undefined');
// expect(function() { FooClass.implements(undefined); }).toThrow('ArgumentTypeError in .implements: expected array, got undefined');
// });
// it('throws an ArgumenTypeError when passed with null: `ArgumentTypeError in .implements: expected array, got null`', function() {
// expect(function() { FooClass.implements(null); }).toThrow('ArgumentTypeError in .implements: expected array, got null');
// });
// it('throws an ArgumenTypeError when passed with an object: `ArgumentTypeError in .implements: expected array, got object`', function() {
// expect(function() { FooClass.implements({}); }).toThrow('ArgumentTypeError in .implements: expected array, got object');
// expect(function() { FooClass.implements(new Object()); }).toThrow('ArgumentTypeError in .implements: expected array, got object');
// });
// it('throws an ArgumenTypeError when passed with a function: `ArgumentTypeError in .implements: expected array, got function`', function() {
// expect(function() { FooClass.implements(function() {}); }).toThrow('ArgumentTypeError in .implements: expected array, got function');
// });
// it('throws an ArgumenTypeError when it is _not_ passed a string of functions: `ArgumentTypeError in .implements: expected an array of strings`', function() {
// expect(function() { FooClass.implements([function() {}]); }).toThrow('ArgumentTypeError in .implements: expected an array of strings');
// expect(function() { FooClass.implements([{}]); }).toThrow('ArgumentTypeError in .implements: expected an array of strings');
// expect(function() { FooClass.implements([1]); }).toThrow('ArgumentTypeError in .implements: expected an array of strings');
// expect(function() { FooClass.implements([1]); }).toThrow('ArgumentTypeError in .implements: expected an array of strings');
// });
// });
// describe('`implement` method\'s ImplementsErrors', function() {
// it('throws an ImplementsError when testing for the implementation of an _instance_ method or an _extended_ method: ', function() {
// expect(function() {
// FooClass.implements(['testMethod']);
// }).toThrow('ImplementsError: Klass does not implement testMethod');
// });
// });
// it('takes an array of strings that represent method names and attempt to call the methods', function() {
// FooClass.implements(['initialInstanceMethod', 'parentMethod']);
// var foo = new FooClass();
// spyOn(foo,'initialInstanceMethod');
// foo.initialInstanceMethod();
// spyOn(foo, 'parentMethod');
// foo.parentMethod();
// expect(foo.initialInstanceMethod).toHaveBeenCalled();
// expect(foo.parentMethod).toHaveBeenCalled();
// });
// it('returns the same constructor that it is called on (allowing it to be chainable)', function() {
// expect(FooClass).toBe(FooClass.implements(['parentMethod']));
// });
// });
|
JavaScript
| 0.000074 |
@@ -1,9 +1,8 @@
-%0A
;(functi
@@ -612,3737 +612,4 @@
();%0A
-%0A%0A%0A// describe('The %60implements%60 method on the constructor function returned from invoking the Klass function', function() %7B%0A// var FooClass;%0A// beforeEach(function() %7B%0A// FooClass = Klass(%7B%0A// initialInstanceMethod: function() %7B%7D%0A// %7D).extends(%7B%0A// parentMethod: function() %7B%7D%0A// %7D);%0A// %7D);%0A%0A// it('exists (as a function)', function() %7B%0A// expect(typeof FooClass.implements).toBe('function');%0A// %7D);%0A%0A// describe('%60implements%60 method%5C's ArgumentTypeErrors', function() %7B%0A// it('throws an ArgumenTypeError when passed with undefined: %60ArgumentTypeError in .implements: expected array, got undefined%60', function() %7B%0A// expect(function() %7B FooClass.implements(); %7D).toThrow('ArgumentTypeError in .implements: expected array, got undefined');%0A// expect(function() %7B FooClass.implements(undefined); %7D).toThrow('ArgumentTypeError in .implements: expected array, got undefined');%0A// %7D);%0A%0A// it('throws an ArgumenTypeError when passed with null: %60ArgumentTypeError in .implements: expected array, got null%60', function() %7B%0A// expect(function() %7B FooClass.implements(null); %7D).toThrow('ArgumentTypeError in .implements: expected array, got null');%0A// %7D);%0A%0A// it('throws an ArgumenTypeError when passed with an object: %60ArgumentTypeError in .implements: expected array, got object%60', function() %7B%0A// expect(function() %7B FooClass.implements(%7B%7D); %7D).toThrow('ArgumentTypeError in .implements: expected array, got object');%0A// expect(function() %7B FooClass.implements(new Object()); %7D).toThrow('ArgumentTypeError in .implements: expected array, got object');%0A// %7D);%0A%0A// it('throws an ArgumenTypeError when passed with a function: %60ArgumentTypeError in .implements: expected array, got function%60', function() %7B%0A// expect(function() %7B FooClass.implements(function() %7B%7D); %7D).toThrow('ArgumentTypeError in .implements: expected array, got function');%0A// %7D);%0A%0A// it('throws an ArgumenTypeError when it is _not_ passed a string of functions: %60ArgumentTypeError in .implements: expected an array of strings%60', function() %7B%0A// expect(function() %7B FooClass.implements(%5Bfunction() %7B%7D%5D); %7D).toThrow('ArgumentTypeError in .implements: expected an array of strings');%0A// expect(function() %7B FooClass.implements(%5B%7B%7D%5D); %7D).toThrow('ArgumentTypeError in .implements: expected an array of strings');%0A// expect(function() %7B FooClass.implements(%5B1%5D); %7D).toThrow('ArgumentTypeError in .implements: expected an array of strings');%0A// expect(function() %7B FooClass.implements(%5B1%5D); %7D).toThrow('ArgumentTypeError in .implements: expected an array of strings');%0A// %7D);%0A// %7D);%0A %0A// describe('%60implement%60 method%5C's ImplementsErrors', function() %7B%0A// it('throws an ImplementsError when testing for the implementation of an _instance_ method or an _extended_ method: ', function() %7B%0A// expect(function() %7B%0A// FooClass.implements(%5B'testMethod'%5D);%0A// %7D).toThrow('ImplementsError: Klass does not implement testMethod');%0A// %7D);%0A// %7D);%0A%0A// it('takes an array of strings that represent method names and attempt to call the methods', function() %7B%0A// FooClass.implements(%5B'initialInstanceMethod', 'parentMethod'%5D);%0A// var foo = new FooClass();%0A%0A// spyOn(foo,'initialInstanceMethod');%0A// foo.initialInstanceMethod();%0A%0A// spyOn(foo, 'parentMethod');%0A// foo.parentMethod();%0A%0A// expect(foo.initialInstanceMethod).toHaveBeenCalled();%0A// expect(foo.parentMethod).toHaveBeenCalled();%0A// %7D);%0A%0A// it('returns the same constructor that it is called on (allowing it to be chainable)', function() %7B%0A// expect(FooClass).toBe(FooClass.implements(%5B'parentMethod'%5D));%0A// %7D);%0A// %7D);
|
f1d26334f4976c8682f7a96c5a14f5b2a40ffc7a
|
Improve angular-module-name error message
|
rules/angular-module-name.js
|
rules/angular-module-name.js
|
'use strict';
const path = require('path');
const angularUtils = require('../utils/angular-utils');
'use strict';
module.exports = {
meta: {
docs: {
description: 'enforce naming modules after folder path to file',
category: 'Stylistic Issues',
recommended: false,
},
schema: [
{
type: 'object',
properties: {
basePath: {
type: 'string',
}
},
additionalProperties: false,
}
]
},
create,
};
function create(context) {
const options = context.options[0] || { basePath: '' };
return {
CallExpression: gatherAngularModuleInfos,
};
function gatherAngularModuleInfos(node) {
if (!angularUtils.isAngularModuleDeclaration(node) || !context.getFilename().includes(options.basePath)) {
return;
}
const moduleName = node.arguments[0].value;
const filePath = path.relative(options.basePath, context.getFilename());
const filePathInfo = path.parse(filePath)
const directoryPortion = filePathInfo.dir.split('/').join('.');
const expectedModuleName = `${directoryPortion}${directoryPortion.length ? '.' : '' }${filePathInfo.base.split('.')[0]}`;
if (moduleName !== expectedModuleName) {
context.report(node, `Module name must be "${expectedModuleName}"`);
}
}
};
|
JavaScript
| 0.000066 |
@@ -1484,16 +1484,42 @@
leName%7D%22
+ to match folder hierarchy
%60);%0A
|
50c753fd19994314fdad7667e21413f61b663b1a
|
Rename function
|
lib/node_modules/@stdlib/utils/timeit/lib/sync.js
|
lib/node_modules/@stdlib/utils/timeit/lib/sync.js
|
'use strict';
// MAIN //
/**
* Generates a source code body for synchronous execution.
*
* #### Notes
*
* * Example output:
*
* ``` javascript
* "use strict";
*
* var ctx = this;
* var t1, d1, i1;
*
* // {{before}}
*
* t1 = ctx.tic();
* for ( i1 = 0; i1 < 1e6; i1++ ) {
* // {{code}}
* }
* d1 = ctx.toc( t1 );
*
* // {{after}}
*
* ctx.done( null, d1 );
*
* return 1;
* ```
*
*
* @private
* @param {number} id - id
* @param {string} code - code to time
* @param {Options} opts - function options
* @param {string} opts.before - setup code
* @param {string} opts.after - cleanup code
* @param {PositiveInteger} opts.iterations - number of iterations
* @returns {string} source code body
*/
function body( id, code, opts ) {
var src;
var ctx;
var t;
var d;
var i;
src = '"use strict";';
// Declare variables:
ctx = '__ctx$'+id+'__';
i = '__i$'+id+'__';
t = '__t$'+id+'__';
d = '__d$'+id+'__';
src += 'var '+ctx+' = this;';
src += 'var '+t+','+d+','+i+';';
// Insert the setup code:
src += opts.before+';';
// Start the timer:
src += t+' = '+ctx+'.tic();';
// Create the loop:
src += 'for ( '+i+'= 0; '+i+' < '+opts.iterations+'; '+i+'++ ) {';
// Insert the loop body:
src += code+';';
// Close the loop:
src += '}';
// Stop the timer:
src += d+' = '+ctx+'.toc( '+t+' );';
// Insert the cleanup code:
src += opts.after+';';
// Return results:
src += ctx+'.done( null, '+d+' );';
// Return a value:
src += 'return '+id+';';
return src;
} // end FUNCTION body()
// EXPORTS //
module.exports = body;
|
JavaScript
| 0.000005 |
@@ -724,20 +724,24 @@
unction
-body
+generate
( id, co
@@ -1525,20 +1525,24 @@
UNCTION
-body
+generate
()%0A%0A%0A//
@@ -1570,14 +1570,18 @@
ports =
-body
+generate
;%0A
|
3d59e230b170f1e2ab2a9be2eabe664c0102de5d
|
Allow group tandems to recreate specific IDs for load, see https://github.com/phetsims/together/issues/319
|
js/Tandem.js
|
js/Tandem.js
|
// Copyright 2015, University of Colorado Boulder
/**
* Tandem is a general instance registry that can be used to track creation/disposal of instances in PhET Simulations.
* It is used for together.js instrumentation for PhET-iO support.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var inherit = require( 'PHET_CORE/inherit' );
var tandemNamespace = require( 'TANDEM/tandemNamespace' );
var StringUtils = require( 'PHETCOMMON/util/StringUtils' );
// text
var packageString = require( 'text!REPOSITORY/package.json' );
// constants
var packageJSON = JSON.parse( packageString );
/**
* @param {string} id - id as a string (or '' for a root id)
* @constructor
*/
function Tandem( id ) {
// @public {read-only}
this.id = (id !== undefined) ? id : '';
}
tandemNamespace.register( 'Tandem', Tandem );
// Listeners that will be notified when items are registered/deregistered
var instanceListeners = [];
inherit( Object, Tandem, {
/**
* Adds an instance of any type. For example, it could be an axon Property, scenery Node or Sun button. Each
* item should only be added to the registry once, but that is not enforced here in Tandem.
*
* This is used to register instances with together.
* @param {Object} instance - the instance to add
* @public
*/
addInstance: function( instance ) {
for ( var i = 0; i < instanceListeners.length; i++ ) {
instanceListeners[ i ].addInstance( this.id, instance );
}
},
/**
* Removes an instance from the
* @param {Object} instance - the instance to remove
* @public
*/
removeInstance: function( instance ) {
for ( var i = 0; i < instanceListeners.length; i++ ) {
instanceListeners[ i ].removeInstance( this.id, instance );
}
},
/**
* Create a new Tandem by appending the given id
* @param {string} id
* @returns {Tandem}
* @public
*/
createTandem: function( id ) {
var string = (this.id.length > 0) ? (this.id + '.' + id) : id;
return new Tandem( string );
},
/**
* Creates a group tandem for creating multiple indexed child tandems, such as:
* sim.screen.model.electron_0
* sim.screen.model.electron_1
*
* In this case, 'sim.screen.model.electron' is the group tandem id.
*
* Used for arrays, observable arrays, or when many elements of the same type are created and they do not otherwise
* have unique identifiers.
* @param id
* @returns {GroupTandem}
*/
createGroupTandem: function( id ) {
// Unfortunately we must resort to globals here since loading through the namespace would create a cycle
return new GroupTandem( this.id + '.' + id );
},
/**
* Get the last part of the tandem (after the last .), used in Joist for creating button names dynamically based
* on screen names
* @return {string} the tail of the tandem
*/
get tail() {
assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );
var lastIndexOfDot = this.id.lastIndexOf( '.' );
var tail = this.id.substring( lastIndexOfDot + 1 );
assert && assert( tail.length > 0, 'tandem ID did not have a tail' );
return tail;
}
}, {
/**
* Adds a listener that will be notified when items are registered/deregistered
* Listeners have the form
* {
* addInstance(id,instance),
* removeInstance(id,instance)
* }
* where id is of type {string} and instance is of type {Object}
*
* @param {Object} instanceListener - described above
* @public
* @static
*/
addInstanceListener: function( instanceListener ) {
instanceListeners.push( instanceListener );
},
/**
* Create a tandem based on the name of the running simulation.
* @returns {Tandem}
*/
createRootTandem: function() {
return new Tandem( StringUtils.toCamelCase( packageJSON.name ) );
},
/**
* Create a child of the root tandem.
* @param {string} name
* @returns {Tandem}
*/
createStaticTandem: function( name ) {
return Tandem.createRootTandem().createTandem( name );
}
} );
// Tandem checks for listeners added before the Tandem module was loaded. This is necessary so that together.js can
// receive notifications about items created during static initialization such as Solute.js
// which is created before Sim.js runs.
if ( window.tandemPreloadInstanceListeners ) {
for ( var i = 0; i < window.tandemPreloadInstanceListeners.length; i++ ) {
Tandem.addInstanceListener( window.tandemPreloadInstanceListeners[ i ] );
}
}
/**
* @param {string} id - id as a string (or '' for a root id)
* @constructor
* @private create with Tandem.createGroupTandem
* Declared in the same file to avoid circular reference errors in module loading.
*/
function GroupTandem( id ) {
Tandem.call( this, id );
// @private for generating indices from a pool
this.groupElementIndex = 0;
}
tandemNamespace.register( 'Tandem.GroupTandem', GroupTandem );
inherit( Tandem, GroupTandem, {
createNextTandem: function() {
return new Tandem( this.id + '_' + (this.groupElementIndex++) );
}
} );
return Tandem;
} );
|
JavaScript
| 0 |
@@ -5292,16 +5292,296 @@
ndem, %7B%0A
+%0A /**%0A * @param %5Bid%5D %7Bstring%7D optional override, used when loading a state and the tandems must be restored exactly as%0A * they were saved%0A * @returns %7BTandem%7D%0A */%0A createSpecificTandem: function( id ) %7B%0A return new Tandem( this.id + '_' + id );%0A %7D,%0A%0A
crea
@@ -5680,27 +5680,31 @@
+) );%0A %7D%0A
+
%7D
+%0A
);%0A%0A retur
|
5ba332feb93296cf5c697e6f568cbbf2d52e60df
|
Add password confirmation validation
|
server/controllers/authController.js
|
server/controllers/authController.js
|
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const emailValidator = require('email-validator');
const { createNewUser, findUserByUsername } = require('../models/services/user');
const { INVALID_INPUT_STATUS } = require('../utils/http');
const { transformOne } = require('../transformers/userTransformer');
const login = async (req, res) => {
const username = req.body.username;
const password = req.body.password;
try {
const user = await findUserByUsername(username);
if (!user) {
res.status(401).json({ message: 'username does not exist' });
}
const passwordIsValid = await bcrypt.compare(password, user.password);
if (!passwordIsValid) {
res.status(401).json({ message: 'authentication failed' });
}
const token = jwt.sign(
{ id: user.id },
process.env.JWT_SECRET,
{ issuer: process.env.JWT_ISSUER }
);
res.json({
success: true,
user: transformOne({ ...user, token }),
});
} catch ({ message }) {
res.status(500).json({ message });
}
};
const register = async (req, res) => {
const {
email,
password,
username,
firstName,
lastName
} = req.body;
if (!password || password.length < 8) {
return res.status(INVALID_INPUT_STATUS).json({ message: 'password must be at least 8 characters long' });
}
if (!emailValidator.validate(email)) {
return res.status(INVALID_INPUT_STATUS).json({ message: 'email is required and must be valid email' });
}
if (!username || username.length < 1) {
return res.status(INVALID_INPUT_STATUS).json({ message: 'username is required' });
}
const userExists = await findUserByUsername(username);
if (userExists) {
return res.status(INVALID_INPUT_STATUS).json({ message: 'username is already in use' });
}
const encryptedPassword = await bcrypt.hash(password, 8);
const user = await createNewUser({
email,
password: encryptedPassword,
username,
firstName,
lastName
});
return res.json(user);
};
module.exports = {
login,
register,
};
|
JavaScript
| 0.000001 |
@@ -1235,32 +1235,62 @@
password,%0A
+ passwordConfirmation,%0A
username
@@ -1503,32 +1503,175 @@
ong' %7D);%0A %7D%0A%0A
+ if (password !== passwordConfirmation) %7B%0A return res.status(INVALID_INPUT_STATUS).json(%7B message: 'passwords must match' %7D);%0A %7D%0A%0A
if (!emailVa
|
0dbc4cc303b128a9178e9a261b3e42c8b2486f37
|
Fix for double-timer issue in suggestions
|
media/js/impala/suggestions.js
|
media/js/impala/suggestions.js
|
$.fn.highlightTerm = function(val) {
// If an item starts with `val`, wrap the matched text with boldness.
val = val.replace(/[^\w\s]/gi, '');
var pat = new RegExp(val, 'gi');
this.each(function() {
var $this = $(this),
txt = $this.html(),
matchedTxt = txt.replace(pat, '<b>$&</b>');
if (txt != matchedTxt) {
$this.html(matchedTxt);
}
});
};
/*
* searchSuggestions
* Grants search suggestions to an input of type text/search.
* Required:
* $results - a container for the search suggestions, typically UL.
* processCallback - callback function that deals with the XHR call & populates
- the $results element.
* Optional:
* searchType - possible values are 'AMO', 'MKT'
*/
$.fn.searchSuggestions = function($results, processCallback, searchType) {
var $self = this,
$form = $self.closest('form');
if (!$results.length) {
return;
}
var cat = $results.attr('data-cat');
if (searchType == 'AMO') {
// Some base elements that we don't want to keep creating on the fly.
var msg;
if (cat == 'personas') {
msg = gettext('Search personas for <b>{0}</b>');
} else if (cat == 'apps') {
msg = gettext('Search apps for <b>{0}</b>');
} else {
msg = gettext('Search add-ons for <b>{0}</b>');
}
var base = template('<div class="wrap">' +
'<p><a class="sel" href="#"><span>{msg}</span></a></p><ul></ul>' +
'</div>');
$results.html(base({'msg': msg}));
} else if (searchType == 'MKT') {
$results.html('<div class="wrap"><ul></ul></div>');
}
// Control keys that shouldn't trigger new requests.
var ignoreKeys = [
z.keys.SHIFT, z.keys.CONTROL, z.keys.ALT, z.keys.PAUSE,
z.keys.CAPS_LOCK, z.keys.ESCAPE, z.keys.ENTER,
z.keys.PAGE_UP, z.keys.PAGE_DOWN,
z.keys.LEFT, z.keys.UP, z.keys.RIGHT, z.keys.DOWN,
z.keys.HOME, z.keys.END,
z.keys.COMMAND, z.keys.WINDOWS_RIGHT, z.keys.COMMAND_RIGHT,
z.keys.WINDOWS_LEFT_OPERA, z.keys.WINDOWS_RIGHT_OPERA, z.keys.APPLE
];
var gestureKeys = [z.keys.ESCAPE, z.keys.UP, z.keys.DOWN];
function pageUp() {
// Select the first element.
$results.find('.sel').removeClass('sel');
$results.removeClass('sel');
$results.find('a:first').addClass('sel');
}
function pageDown() {
// Select the last element.
$results.find('.sel').removeClass('sel');
$results.removeClass('sel');
$results.find('a:last').addClass('sel');
}
function dismissHandler() {
if ($results.hasClass('locked')) {
return;
}
$results.removeClass('visible sel');
$results.find('.sel').removeClass('sel');
if (searchType == 'MKT') {
$('#site-header').removeClass('suggestions');
}
}
function gestureHandler(e) {
// Bail if the results are hidden or if we have a non-gesture key
// or if we have a alt/ctrl/meta/shift keybinding.
if (!$results.hasClass('visible') ||
$.inArray(e.which, gestureKeys) < 0 ||
e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
$results.trigger('keyIgnored');
return;
}
e.preventDefault();
if (e.which == z.keys.ESCAPE) {
dismissHandler();
} else if (e.which == z.keys.UP || e.which == z.keys.DOWN) {
var $sel = $results.find('.sel'),
$elems = $results.find('a'),
i = $elems.index($sel.get(0));
if ($sel.length && i >= 0) {
if (e.which == z.keys.UP) {
// Clamp the value so it goes to the previous row
// but never goes beyond the first row.
i = Math.max(0, i - 1);
} else {
// Clamp the value so it goes to the next row
// but never goes beyond the last row.
i = Math.min(i + 1, $elems.length - 1);
}
} else {
i = 0;
}
$sel.removeClass('sel');
$elems.eq(i).addClass('sel');
$results.addClass('sel').trigger('selectedRowUpdate', [i]);
}
}
function inputHandler(e) {
var val = escape_($self.val());
if (val.length < 3) {
$results.filter('.visible').removeClass('visible');
return;
}
// Required data to send to the callback.
var settings = {
'$results': $results,
'$form': $form,
'searchTerm': val
};
// Optional data for callback.
if (searchType == 'AMO' || searchType == 'MKT') {
settings['category'] = cat;
}
if ((e.type === 'keyup' && typeof e.which === 'undefined') ||
$.inArray(e.which, ignoreKeys) >= 0) {
$results.trigger('inputIgnored');
} else {
// XHR call and populate suggestions.
processCallback(settings);
}
}
var pollVal;
if (z.capabilities.touch) {
$self.focus(function() {
pollVal = setInterval(function() {
gestureHandler($self);
inputHandler($self);
return;
}, 350);
});
}
$self.keydown(gestureHandler)
.bind('keyup paste', _.throttle(inputHandler, 250))
.blur(function() {
clearInterval(pollVal);
_.delay(dismissHandler, 250);
});
$results.delegate('li, p', 'hover', function() {
$results.find('.sel').removeClass('sel');
$results.addClass('sel');
$(this).find('a').addClass('sel');
}).delegate('a', 'click', _pd(function() {
$results.addClass('locked');
$form.submit();
}));
$results.bind('highlight', function(e, val) {
// If an item starts with `val`, wrap the matched text with boldness.
$results.find('ul a span').highlightTerm(val);
$results.addClass('visible');
if (!$results.find('.sel').length) {
pageUp();
}
});
$results.bind('dismiss', dismissHandler);
$form.submit(function(e) {
clearInterval(pollVal);
var $sel = $results.find('.sel');
if ($sel.length && $sel.eq(0).attr('href') != '#') {
e.stopPropagation();
e.preventDefault();
window.location = $sel.get(0).href;
}
$results.removeClass('locked');
dismissHandler();
});
$(document).keyup(function(e) {
if (fieldFocused(e)) {
return;
}
if (e.which == 83) {
$self.focus();
}
});
return this;
};
|
JavaScript
| 0 |
@@ -5248,16 +5248,20 @@
pollVal
+ = 0
;%0A%0A i
@@ -5312,32 +5312,173 @@
us(function() %7B%0A
+ // If we've already got a timer, clear it.%0A if (pollVal != 0) %7B%0A clearInterval(pollVal);%0A %7D%0A
poll
|
59db8493b2df11eddf7ee1c889237d164af416bd
|
fix chromecast plugin on native apps
|
modules/Chromecast/resources/chromecastLib.js
|
modules/Chromecast/resources/chromecastLib.js
|
(function() {var chrome = window.chrome || {};
chrome.cast = chrome.cast || {};
chrome.cast.media = chrome.cast.media || {};
chrome.cast.ApiBootstrap_ = function() {
};
chrome.cast.ApiBootstrap_.EXTENSION_IDS = ["boadgeojelhgndaghljhdicfkmllpafd", "dliochdbjfkdbacpmhlcpmleaejidimm", "hfaagokkkhdbgiakmmlclaapfelnkoah", "fmfcbgogabcbclcofgocippekhfcmgfj", "enhhojjnijigcajfphajepfemndkmdlo"];
chrome.cast.ApiBootstrap_.findInstalledExtension_ = function(callback) {
chrome.cast.ApiBootstrap_.findInstalledExtensionHelper_(0, callback);
};
chrome.cast.ApiBootstrap_.findInstalledExtensionHelper_ = function(index, callback) {
index == chrome.cast.ApiBootstrap_.EXTENSION_IDS.length ? callback(null) : chrome.cast.ApiBootstrap_.isExtensionInstalled_(chrome.cast.ApiBootstrap_.EXTENSION_IDS[index], function(installed) {
installed ? callback(chrome.cast.ApiBootstrap_.EXTENSION_IDS[index]) : chrome.cast.ApiBootstrap_.findInstalledExtensionHelper_(index + 1, callback);
});
};
chrome.cast.ApiBootstrap_.getCastSenderUrl_ = function(extensionId) {
return "chrome-extension://" + extensionId + "/cast_sender.js";
};
chrome.cast.ApiBootstrap_.isExtensionInstalled_ = function(extensionId, callback) {
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
4 == xmlhttp.readyState && 200 == xmlhttp.status && callback(!0);
};
xmlhttp.onerror = function() {
callback(!1);
};
xmlhttp.open("GET", chrome.cast.ApiBootstrap_.getCastSenderUrl_(extensionId), !0);
xmlhttp.send();
};
chrome.cast.ApiBootstrap_.findInstalledExtension_(function(extensionId) {
if (extensionId) {
console.log("Found cast extension: " + extensionId);
chrome.cast.extensionId = extensionId;
var apiScript = document.createElement("script");
apiScript.src = chrome.cast.ApiBootstrap_.getCastSenderUrl_(extensionId);
(document.head || document.documentElement).appendChild(apiScript);
} else {
var msg = "No cast extension found";
console.log(msg);
var callback = window.__onGCastApiAvailable;
callback && "function" == typeof callback && callback(!1, msg);
}
});
})();
|
JavaScript
| 0 |
@@ -6,16 +6,97 @@
tion() %7B
+%0A%09if ( navigator.userAgent.match(/kalturaNativeCordovaPlayer/) ) %7B%0A%09%09return;%0A%09%7D%0A%09
var chro
|
b3c9903954f96f0e62bd949d0973770fe33a45ac
|
Update custom consequence colors.
|
src/VariantLegendDialog.js
|
src/VariantLegendDialog.js
|
/*jslint node: true */
/*jshint laxbreak: true */
/*jshint laxcomma: true */
"use strict";
var d3 = require("d3");
var _ = require("underscore");
var LegendDialog = function() {
var createLegendRow = function(self, background, text) {
var row = self.dialog.append('div').classed('up_pftv_legend', true);
row.append('span')
.classed('up_pftv_legendRect', true)
.style('background-color', background);
row.append('span')
.classed('up_pftv_legendTitle', true)
.text(text);
};
var populateDialog = function(self) {
createLegendRow(self, self.UPDiseaseColor, 'Disease (UniProt)');
createLegendRow(self, self.getPredictionColor(0), 'Deleterious (Large scale studies)');
var colorScale = self.dialog.append('div');
colorScale.selectAll('div')
.data([0.2, 0.4, 0.6, 0.8])
.enter().append('div')
.classed('up_pftv_legend', true)
.append('span')
.classed('up_pftv_legendRect', true)
.style('background-color', function(d) {
return self.getPredictionColor(d);
})
;
createLegendRow(self, self.getPredictionColor(1), 'Benign (Large scale studies)');
createLegendRow(self, self.UPNonDiseaseColor, 'Non-disease (UniProt)');
createLegendRow(self, self.othersColor, 'Init codon, stop lost & gained');
};
return {
UPDiseaseColor: '#990000',
deleteriousColor: '#002594',
benignColor: '#8FE3FF',
UPNonDiseaseColor: '#99cc00',
othersColor: '#FFCC00',
consequenceColors: ["#66c2a5","#8da0cb","#e78ac3","#e5c494","#fc8d62","#ffd92f","#a6d854","#b3b3b3"],
getPredictionColor: d3.scale.linear()
.domain([0,1])
.range(['#002594','#8FE3FF']),
createLegendDialog: function(container, fv) {
this.dialog = container.append('div')
.attr('class','up_pftv_dialog-container');
populateDialog(this, fv);
return this.dialog;
}
};
}();
module.exports = LegendDialog;
|
JavaScript
| 0 |
@@ -1658,44 +1658,14 @@
%5B%22#
-66c2a5%22,%22#8da0cb%22,%22#e78ac3%22,%22#e5c494
+e78ac3
%22,%22#
@@ -1678,34 +1678,36 @@
%22,%22#
-ffd92f
+e5c494
%22,
+
%22#
-a6d854
+762A83
%22,
+
%22#
-b3b3b3
+B35806
%22%5D,%0A
|
3405b8ce4fd8058b6ca1a1701e2fe4d90707b5f7
|
fix optimization of JavaScript method calls
|
runtime/jslib_js_of_ocaml.js
|
runtime/jslib_js_of_ocaml.js
|
// Js_of_ocaml library
// http://www.ocsigen.org/js_of_ocaml/
// Copyright (C) 2010 Jérôme Vouillon
// Laboratoire PPS - CNRS Université Paris Diderot
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, with linking exception;
// either version 2.1 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////// Jslib: code specific to Js_of_ocaml
//Provides: caml_js_from_bool const (const)
function caml_js_from_bool(x) { return !!x; }
//Provides: caml_js_to_bool const (const)
function caml_js_to_bool(x) { return +x; }
//Provides: caml_js_from_float const (const)
function caml_js_from_float(x) { return x; }
//Provides: caml_js_to_float const (const)
function caml_js_to_float(x) { return x; }
//Provides: caml_js_from_string mutable (const)
//Requires: MlString
function caml_js_from_string(s) { return s.toString(); }
//Provides: caml_js_from_array mutable (shallow)
//Requires: raw_array_sub
function caml_js_from_array(a) { return raw_array_sub(a,1,a.length-1); }
//Provides: caml_js_to_array mutable (shallow)
//Requires: raw_array_cons
function caml_js_to_array(a) { return raw_array_cons(a,0); }
//Provides: caml_js_var mutable (const)
//Requires: js_print_stderr
//Requires: MlString
function caml_js_var(x) {
var x = x.toString();
//Checks that x has the form ident[.ident]*
if(!x.match(/^[a-zA-Z_$][a-zA-Z_$0-9]*(\.[a-zA-Z_$][a-zA-Z_$0-9]*)*$/)){
js_print_stderr("caml_js_var: \"" + x + "\" is not a valid JavaScript variable. continuing ..");
//joo_global_object.console.error("Js.Unsafe.eval_string")
}
return eval(x);
}
//Provides: caml_js_call (const, mutable, shallow)
//Requires: caml_js_from_array
function caml_js_call(f, o, args) { return f.apply(o, caml_js_from_array(args)); }
//Provides: caml_js_fun_call (const, shallow)
//Requires: caml_js_from_array
function caml_js_fun_call(f, args) { return f.apply(null, caml_js_from_array(args)); }
//Provides: caml_js_meth_call (mutable, mutable, shallow)
//Requires: MlString
//Requires: caml_js_from_array
function caml_js_meth_call(o, f, args) {
return o[f.toString()].apply(o, caml_js_from_array(args));
}
//Provides: caml_js_new (const, shallow)
//Requires: caml_js_from_array
function caml_js_new(c, a) {
switch (a.length) {
case 1: return new c;
case 2: return new c (a[1]);
case 3: return new c (a[1],a[2]);
case 4: return new c (a[1],a[2],a[3]);
case 5: return new c (a[1],a[2],a[3],a[4]);
case 6: return new c (a[1],a[2],a[3],a[4],a[5]);
case 7: return new c (a[1],a[2],a[3],a[4],a[5],a[6]);
case 8: return new c (a[1],a[2],a[3],a[4],a[5],a[6], a[7]);
}
function F() { return c.apply(this, caml_js_from_array(a)); }
F.prototype = c.prototype;
return new F;
}
//Provides: caml_js_wrap_callback const (const)
//Requires: caml_call_gen,raw_array_copy
function caml_js_wrap_callback(f) {
return function () {
if(arguments.length > 0){
return caml_call_gen(f, raw_array_copy(arguments));
} else {
return caml_call_gen(f, [undefined]);
}
}
}
//Provides: caml_js_wrap_meth_callback const (const)
//Requires: caml_call_gen,raw_array_cons
function caml_js_wrap_meth_callback(f) {
return function () {
return caml_call_gen(f,raw_array_cons(arguments,this));
}
}
//Provides: caml_js_wrap_meth_callback_unsafe const (const)
//Requires: caml_call_gen,raw_array_cons
function caml_js_wrap_meth_callback_unsafe(f) {
return function () { f.apply(null, raw_array_cons(arguments,this)); }
}
//Provides: caml_js_equals mutable (const, const)
function caml_js_equals (x, y) { return +(x == y); }
//Provides: caml_js_to_byte_string const
//Requires: caml_new_string
function caml_js_to_byte_string (s) {return caml_new_string (s);}
//Provides: caml_js_eval_string (const)
//Requires: MlString
function caml_js_eval_string (s) {return eval(s.toString());}
//Provides: caml_js_expr (const)
//Requires: js_print_stderr
//Requires: MlString
function caml_js_expr(s) {
js_print_stderr("caml_js_expr: fallback to runtime evaluation");
return eval(s.toString());}
//Provides: caml_pure_js_expr const (const)
//Requires: js_print_stderr
//Requires: MlString
function caml_pure_js_expr (s){
js_print_stderr("caml_pure_js_expr: fallback to runtime evaluation");
return eval(s.toString());}
//Provides: caml_js_object (object_literal)
//Requires: MlString
function caml_js_object (a) {
var o = {};
for (var i = 1; i < a.length; i++) {
var p = a[i];
o[p[1].toString()] = p[2];
}
return o;
}
|
JavaScript
| 0.000001 |
@@ -2538,23 +2538,21 @@
utable,
-mutable
+const
, shallo
|
1b87026df4716bb114cbf00aef4023d9ca319b93
|
Use camel case in js
|
app/assets/javascripts/likes.js
|
app/assets/javascripts/likes.js
|
$(document).ready(function() {
$('.like-btn').show();
$('.post-like').on('ajax:success', function(event, data) {
var like_button = $('#post-' + data.id + ' .post-like');
var like_badge = $('#post-'+ data.id + ' .like-badge');
$('#post-' + data.id + ' .like-count').text(data.like_count);
if (data.liked_by_member) {
like_badge.addClass('liked');
like_button.data('method', 'delete');
like_button.attr('href', data.url);
like_button.text('Unlike');
} else {
like_badge.removeClass('liked');
like_button.data('method', 'post');
like_button.attr('href', '/likes.json?post_id=' + data.id);
like_button.text('Like');
}
});
$('.photo-like').on('ajax:success', function(event, data) {
var like_badge = $('#photo-'+ data.id + ' .like-badge');
var like_button = $('#photo-'+ data.id + ' .like-btn');
$('#photo-' + data.id + ' .like-count').text(data.like_count);
if (data.liked_by_member) {
like_badge.addClass('liked');
// Turn the button into an unlike button
like_button.data('method', 'delete');
like_button.attr('href', data.url);
} else {
like_badge.removeClass('liked');
// Turn the button into an *like* button
like_button.data('method', 'post');
like_button.attr('href', '/likes.json?photo_id=' + data.id);
}
});
});
|
JavaScript
| 0.00039 |
@@ -115,34 +115,33 @@
) %7B%0A var like
-_b
+B
utton = $('#post
@@ -175,34 +175,33 @@
');%0A var like
-_b
+B
adge = $('#post-
@@ -331,34 +331,33 @@
er) %7B%0A like
-_b
+B
adge.addClass('l
@@ -366,34 +366,33 @@
ed');%0A like
-_b
+B
utton.data('meth
@@ -409,34 +409,33 @@
te');%0A like
-_b
+B
utton.attr('href
@@ -450,34 +450,33 @@
url);%0A like
-_b
+B
utton.text('Unli
@@ -496,34 +496,33 @@
lse %7B%0A like
-_b
+B
adge.removeClass
@@ -534,34 +534,33 @@
ed');%0A like
-_b
+B
utton.data('meth
@@ -575,34 +575,33 @@
st');%0A like
-_b
+B
utton.attr('href
@@ -644,26 +644,25 @@
;%0A like
-_b
+B
utton.text('
@@ -753,26 +753,25 @@
var like
-_b
+B
adge = $('#p
@@ -813,26 +813,25 @@
var like
-_b
+B
utton = $('#
@@ -970,26 +970,25 @@
%7B%0A like
-_b
+B
adge.addClas
@@ -1048,34 +1048,33 @@
utton%0A like
-_b
+B
utton.data('meth
@@ -1091,34 +1091,33 @@
te');%0A like
-_b
+B
utton.attr('href
@@ -1153,18 +1153,17 @@
like
-_b
+B
adge.rem
@@ -1234,26 +1234,25 @@
n%0A like
-_b
+B
utton.data('
@@ -1279,18 +1279,17 @@
like
-_b
+B
utton.at
|
6f2e1dc5a6a7bb593bc54500a4ff559a2d00086c
|
Add back in lost bugfix
|
js/backup.js
|
js/backup.js
|
oT.backup = {};
oT.backup.openPanel = function(){
oT.backup.populatePanel();
$('.backup-window').height( $('.textbox-container').height() * (3/5) );
$('.backup-panel').fadeIn('fast');
}
oT.backup.closePanel = function(){
$('.backup-panel').fadeOut('fast',function(){
$('.backup-window').empty();
});
}
oT.backup.generateBlock = function(ref){
// create icon and 'restore' button
var text = localStorage.getItem(ref);
var timestamp = ref.replace('oTranscribe-backup-','');
var date = oT.backup.formatDate(timestamp);
var block = document.createElement('div');
var doc = document.createElement('div');
var restoreButton = document.createElement('div');
block.className = 'backup-block';
doc.className = 'backup-doc';
restoreButton.className = 'backup-restore-button';
doc.innerHTML = text;
restoreButton.innerHTML = date+' - <span onClick="oT.backup.restore('+timestamp+');">restore</span>';
block.appendChild(doc);
block.appendChild(restoreButton);
return block;
}
oT.backup.formatDate = function(timestamp){
var d = new Date( parseFloat(timestamp) );
var day = d.getDate() + '/' + (d.getMonth()+1);
var now = new Date();
today = now.getDate() + '/' + (now.getMonth()+1);
yesterday = (now.getDate()-1) + '/' + (now.getMonth()+1);
if (day === today) {
day = 'Today';
} else if (day === yesterday) {
day = 'Yesterday'
}
var time = d.getHours() + ':';
if (d.getMinutes() < 10) {
time += '0';
}
time += d.getMinutes();
formattedDate = day + ' ' + time;
return formattedDate;
}
oT.backup.populatePanel = function(){
oT.backup.addDocsToPanel(0,8);
if (oT.backup.list().length === 0) {
$('.backup-window').append( '<div class="no-backups">No backups found.</div>' );
}
}
oT.backup.addDocsToPanel = function(start,end){
$('.more-backups').remove();
var allDocs = oT.backup.list();
docs = allDocs.slice(start,end);
for (var i = 0; i < docs.length; i++) {
$('.backup-window').append( oT.backup.generateBlock(docs[i]) );
}
if (allDocs[end]) {
$('.backup-window').append( '<div class="more-backups" onclick="oT.backup.addDocsToPanel('+(end)+','+(end+8)+')" >Load older backups</div>' );
}
}
oT.backup.save = function(){
// save current text to timestamped localStorage item
var text = document.getElementById("textbox");
var timestamp = new Date().getTime();
oT.backup.saveToLocalStorage('oTranscribe-backup-'+timestamp, text.innerHTML);
// and bleep icon
$('.sbutton.backup').addClass('flash');
setTimeout(function(){
$('.sbutton.backup').removeClass('flash');
},1000);
// and add to tray
var newBlock = oT.backup.generateBlock('oTranscribe-backup-'+timestamp);
newBlock.className += ' new-block';
$('.backup-window').prepend( newBlock );
$( newBlock ).animate({
'opacity': 1,
'width': '25%'
},'slow',function(){
$( newBlock ).find('.backup-restore-button').fadeIn();
});
}
oT.backup.saveToLocalStorage = function(name){
console.log(name);
try {
localStorage.setItem( name );
} catch (e) {
console.log('error');
if(e.name === "NS_ERROR_DOM_QUOTA_REACHED") {
oT.backup.removeOldest();
// oT.backup.save();
}
}
}
oT.backup.init = function(){
setInterval(function(){
oT.backup.save();
oT.backup.cleanup();
},300000 /* 5 minutes */);
}
oT.backup.list = function(){
var result = [];
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).indexOf('oTranscribe-backup') > -1) {
result.push(localStorage.key(i));
}
}
return result.sort().reverse();
}
oT.backup.restore = function(timestamp){
oT.backup.save();
var textbox = document.getElementById("textbox");
var newText = localStorage.getItem('oTranscribe-backup-'+timestamp);
document.getElementById("textbox").innerHTML = newText;
oT.backup.closePanel();
}
oT.backup.cleanup = function(){
var backups = oT.backup.list();
for (var i = 0; i < backups.length; i++) {
var bu = backups[i];
var ts = bu.replace('oTranscribe-backup-','');
var date = new Date( parseFloat( ts ) );
var diff = Date.now() - date;
// 1 day = 86400000 miliseconds
if (diff > (86400000*7) ) {
localStorage.removeItem( bu );
}
}
}
oT.backup.removeOldest = function(){
localStorage.clear();
var list = oT.backup.list();
// var toDelete = list.slice(Math.max(list.length - 5, 1));
var toDelete = list;
console.log('todelete: ',toDelete);
for (var i = 0; i < toDelete.length; i++) {
console.log('deleting '+toDelete[i])
localStorage.removeItem( toDelete[i] );
}
}
// original autosave function
function saveText(){
var field = document.getElementById("textbox");
// load existing autosave (if present)
if ( localStorage.getItem("autosave")) {
field.innerHTML = localStorage.getItem("autosave");
}
// autosave every second - but wait five seconds before kicking in
setTimeout(function(){
setInterval(function(){
oT.backup.saveToLocalStorage("autosave", field.innerHTML);
}, 1000);
}, 5000);
}
|
JavaScript
| 0 |
@@ -5281,32 +5281,144 @@
out(function()%7B%0A
+ // prevent l10n from replacing user text%0A $('#textbox p%5Bdata-l10n-id%5D').attr('data-l10n-id','');%0A
setInter
|
f56ea1d936fca9f24e50e90e1f217f84112091d2
|
remove cache task imagemin
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
cache = require('gulp-cache'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
minifyCss = require('gulp-minify-css'),
imagemin = require('gulp-imagemin');
/**
* Imagemin Task
*/
gulp.task('imagemin', function () {
return gulp.src('src/img/**/*.{jpg,png,gif}')
.pipe(plumber())
.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/img/'));
});
/**
* Javascript Task
*/
gulp.task('js', function () {
return gulp.src('src/js/**/*.js')
.pipe(plumber())
.pipe(concat('main.js'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'));
});
/**
* CSS Task
*/
gulp.task('css', function () {
return gulp.src('src/css/*.css')
.pipe(plumber())
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(gulp.dest('assets/css/'));
});
/**
* Watch stylus files for changes & recompile
* Watch html/md files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('src/js/**/*.js', ['js']);
gulp.watch('src/css/*.css', ['css']);
gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
});
gulp.task('default', ['imagemin', 'js', 'css', 'watch']);
|
JavaScript
| 0.000004 |
@@ -438,14 +438,8 @@
ipe(
-cache(
imag
@@ -506,17 +506,16 @@
true %7D))
-)
%0A
|
cd898673f999c34c2679f9cd015ad666bf0c01ba
|
remove semi-colons
|
index.es6.js
|
index.es6.js
|
import createVirtualAudioGraph from 'virtual-audio-graph';
export default ({audioContext = new AudioContext(),
output = audioContext.destination} = {}) => {
const virtualAudioGraph = createVirtualAudioGraph({audioContext, output});
return nodeParams$ => nodeParams$.subscribe(nodeParams => virtualAudioGraph.update(nodeParams));
};
|
JavaScript
| 0.999999 |
@@ -50,17 +50,16 @@
o-graph'
-;
%0A%0Aexport
@@ -242,17 +242,16 @@
output%7D)
-;
%0A retur
@@ -344,9 +344,7 @@
ms))
-;
%0A%7D
-;
%0A
|
50e8a0a41f940d420d6d2d2fe8d0382c17af682c
|
Update gulp pipe to br more semantic
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
header = require('gulp-header'),
include = require('gulp-include'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');
var pkg = require('./bower.json')
fs = require('fs');
var dev = {
mangle: false,
compress: true,
preserveComments: 'some',
output: {
beautify: true,
indent_level: 2,
ascii_only: true,
comments: false,
width: 80
}
};
var prod = {
mangle: true,
preserveComments: 'some',
compress: {
global_defs: 'angular'
}
};
function min(path) {
path.basename += ".min";
}
function banner() {
var today = new Date();
var license = fs.readFileSync('./LICENSE.md').toString()
.split('\n').splice(3).join('\n');
var banner = [
'/**!',
' * <%= pkg.title %> v<%= pkg.version %>',
' * <%= pkg.homepage %>',
' * Copyright (c) <%= today.getFullYear() %> <%= pkg.author %>',
' * <%= license.replace(/\\n/gm, "\\n * ") %>',
' */',
''].join('\n');
return header(banner, {pkg: pkg, today: today, license: license});
}
gulp.task('build', function() {
gulp.src('src/*.js')
.pipe(include())
// Dev file
.pipe(uglify(dev))
.pipe(banner())
.pipe(gulp.dest('dist/'))
// Prod file
.pipe(rename(min))
.pipe(uglify(prod))
.pipe(banner())
.pipe(gulp.dest('dist/'));
});
|
JavaScript
| 0 |
@@ -235,22 +235,48 @@
);%0A%0A
-var dev =
+%0Afunction dev() %7B%0A return uglify(
%7B%0A
+
+
mang
@@ -286,16 +286,18 @@
false,%0A
+
compre
@@ -298,32 +298,34 @@
compress: true,%0A
+
preserveCommen
@@ -338,16 +338,18 @@
ome',%0A
+
+
output:
@@ -346,24 +346,26 @@
output: %7B%0A
+
beautify
@@ -376,16 +376,18 @@
ue,%0A
+
+
indent_l
@@ -395,16 +395,18 @@
vel: 2,%0A
+
asci
@@ -423,16 +423,18 @@
ue,%0A
+
comments
@@ -446,16 +446,18 @@
se,%0A
+
width: 8
@@ -462,29 +462,61 @@
80%0A
+
%7D%0A
-%7D;%0A%0Avar prod = %7B%0A
+ %7D);%0A%7D%0A%0Afunction prod() %7B%0A return uglify(%7B%0A
ma
@@ -529,16 +529,18 @@
true,%0A
+
+
preserve
@@ -557,16 +557,18 @@
'some',%0A
+
compre
@@ -577,16 +577,18 @@
: %7B%0A
+
global_d
@@ -608,12 +608,19 @@
'%0A
+
+
%7D%0A
+ %7D);%0A
%7D
-;
%0A%0Afu
@@ -1249,18 +1249,12 @@
ipe(
-uglify(
dev
+(
))%0A
@@ -1356,19 +1356,13 @@
ipe(
-uglify(
prod
+(
))%0A
|
75d4a274d8edbec19d2111fa37d26c5e786a0c83
|
define usage target for cssnext (autoprefixer & rem/px fallback) to last 2 version
|
gulpfile.js
|
gulpfile.js
|
// jchck_'s gulpfile
//
// site's dev URL (used in the watch task below)
//
var devUrl = 'http://vagrant.local/jchck/';
//
// gulp plugin registry
//
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var atImport = require('postcss-import');
var mqpacker = require('css-mqpacker');
var cssnano = require('cssnano');
var size = require('gulp-size');
var cssvariables = require('postcss-css-variables');
var browserSync = require('browser-sync').create();
//
// css processing task
//
// $ gulp css
//
gulp.task('css', function(){
// postcss plugin registry
var postcssPlugins = [
atImport,
cssvariables,
cssnano,
cssnext,
mqpacker,
];
// processing plumbing
return gulp.src('./src/css/jchck_.css')
// postcss it
.pipe(postcss(postcssPlugins))
// what's the size?
.pipe(size({gzip: false, showFiles: true, title: 'Processed!'}))
.pipe(size({gzip: true, showFiles: true, title: 'Processed & gZipped!'}))
// spit it out
.pipe(gulp.dest('./dest'))
// add to the browser sync stream
.pipe(browserSync.stream());
});
//
// watch task
//
// $ gulp watch
//
gulp.task('watch', function(){
browserSync.init({
// the php files to watch
files: [
'{lib,templates}/**/*.php',
'*.php'
],
// the url getting proxied, defined above
proxy: devUrl,
// @see https://www.browsersync.io/docs/options/#option-snippetOptions
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
// the css files to watch on change runs the css processing task
gulp.watch(['./src/css/*'], ['css']);
});
//
// default task
//
// $ gulp
//
gulp.task('default', ['css', 'watch']);
|
JavaScript
| 0 |
@@ -717,16 +717,57 @@
%09cssnext
+(%7B%0A%09%09%09'browsers': %5B'last 2 version'%5D%0A%09%09%7D)
,%0A%09%09mqpa
|
c999457337214ab105626cb331ea0fe80115bc96
|
fix ios index file
|
index.ios.js
|
index.ios.js
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class strava extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('strava', () => strava);
|
JavaScript
| 0.000001 |
@@ -1,1006 +1,92 @@
-/**%0A * Sample React Native App%0A * https://github.com/facebook/react-native%0A * @flow%0A */%0A%0Aimport React, %7B Component %7D from 'react';%0Aimport %7B%0A AppRegistry,%0A StyleSheet,%0A Text,%0A View%0A%7D from 'react-native';%0A%0Aexport default class strava extends Component %7B%0A render() %7B%0A return (%0A %3CView style=%7Bstyles.container%7D%3E%0A %3CText style=%7Bstyles.welcome%7D%3E%0A Welcome to React Native!%0A %3C/Text%3E%0A %3CText style=%7Bstyles.instructions%7D%3E%0A To get started, edit index.ios.js%0A %3C/Text%3E%0A %3CText style=%7Bstyles.instructions%7D%3E%0A Press Cmd+R to reload,%7B'%5Cn'%7D%0A Cmd+D or shake for dev menu%0A %3C/Text%3E%0A %3C/View%3E%0A );%0A %7D%0A%7D%0A%0Aconst styles = StyleSheet.create(%7B%0A container: %7B%0A flex: 1,%0A justifyContent: 'center',%0A alignItems: 'center',%0A backgroundColor: '#F5FCFF',%0A %7D,%0A welcome: %7B%0A fontSize: 20,%0A textAlign: 'center',%0A margin: 10,%0A %7D,%0A instructions: %7B%0A textAlign: 'center',%0A color: '#333333',%0A marginBottom: 5,%0A %7D,%0A%7D)
+'use strict';%0Aimport React, %7B AppRegistry %7D from 'react-native';%0Aimport App from './app'
;%0A%0AA
@@ -134,13 +134,9 @@
=%3E
-strava
+App
);
-%0A
|
45b8423d525a84a45145ed0e055bad2d89b860cb
|
update localhost
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
cssnano = require('gulp-cssnano'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
notify = require('gulp-notify'),
bs = require('browser-sync').create(),
proxyUrl = 'localhost/razvantirboaca.com';
var paths = {
watch : {
sass: 'src/css/**/**/*.scss',
js: 'src/js/**/**/*.js'
},
src: {
css: 'src/css/style.scss',
js: 'src/js/',
node: 'node_modules/'
},
dist: 'dist/'
};
gulp.task('browser-sync', function() {
bs.init({
proxy: proxyUrl,
scriptPath: function (path, port, options) {
return options.get("absolute");
},
files: ['./*.html', '!' + paths.dist + 'css/*']
});
});
gulp.task('sass', function () {
var onError = function(err) {
notify.onError({
title: 'Sass error',
message: 'Error: <%= error.message %>'
})(err);
this.emit('end');
};
return gulp.src(paths.src.css)
.pipe(plumber({errorHandler: onError}))
.pipe(sass())
.pipe(postcss([
autoprefixer()
]))
.pipe(cssnano())
.pipe(gulp.dest(paths.dist + 'css'))
.pipe(notify({ message: 'Sass task complete' }))
.pipe(bs.stream())
});
gulp.task('js', function () {
var onError = function(err) {
notify.onError({
title: 'JS error',
message: 'Error: <%= error.message %>'
})(err);
this.emit('end');
};
return gulp.src([
paths.src.js + 'lazy-load.js',
paths.src.node + 'photoswipe/dist/photoswipe.min.js',
paths.src.node + 'photoswipe/dist/photoswipe-ui-default.min.js',
paths.src.js + 'app.js'
])
.pipe(plumber({errorHandler: onError}))
.pipe(concat('app.js'))
//.pipe(uglify())
.pipe(gulp.dest(paths.dist + 'js'))
.pipe(notify({ message: 'JS task complete' }))
.pipe(bs.stream())
});
gulp.task('default', ['browser-sync'], function(){
// Listen to change events on scss and compile sass
gulp.watch(paths.watch.sass, ['sass']);
// Listen to change events on js and concat js
gulp.watch(paths.watch.js, ['js']);
});
|
JavaScript
| 0.000002 |
@@ -449,19 +449,25 @@
irboaca.
-com
+github.io
';%0A%0Avar
|
1186ae1d44441ec7b72ef482e419e4bd472a0e5b
|
use exclude_geometry: true
|
app/isochrones/route.js
|
app/isochrones/route.js
|
import Ember from 'ember';
import setLoading from 'mobility-playground/mixins/set-loading';
export default Ember.Route.extend(setLoading, {
queryParams: {
isochrone_mode: {
replace: true,
refreshModel: true,
},
pin: {
replace: true,
refreshModel: true
},
departure_time: {
replace: true,
refreshModel: true
},
include_operators: {
replace: true,
refreshModel: true
},
exclude_operators: {
replace: true,
refreshModel: true
},
include_routes: {
replace: true,
refreshModel: true
},
exclude_routes: {
replace: true,
refreshModel: true
},
stop: {
replace: true,
refreshModel: true
}
},
setupController: function (controller, model) {
if (controller.get('bbox') !== null){
var coordinateArray = [];
var bboxString = controller.get('bbox');
var tempArray = [];
var boundsArray = [];
coordinateArray = bboxString.split(',');
for (var i = 0; i < coordinateArray.length; i++){
tempArray.push(parseFloat(coordinateArray[i]));
}
var arrayOne = [];
var arrayTwo = [];
arrayOne.push(tempArray[1]);
arrayOne.push(tempArray[0]);
arrayTwo.push(tempArray[3]);
arrayTwo.push(tempArray[2]);
boundsArray.push(arrayOne);
boundsArray.push(arrayTwo);
controller.set('leafletBounds', boundsArray);
}
controller.set('leafletBbox', controller.get('bbox'));
this._super(controller, model);
},
model: function(params){
this.store.unloadAll('data/transitland/operator');
this.store.unloadAll('data/transitland/stop');
this.store.unloadAll('data/transitland/route');
this.store.unloadAll('data/transitland/route_stop_pattern');
if (params.isochrone_mode){
var pinLocation = params.pin;
if (typeof(pinLocation)==="string"){
var pinArray = pinLocation.split(',');
pinLocation = pinArray;
}
var mode = params.isochrone_mode;
var url = 'https://matrix.mapzen.com/isochrone?api_key=mapzen-jLrDBSP&json=';
var linkUrl = 'https://matrix.mapzen.com/isochrone?json=';
var json = {
locations: [{"lat":pinLocation[0], "lon":pinLocation[1]}],
costing: mode,
denoise: 0.3,
polygons: true,
generalize: 50,
costing_options: {"pedestrian":{"use_ferry":0}},
contours: [{"time":15},{"time":30},{"time":45},{"time":60}],
};
if (json.costing === "multimodal"){
json.denoise = 0;
// transit_start_end_max_distance default is 2145 or about 1.5 miles for start/end distance:
// transit_transfer_max_distance default is 800 or 0.5 miles for transfer distance:
// exclude - exclude all of the ids listed in the filter
// include - include only the ids listed in the filter
// Once /routes?operated_by= accepts a comma-separated list:
// Only query for routes operated by selected operators.
json.costing_options.pedestrian = {
"use_ferry":0,
"transit_start_end_max_distance":100000,
"transit_transfer_max_distance":100000
};
json.costing_options["transit"]={};
json.costing_options.transit["filters"]={}
if (params.include_operators.length > 0) {
json.costing_options.transit.filters["operators"] = {
"ids": params.include_operators,
"action":"include"
};
} else if (params.exclude_operators.length > 0) {
json.costing_options.transit.filters["operators"] = {
"ids": params.exclude_operators,
"action":"exclude"
};
}
if (params.include_routes.length > 0) {
json.costing_options.transit.filters["routes"] = {
"ids": params.include_routes,
"action":"include"
};
} else if (params.exclude_routes.length > 0) {
json.costing_options.transit.filters["routes"] = {
"ids": params.exclude_routes,
"action":"exclude"
};
}
if (params.departure_time){
json.date_time = {"type": 1, "value": params.departure_time};
}
}
url = encodeURI(url + JSON.stringify(json));
linkUrl = encodeURI(linkUrl + JSON.stringify(json));
var isochrones = Ember.$.ajax({ url });
var operators = this.store.query('data/transitland/operator', {bbox: params.bbox});
var routes;
if (params.include_operators.length > 0){
// change routes query to be only for the selected operator(s) routes
var includeOperators = "";
for (var j = 0; j < params.include_operators.length; j++){
if (j > 0){
includeOperators += ","
}
includeOperators += params.include_operators[j]
}
routes = this.store.query('data/transitland/route', {bbox: params.bbox, operated_by: includeOperators});
} else {
routes = this.store.query('data/transitland/route', {bbox: params.bbox});
}
return Ember.RSVP.hash({
operators: operators,
routes: routes,
isochrones: isochrones,
linkUrl: linkUrl
});
}
},
actions: {
}
});
|
JavaScript
| 0.999999 |
@@ -4579,16 +4579,40 @@
perators
+, exclude_geometry: true
%7D);%0A%09%09%09%7D
@@ -4689,24 +4689,48 @@
params.bbox
+, exclude_geometry: true
%7D);%0A%09%09%09%7D%0A%0A%09%09
@@ -4727,16 +4727,17 @@
;%0A%09%09%09%7D%0A%0A
+%0A
%09%09%09retur
|
e209764100d3690ecedeffe55ec4d935ce937a1b
|
add eow
|
background.js
|
background.js
|
chrome.contextMenus.create({
"title": "LookUpInOALD",
"type": "normal",
"contexts": ["selection"],
"onclick":function() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, { "message": "clicked_browser_action" });
});
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message === "open_new_tab") {
var oald = 'http://www.oxfordlearnersdictionaries.com/search/english/?q=' + request.word;
chrome.tabs.create({ "url": oald });
}
});
|
JavaScript
| 0.999628 |
@@ -561,40 +561,143 @@
-chrome.tabs.create(%7B %22url%22: oald
+var eow = 'http://eow.alc.co.jp/search?q=' + request.word;%0A chrome.tabs.create(%7B %22url%22: oald %7D);%0A chrome.tabs.create(%7B %22url%22: eow
%7D);
|
feb2e5fc7ca547222a89b55be1bca88d4bf007b4
|
Remove stray unused import
|
assets/scripts/app/load_resources.js
|
assets/scripts/app/load_resources.js
|
/**
* load_resources
*
* Loads images, etc and tracks progress. (WIP)
* TODO: Rely on Promises to resolve progress
*/
import { checkIfEverythingIsLoaded } from './initialization'
// Image tileset loading
// TODO: Deprecate in favor of inlined SVGs
const TILESET_IMAGE_VERSION = 55
const IMAGES_TO_BE_LOADED = [
'/images/tiles-1.png',
'/images/tiles-2.png',
'/images/tiles-3.png',
'/images/sky-front.png',
'/images/sky-rear.png'
]
const SVGS_TO_BE_LOADED = [
'/assets/images/icons.svg',
'/assets/images/images.svg'
]
const SVGStagingEl = document.getElementById('svg')
export const images = [] // This is an associative array; TODO: something else
let loading = []
// Set loading bar
const loadingEl = document.getElementById('loading-progress')
loadingEl.max += 5 // Legacy; this is for other things that must load
// Load everything
loadImages()
loadSVGs()
// When everything is loaded...
export function checkIfImagesLoaded () {
return Promise.all(loading)
}
function loadImages () {
loadingEl.max += IMAGES_TO_BE_LOADED.length
for (let url of IMAGES_TO_BE_LOADED) {
loading.push(getImage(url + '?v' + TILESET_IMAGE_VERSION)
.then(function (image) {
// Store on the global images object, using the url as the key
images[url] = image
loadingEl.value++
})
.catch(function (error) {
console.error('loading image error', error.message)
}))
}
}
function loadSVGs () {
loadingEl.max += SVGS_TO_BE_LOADED.length
for (let url of SVGS_TO_BE_LOADED) {
loading.push(window.fetch(url)
.then(function (response) {
return response.text()
})
.then(function (response) {
SVGStagingEl.innerHTML += response
// ctx.drawImage() can only draw things that are images, so you can't draw
// an SVG directly. You also can't <use> a symbol reference from inside an
// image tag. So we have to create an image using a reconstructed SVG as a
// data-URI. Here, let's cache all the artwork svgs as image elements for
// later rendering to canvas
let svgEls = SVGStagingEl.querySelectorAll('symbol')
for (let svg of svgEls) {
// Only cache segment illustrations, don't need to cache icons
if (svg.id.indexOf('image-') === 0) {
// Simplify id, removing namespace prefix
const id = svg.id.replace(/^image-/, '')
// Get details of the SVG so we can reconstruct an image element
const svgViewbox = svg.getAttribute('viewBox')
let svgInternals = svg.innerHTML
// innerHTML is not an available property for SVG elements in IE / Edge
// so if turns to be undefined, we use this alternate method below,
// which iterates through each of the symbol's child nodes and
// serializes each element to a string.
if (typeof svgInternals === 'undefined') {
svgInternals = ''
Array.prototype.slice.call(svg.childNodes).forEach(function (node, index) {
svgInternals += (new window.XMLSerializer()).serializeToString(node)
})
}
// SVG element requires the 'xmlns' namespace
// As well as the original viewBox attribute
// The width and height values are required in Firefox
// and to display them at the correct size in IE / Edge
const svgWidth = svg.viewBox.baseVal.width
const svgHeight = svg.viewBox.baseVal.height
const svgHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${svgViewbox}" width="${svgWidth}" height="${svgHeight}">${svgInternals}</svg>`
const img = new window.Image()
// Browsers appear to do better with base-64 URLs rather than Blobs
// (Chrome works with blobs, but setting width and height on SVG
// makes rendering intermittent)
img.src = 'data:image/svg+xml;base64,' + window.btoa(svgHTML)
// Store on the global images object, using its simplified id as the key
images[id] = img
}
}
loadingEl.value++
})
.catch(function (error) {
console.error('loading svg error', error)
}))
}
}
/**
* Wraps `new Image()`'s onload and onerror properties with
* Promises. This provides a more reliable way of knowing when a
* image element is done loading (rather than fetch) because a
* fetch can successfully load an image file but be resolved
* before the image element is ready. So we must resolve only after
* the image's `onload` callback has been called.
*/
function getImage (url) {
return new Promise(function (resolve, reject) {
var img = new window.Image()
img.onload = function () {
resolve(img)
}
img.onerror = function () {
reject(new Error('unable to load image ' + url))
}
img.src = url
})
}
export function hideLoadingScreen () {
// NOTE:
// This function might be called on very old browsers. Please make
// sure not to use modern faculties.
document.getElementById('loading').className += ' hidden'
}
|
JavaScript
| 0 |
@@ -121,70 +121,8 @@
*/%0A%0A
-import %7B checkIfEverythingIsLoaded %7D from './initialization'%0A%0A
// I
|
c577f1a55758416fe7e886ba89749265f7a746b5
|
fix link to user manual
|
src/menu/views/HelpMenu.js
|
src/menu/views/HelpMenu.js
|
import MenuBuilder from "../menubuilder";
const HelpMenu = MenuBuilder.extend({
initialize: function(data) {
return this.g = data.g;
},
render: function() {
this.setName("Help");
this.addNode("About the project", () => {
return window.open("https://github.com/wilzbach/msa");
});
this.addNode("Report issues", () => {
return window.open("https://github.com/wilzbach/msa/issues");
});
this.addNode("User manual", () => {
return window.open("https://github.com/wilzbach/msa/wiki");
});
this.el.style.display = "inline-block";
this.el.appendChild(this.buildDOM());
return this;
}
});
export default HelpMenu;
|
JavaScript
| 0.000001 |
@@ -524,16 +524,28 @@
msa/wiki
+/User-manual
%22);%0A
|
a9976001a710c4aebadca04a245b2c7f700a2fb9
|
Test nouvelle facon de tourner
|
src/public/script/RoyalPac.js
|
src/public/script/RoyalPac.js
|
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update
});
function preload() {
game.load.tilemap('ClassicMap', '../assets/RoyalPac-mapV2.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles', '../assets/TileSet.png');
game.load.image('star', '../assets/star.png');
game.load.spritesheet('pacman','../assets/pacman_test.png',25,25,13);
}
var map;
var layer;
var player;
var tiles;
var tileset;
var cursors;
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
//Création Map
map = game.add.tilemap('ClassicMap', 'tiles');
map.addTilesetImage('TileSet', 'tiles');
layer = map.createLayer('Calque de Tile 1');
layer.resizeWorld();
map.setCollision(2);
map.setCollision(1);
game.physics.arcade.collide(player, layer);
player = game.add.sprite(375,375,'pacman');
game.physics.enable(player);
player.body.collideWorldBounds = true;
//player.body.setSize(23, 23, 0, 0);
player.animations.add('left', [6, 5, 4], 10, true);
player.animations.add('right', [9, 8, 7], 10, true);
player.animations.add('down', [3, 2, 1], 10, true);
player.animations.add('up', [12, 11, 10], 10, true);
var m_un = new monster(game,200,300);
game.add.existing(m_un);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collide(player, layer);
//Get Tiles around player
var leftTile = map.getTileWorldXY(player.position.x -30, player.position.y, 25, 25, layer).index;
var rightTile = map.getTileWorldXY(player.position.x +30, player.position.y, 25, 25, layer).index;
var upTile = map.getTileWorldXY(player.position.x, player.position.y +30, 25, 25, layer).index;
var downTile = map.getTileWorldXY(player.position.x, player.position.y -30, 25, 25, layer).index;
var isWall;
if (cursors.left.isDown){
// Move to the left
isWall = (leftTile == 1);
if (isWall) {
console.log("it s a wall");
}
if (!isWall){
player.body.velocity.x = -150;
player.body.velocity.y = 0;
player.animations.play('left');
}
}
if (cursors.right.isDown){
// Move to the right
isWall = (rightTile == 1);
if (isWall) {
console.log("it s a wall");
}
if (!isWall){
player.body.velocity.x = 150;
player.body.velocity.y = 0;
player.animations.play('right');
}
}
if (cursors.up.isDown){
// Move up
isWall = (upTile == 1);
if (isWall) {
console.log("it s a wall");
}
if (!isWall){
player.body.velocity.y = -150;
player.body.velocity.x = 0;
player.animations.play('up');
}
}
if (cursors.down.isDown){
// Move down
isWall = (downTile == 1);
if (isWall) {
console.log("it s a wall");
}
if (!isWall){
player.body.velocity.y = 150;
player.body.velocity.x = 0;
player.animations.play('down');
}
}
}
monster = function(game,x,y){
Phaser.Sprite.call(this,game,x,y,'star');
}
monster.prototype = Object.create(Phaser.Sprite.prototype);
monster.prototype.constructor = monster;
monster.prototype.create = function(){
game.physics.enable(this);
game.physics.arcade.collide(this, layer);
}
monster.prototype.update = function(){
//console.log("hello");
}
//bat les couilles wallah déconne pas
|
JavaScript
| 0 |
@@ -1520,18 +1520,18 @@
tion.x -
-30
+25
, player
@@ -1621,18 +1621,18 @@
tion.x +
-30
+25
, player
@@ -1738,18 +1738,18 @@
tion.y +
-30
+25
, 25, 25
@@ -1838,18 +1838,18 @@
tion.y -
-30
+25
, 25, 25
@@ -1957,32 +1957,34 @@
= (leftTile == 1
+36
);%0A if (isW
@@ -2262,32 +2262,34 @@
(rightTile == 1
+36
);%0A if (isW
@@ -2549,32 +2549,34 @@
l = (upTile == 1
+36
);%0A if (isW
@@ -2819,16 +2819,16 @@
ve down%0A
-
is
@@ -2848,16 +2848,18 @@
ile == 1
+36
);%0A
|
e533dc26eef3f50395a770f72c9ac4fbf15d69c6
|
Remove now deprecated modulr.cache method.
|
assets/modulr.js
|
assets/modulr.js
|
// modulr (c) 2010 codespeaks sàrl
// Freely distributable under the terms of the MIT license.
// For details, see:
// http://github.com/codespeaks/modulr/blob/master/LICENSE
var modulr = (function(global) {
var _modules = {},
_moduleObjects = {},
_exports = {},
_oldDir = '',
_currentDir = '',
PREFIX = '__module__', // Prefix identifiers to avoid issues in IE.
RELATIVE_IDENTIFIER_PATTERN = /^\.\.?\//;
var _forEach = (function() {
var hasOwnProp = Object.prototype.hasOwnProperty,
DONT_ENUM_PROPERTIES = [
'constructor',
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable'
],
LENGTH = DONT_ENUM_PROPERTIES.length,
DONT_ENUM_BUG = true;
function _forEach(obj, callback) {
for(var prop in obj) {
if (hasOwnProp.call(obj, prop)) {
callback(prop, obj[prop]);
}
}
}
for(var prop in { toString: true }) {
DONT_ENUM_BUG = false
}
if (DONT_ENUM_BUG) {
return function(obj, callback) {
_forEach(obj, callback);
for (var i = 0; i < LENGTH; i++) {
var prop = DONT_ENUM_PROPERTIES[i];
if (hasOwnProp.call(obj, prop)) {
callback(prop, obj[prop]);
}
}
}
}
return _forEach;
})();
function log(str) {
if (global.console && console.log) { console.log(str); }
}
function require(identifier) {
var fn, modObj,
id = resolveIdentifier(identifier),
key = PREFIX + id,
expts = _exports[key];
log('Required module "' + identifier + '".');
if (!expts) {
_exports[key] = expts = {};
_moduleObjects[key] = modObj = { id: id };
if (!require.main) { require.main = modObj; }
fn = _modules[key];
_oldDir = _currentDir;
_currentDir = id.slice(0, id.lastIndexOf('/'));
try {
if (!fn) { throw 'Can\'t find module "' + identifier + '".'; }
if (typeof fn === 'string') {
fn = new Function('require', 'exports', 'module', fn);
}
fn(require, expts, modObj);
_currentDir = _oldDir;
} catch(e) {
_currentDir = _oldDir;
// We'd use a finally statement here if it wasn't for IE.
throw e;
}
}
return expts;
}
function resolveIdentifier(identifier) {
var parts, part, path;
if (!RELATIVE_IDENTIFIER_PATTERN.test(identifier)) {
return identifier;
}
parts = (_currentDir + '/' + identifier).split('/');
path = [];
for (var i = 0, length = parts.length; i < length; i++) {
part = parts[i];
switch (part) {
case '':
case '.':
continue;
case '..':
path.pop();
break;
default:
path.push(part);
}
}
return path.join('/');
}
function cache(id, fn) {
var key = PREFIX + id;
log('Cached module "' + id + '".');
_modules[key] = fn;
}
function define(moduleDescriptors) {
_forEach(moduleDescriptors, function(k, v) {
_modules[PREFIX + k] = v;
});
}
function ensure(identifiers, onAvailable, onMissing) {
for (var i = 0, length = identifiers.length; i < length; i++) {
var identifier = identifiers[i];
if (!_modules[PREFIX + identifier]) {
var error = new Error('Can\'t find module "' + identifier + '".')
if (typeof onMissing === 'function') {
onMissing(error);
return;
}
throw error;
}
}
onAvailable();
}
require.define = define;
require.ensure = ensure;
return {
require: require,
cache: cache
};
})(this);
|
JavaScript
| 0 |
@@ -3026,138 +3026,8 @@
%0A %0A
- function cache(id, fn) %7B%0A var key = PREFIX + id;%0A %0A log('Cached module %22' + id + '%22.');%0A _modules%5Bkey%5D = fn;%0A %7D%0A %0A
fu
@@ -3696,26 +3696,8 @@
uire
-,%0A cache: cache
%0A %7D
|
04ca801e967fa2f6d258d3341090a39ca26c3826
|
remove logger function
|
gulpfile.js
|
gulpfile.js
|
/*global require*/
var gulp = require('gulp');
var args = require('yargs').argv;
var config = require('./gulp.config')();
var del = require('del');
var $ = require('gulp-load-plugins')({lazy: true});
//var jshint = require('gulp-jshint');
//var jscs = require('gulp-jscs');
//var util = require('gulp-util');
//var gulpprint = require('gulp-print');
//var gulpif = require('gulp-if');
function log(msg) {
'use strict';
var item;
if (typeof (msg) === 'object') {
for (item in msg) {
if (msg.hasOwnProperty(item)) {
$.util.log($.util.colors.blue(msg[item]));
}
}
} else {
$.util.log($.util.colors.green(msg));
}
}
//gulp vet --verbose
gulp.task('vet', function () {
'use strict';
log('Analyzing source with JSHint and JSCS');
return gulp
.src(config.alljs)
.pipe($.if(args.verbose, $.print()))
.pipe($.jscs())
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
.pipe($.jshint.reporter('fail'));
});
function errorLogger(error) {
log('Start of Error');
log(error);
log('End of Error');
this.emit('end');
}
gulp.task('styles', ['clean-styles'], function () {
'use strict';
log('Compile Less --->CSS');
return gulp
.src(config.less) //TODO
.pipe($.plumber())
.pipe($.less())
.pipe($.autoprefixer({browsers: ['last 2 version', '> 5%']}))
.pipe(gulp.dest(config.temp));
});
function clean(path, done) {
'use strict';
log('Cleaning: ' + $.util.colors.blue(path));
del(path).then(done());
}
gulp.task('clean-styles', function (done) {
'use strict';
log('Clean files');
var files = config.temp + '**/*.css';
clean(files, done);
});
gulp.task('less-watcher', function () {
'use strict';
gulp.watch([config.less], ['styles']);
});
|
JavaScript
| 0.000018 |
@@ -1073,132 +1073,8 @@
);%0A%0A
-function errorLogger(error) %7B%0A log('Start of Error');%0A log(error);%0A log('End of Error');%0A this.emit('end');%0A%7D%0A%0A%0A
gulp
|
7de88604790efd932ca321eb313e40fcab4bc556
|
remove safari from test suite
|
test/e2e.travis.conf.js
|
test/e2e.travis.conf.js
|
/* global exports */
// An example configuration file.
exports.config = {
specs: ['e2e/**/*Spec.js'],
baseUrl: 'http://localhost:8000',
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
multiCapabilities: [{
browserName: 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
}, {
browserName: 'firefox',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
}, {
browserName: 'internet explorer',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
}, {
browserName: 'safari',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER
}],
getPageTimeout: 2000
};
|
JavaScript
| 0 |
@@ -506,32 +506,35 @@
VIS_JOB_NUMBER%0A
+ //
%7D, %7B%0A browse
@@ -518,32 +518,35 @@
ER%0A // %7D, %7B%0A
+ //
browserName: 's
@@ -552,24 +552,27 @@
safari',%0A
+ //
'tunnel-ide
@@ -619,32 +619,8 @@
%7D%5D
-,%0A getPageTimeout: 2000
%0A%7D;%0A
|
1f447ee30c61301f28f75fad027572011db59213
|
debug logs for heroku
|
public/javascripts/main.js
|
public/javascripts/main.js
|
//Start Parallax Animation
$('.parallax').parallax();
//Declare JQuery Selectors
var $submitBtn = $(".submit-btn");
var $nextBtn = $(".next-btn");
var $downExplainBtn = $("#down-explain");
var $downEmotchaBtn = $("#down-emotcha");
var $loginBtn = $(".login-btn");
var $exampleImg = $("#example-img");
//Initialize Video Variable
var video = document.querySelector('video');
var capturing = false;
var finished = false;
var firstFinish = true;
var updateInterval;
//Initialize Canvas Elements
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 450;
canvas.height = 450;
var image = "happy.jpg"
//Initialize Emotional Varialbes
var exampleEmotions;
var liveEmotions;
var metric;
//Get Initial Example
getExample();
//On Click Functions
$submitBtn.click(function(){
//Logic for play pause restart button on live card
if(finished){
getExample();
$submitBtn.children().replaceWith("<i class='mdi-av-pause'></i>");
$submitBtn.toggleClass('red', true);
$submitBtn.toggleClass('green', false);
$loginBtn.toggleClass('disabled', true);
$('.how-to').toggleClass('hide', false);
finished = false
} else if(capturing){
pauseCapture();
} else {
captureVideo();
}
})
$nextBtn.click(function() {
//Logic for new example button on example card
getExample();
})
$downExplainBtn.click(function() {
//First movement button
console.log("down to explain")
$.smoothScroll({scrollElemnt: $('.explaination-container'), scrollTarget: '#explanation-target', offset: -$('.explanation-container').height(), speed: 1000});
})
$downEmotchaBtn.click(function() {
//second movement button
$.smoothScroll({scrollElemnt: $('.emotcha-container'), scrollTarget: '#emotcha-target', offset: -75, speed: 1000, afterScroll: function(){
setTimeout(captureVideo, 200);
capturing = true;
}});
})
$loginBtn.click(function(){
//Sets alerts for login buttons
if(!$loginBtn.hasClass('disabled')){
alert('You could now sucessfully login if this was a real site!');
} else {
alert('You need to match emotional profiles with the picture on the left');
}
});
function getExample() {
//fetch picture and emotional profile from server
console.log("button pushed")
$.get('/image', {image:image})
.done(function (data, status){
exampleEmotions = data.emotions;
image = data.file
$exampleImg.attr('src', 'images/'+data.file);
$('#ex-angry').css('width', (exampleEmotions.Angry*100)+'%');
$('#ex-sad').css('width', (exampleEmotions.Sad*100)+'%');
$('#ex-neutral').css('width', (exampleEmotions.Neutral*100)+'%');
$('#ex-surprise').css('width', (exampleEmotions.Surprise*100)+'%');
$('#ex-fear').css('width', (exampleEmotions.Fear*100)+'%');
$('#ex-happy').css('width', (exampleEmotions.Happy*100)+'%');
})
.error(function (data, status){
console.log(status);
})
}
function pauseCapture(){
//Grab image from video and put it on canvas, pause video
capturing = false;
ctx.drawImage(video, 0, 0, 600, 450);
$(video).replaceWith(canvas);
clearInterval(updateInterval);
$('.submit-btn').children().replaceWith("<i class='mdi-av-play-arrow'></i>");
var dataURI = canvas.toDataURL('image/jpg');
postImage(dataURI);
}
function update(){
//Grab image from video, find face, and send to server every second
ctx.drawImage(video, 0, 0, 600, 450);
var dataURI = canvas.toDataURL('image/jpg');
postImage(dataURI);
}
function postImage(dataURI){
//send face to server and respond by changing bars
$.post("/image", {data: dataURI})
.done(function (data, status) {
if (data['status'] === "found"){
console.log("face!")
data = data['data']
liveEmotions = data;
$('#lv-angry').css('width', (data.Angry*100)+'%');
$('#lv-sad').css('width', (data.Sad*100)+'%');
$('#lv-neutral').css('width', (data.Neutral*100)+'%');
$('#lv-surprise').css('width', (data.Surprise*100)+'%');
$('#lv-fear').css('width', (data.Fear*100)+'%');
$('#lv-happy').css('width', (data.Happy*100)+'%');
//Measure if emotions close enough to unlock system
diffs =[Math.abs(liveEmotions.Angry - exampleEmotions.Angry),
Math.abs(liveEmotions.Sad - exampleEmotions.Sad),
Math.abs(liveEmotions.Neutral - exampleEmotions.Neutral),
Math.abs(liveEmotions.Surprise - exampleEmotions.Surprise),
Math.abs(liveEmotions.Fear - exampleEmotions.Fear),
Math.abs(liveEmotions.Happy - exampleEmotions.Happy)]
sum = 0;
for(i=0; i<diffs.length; i++){
sum+= diffs[i];
}
metric = 2 - sum;
if(metric>1.5){
$submitBtn.children('i').replaceWith("<i class='mdi-content-undo'></i>");
$submitBtn.toggleClass('red', false);
$submitBtn.toggleClass('green', true);
$loginBtn.toggleClass('disabled', false);
$('.how-to').toggleClass('hide', true);
finished = true;
if(firstFinish){
alert("You've sucessfuly matched emotional profiles and unlocked the login button, tap the green arrow on your portrait to try again or the login button to complete the demo login");
firstFinish = false;
}
}
}
})
.error(function (data, status){
console.log(status);
});
}
function captureVideo() {
//Start webcam video playing
navigator.getUserMedia = navigator.getUserMedia ||navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
}, function (err){
console.log("ERROR!", err);
});
}
if(!capturing){
$('canvas').replaceWith(video)
};
$('.submit-btn').children().replaceWith("<i class='mdi-av-pause'></i>");
capturing = true;
updateInterval = setInterval(update, 500);
}
|
JavaScript
| 0 |
@@ -3588,34 +3588,39 @@
ataURL('image/jp
+e
g'
+, .5
);%0A postImage
|
017c6f7b1b3434a1c74d9db05241419acde09db8
|
fix (build)
|
gulpfile.js
|
gulpfile.js
|
'use strict';
// generated on 2017-03-03 using generator-gulp-bootstrap 0.0.4
var gulp = require('gulp');
var browserSync = require('browser-sync');
var pump = require('pump');
var reload = browserSync.reload;
var gutil = require('gulp-util');
var sassJson = require('gulp-sass-json');
// load plugins
var $ = require('gulp-load-plugins')();
gulp.task('styles', ['sassvars'], function () {
return gulp.src('app/styles/main.scss')
.pipe($.sass({ errLogToConsole: true }))
.pipe($.autoprefixer('last 1 version'))
.pipe(gulp.dest('app/styles'))
.pipe(reload({ stream: true }))
.pipe($.size());
});
gulp.task('sassvars', function () {
return gulp.src('app/styles/base/_variables.scss')
.pipe(sassJson())
.pipe(gulp.dest('app/styles'));
});
gulp.task('scripts', function () {
gulp.src('app/scripts/main/**/*.html')
.pipe($.angularTemplatecache('templates.js', {
module: 'vbr-style-guide'
}))
.pipe(gulp.dest('app/scripts/main'));
return gulp.src(['app/scripts/main/**/*.module.js', 'app/scripts/main/**/*.js'])
.pipe($.jshint())
.pipe($.ngAnnotate({
remove: true,
add: true,
single_quotes: true
}))
.pipe($.uglify())
.pipe($.concat('main.js'))
.pipe(gulp.dest('app/scripts'))
.pipe($.jshint.reporter(require('jshint-stylish')))
.pipe($.size());
});
gulp.task('html', ['styles', 'scripts'], function () {
var jsFilter = $.filter('**/*.js');
var cssFilter = $.filter('**/*.css');
return gulp.src('app/*.html')
.pipe($.useref.assets())
.pipe(jsFilter)
.pipe($.uglify())
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe($.csso())
.pipe(cssFilter.restore())
.pipe($.useref.restore())
.pipe($.useref())
.pipe(gulp.dest('styleguide'))
.pipe($.size());
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('styleguide/images'))
.pipe(reload({ stream: true, once: true }))
.pipe($.size());
});
gulp.task('fonts', function () {
var streamqueue = require('streamqueue');
return streamqueue({ objectMode: true },
$.bowerFiles(),
gulp.src('app/fonts/**/*')
)
.pipe($.filter('**/*.{eot,svg,ttf,woff}'))
.pipe($.flatten())
.pipe(gulp.dest('styleguide/fonts'))
.pipe($.size());
});
gulp.task('clean', function () {
return gulp.src(['app/styles/main.css', 'app/styles/variables.json', 'styleguide', 'dist'], { read: false }).pipe($.clean());
});
gulp.task('serve', ['aigis'], function () {
browserSync.init(null, {
server: {
baseDir: 'styleguide',
directory: true
},
debugInfo: false,
open: false
}, function (err, bs) {
require('opn')(bs.options.url);
console.log('Started connect web server on ' + bs.options.url);
});
});
// inject bower components
gulp.task('wiredep', function () {
var wiredep = require('wiredep').stream;
gulp.src('app/styles/*.scss')
.pipe(wiredep({
directory: 'bower_components'
}))
.pipe(gulp.dest('app/styles'));
gulp.src('template_ejs/scripts.ejs')
.pipe(wiredep({
directory: 'bower_components',
fileTypes: {
html: {
replace: {
js: '<script src="<%- root%>{{filePath}}"></script>'
}
}
}
}))
.pipe(gulp.dest('template_ejs'));
});
gulp.task('watch', ['serve'], function () {
// watch for changes
gulp.watch(['styleguide/*.html'], reload);
gulp.watch(['aigis_config.yml', 'template_ejs/**/*', 'aigis_assets/**/*'], ['aigis', 'delayed-reload']);
gulp.watch('app/styles/**/*.scss', ['styles', 'aigis']);
gulp.watch(['app/scripts/main/**/*.js', 'app/scripts/**/*.html'], ['scripts', 'aigis']);
gulp.watch('app/images/**/*', ['images']);
gulp.watch('html/**/*', ['aigis']);
gulp.watch('bower.json', ['wiredep', 'aigis']);
});
gulp.task("aigis", ['styles', 'scripts'], function () {
gulp.src("./aigis_config.yml")
.pipe($.aigis());
});
gulp.task('delayed-reload', function () {
setTimeout(reload, 5000);
});
gulp.task('buildScripts',function(cb){
pump([
gulp.src(['app/scripts/main/*.module.js','app/scripts/main/*.directive.js','app/scripts/main/*.controller.js','app/scripts/main/templates.js','app/scripts/main/*.constants.js','!app/scripts/**/*.spec.js','app/scripts/main/components/**/*.js']),
$.ngAnnotate(),
$.uglify(),
$.concat('index.min.js'),
gulp.dest('dist/scripts/')
],
cb
);
});
gulp.task('buildStyles',function(cb){
pump([
gulp.src('app/styles/**/*.scss'),
$.size(),
gulp.dest('dist/scss/')
],
cb);
});
gulp.task('build', ['clean','buildScripts','buildStyles'], function () {
return true;
});
gulp.task('default', ['clean'], function () {
gulp.start('watch');
});
|
JavaScript
| 0 |
@@ -4795,24 +4795,25 @@
/*.spec.js',
+
'app/scripts
|
c24c32b1559d8fc1b85a46b4accdf792d77df2b9
|
remove logs
|
app/js/pages/FAQPage.js
|
app/js/pages/FAQPage.js
|
'use strict'
import { Component } from 'react'
import DocumentTitle from 'react-document-title'
import marked from 'marked'
import docs from '../../docs.json'
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
})
class FAQpage extends Component {
constructor (props) {
super(props)
this.state = {
questions: null
}
this.setQuestions = this.setQuestions.bind(this)
}
componentWillMount() {
this.setQuestions()
}
setQuestions() {
let questions = []
console.log(docs);
let markdown = docs['faq'].markdown
let markdownParts = markdown.split(/### (.*)/g)
markdownParts.splice(0, 1)
for (let i = 0; i < markdownParts.length; i += 2) {
questions.push({
question: markdownParts[i],
answer: marked(markdownParts[i+1]),
})
}
this.setState({
questions
})
}
render () {
const { questions } = this.state
return(
<DocumentTitle title="Blockstack - FAQ">
<div>
<section className="container-fluid spacing-container">
<div className="container-fluid col-centered">
<div className="container m-b-1">
<div>
<h1>Frequently Asked Questions</h1>
</div>
{ questions.map((faq, index) => {
return (
<div key={ index }>
<h4>{ faq.question }</h4>
<div dangerouslySetInnerHTML={{ __html: faq.answer }}>
</div>
</div>
)
}) }
</div>
</div>
</section>
</div>
</DocumentTitle>
);
}
}
export default FAQpage
|
JavaScript
| 0.000001 |
@@ -646,31 +646,8 @@
%5B%5D%0A
- console.log(docs);%0A
|
80778e82ce608e4d7b58ff6e133e30f5dc91b29b
|
Fix default quality value
|
background.js
|
background.js
|
;
"use strict";
var duk = (function() {
var streams = { "40" : "http://radio.4duk.ru/4duk40.mp3"
, "64" : "http://radio.4duk.ru/4duk64.mp3"
, "128" : "http://radio.4duk.ru/4duk128.mp3"
};
var audio = new Audio(); var playing = false;
function isPlaying() { return playing; }
function setPlaying(p) { playing = p; return playing; }
function getStreamQuality() { return localStorage[ "stream_quality" ] || 128; }
function setStreamQuality(stream_quality) { localStorage[ "stream_quality" ] = stream_quality; }
function startPlaying() {
audio.src = streams[ getStreamQuality() ];
audio.load();
audio.play();
setPlaying(true);
console.log(arguments.callee.name, audio.src);
}
function stopPlaying() {
audio.pause();
audio.currentTime = 0;
audio.src = "";
setPlaying(false);
console.log(arguments.callee.name);
}
function shiftQuality() {
var stream_quality = { "40" : "64"
, "64" : "128"
, "128" : "40"
}[ getStreamQuality() ];
var was_playing = isPlaying();
stopPlaying();
setStreamQuality(stream_quality);
if (was_playing) { startPlaying(); }
console.log(arguments.callee.name);
}
chrome.commands.onCommand.addListener(function(command) {
console.log("chrome commands' listener: ", command);
switch (command) {
case "toogle-playing": {
if (isPlaying()) {
stopPlaying();
} else {
startPlaying();
}
}
}
});
return { startPlaying : startPlaying
, stopPlaying : stopPlaying
, shiftQuality : shiftQuality
, isPlaying : isPlaying
, getStreamQuality : getStreamQuality
};
}());
function getDuk() { return duk; };
|
JavaScript
| 0.000025 |
@@ -484,19 +484,21 @@
y%22 %5D %7C%7C
+%22
128
+%22
; %7D%0A
|
43e54e98c7ccd52b6e6270801a6eb146585897a5
|
correlate black text to light bg, etc
|
assets/script.js
|
assets/script.js
|
$( document ).ready(function() {
$(document).click(function() {
// generate random hue, saturation, lightness for page background color
var hueValue = Math.floor(Math.random()*360);
var saturationValue = Math.floor(Math.random()*100);
var lightnessValue = Math.floor(Math.random()*100);
// splice values into formatted css background-color value, using concatenation operator
var cssValue = 'hsl(' + hueValue + ', ' + saturationValue + '%, ' + lightnessValue + '%)';
// change the css rule for html element to new background color
$('html, body').css('background-color', cssValue);
// if new background color is light, use black text
if (lightnessValue<50) {
$('*').css('color', 'black');
$('a').css('color', 'black');
// otherwise, use white text
} else {
$('*').css('color', 'white');
$('a').css('color', 'white');
}
});
});
|
JavaScript
| 0.998608 |
@@ -634,24 +634,23 @@
is
-light
+dark
, use
-black
+white
tex
@@ -698,29 +698,29 @@
s('color', '
-black
+white
');%0A%09%09%09$('a'
@@ -739,13 +739,13 @@
', '
-black
+white
');%0A
@@ -802,37 +802,37 @@
).css('color', '
-white
+black
');%0A%09%09%09$('a').cs
@@ -839,29 +839,29 @@
s('color', '
-white
+black
');%0A%09%09%7D%0A%0A%09%7D)
|
49d7442bfed695c322bb70e21f32287273c16b11
|
Update test reporter.
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
qunit = require('./index'),
jscs = require('gulp-jscs');
var paths = {
scripts: ['./*.js', './test/*.js', '!./lib', '!./gulpfile.js']
};
gulp.task('lint', function() {
return gulp.src(paths.scripts)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('jscs', function () {
return gulp.src(paths.scripts)
.pipe(jscs());
});
gulp.task('test', function() {
return gulp.src('./test/*.js')
.pipe(mocha({reporter: 'dot'}));
});
gulp.task('qunit', function() {
qunit('./test/fixtures/passing.html');
});
gulp.task('qunit-verbose', function() {
qunit('./test/fixtures/passing.html', { 'verbose': true });
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['lint', 'jscs', 'test']);
});
gulp.task('default', ['lint', 'jscs', 'test', 'watch']);
|
JavaScript
| 0 |
@@ -594,11 +594,12 @@
r: '
-dot
+spec
'%7D))
|
d0c99b1cdbb0af08ce035ba6b2f3f1f6d320ad17
|
make modal test more stable in chrome (all e2e tests pass)
|
test/e2e/specs/modal.js
|
test/e2e/specs/modal.js
|
module.exports = {
'modal': function (browser) {
browser
.url('http://localhost:8080/examples/modal/')
.waitForElementVisible('#app', 1000)
.assert.elementNotPresent('.modal-mask')
.click('#show-modal')
.assert.elementPresent('.modal-mask')
.assert.elementPresent('.modal-wrapper')
.assert.elementPresent('.modal-container')
.assert.cssClassPresent('.modal-mask', 'modal-enter-active')
.waitFor(350)
.assert.cssClassNotPresent('.modal-mask', 'modal-enter-active')
.assert.containsText('.modal-header h3', 'custom header')
.assert.containsText('.modal-body', 'default body')
.assert.containsText('.modal-footer', 'default footer')
.click('.modal-default-button')
// should have transition
.assert.elementPresent('.modal-mask')
.assert.cssClassPresent('.modal-mask', 'modal-leave-active')
.waitFor(350)
.assert.elementNotPresent('.modal-mask')
.end()
}
}
|
JavaScript
| 0 |
@@ -439,33 +439,33 @@
.waitFor(3
-5
+0
0)%0A .assert
@@ -811,32 +811,51 @@
('.modal-mask')%0A
+ .waitFor(50)%0A
.assert.cs
@@ -921,17 +921,17 @@
aitFor(3
-5
+0
0)%0A
|
5b58cba753ab9a97e3a10390ab1084f79b100c1b
|
Remove unused $q dependency
|
app/js/service.login.js
|
app/js/service.login.js
|
angular.module('myApp.service.login', ['firebase', 'myApp.service.firebase'])
.factory('loginService', ['$rootScope', '$firebaseSimpleLogin', 'firebaseRef', 'profileCreator', '$timeout', '$q',
function($rootScope, $firebaseSimpleLogin, firebaseRef, profileCreator, $timeout, $q) {
var auth = null;
return {
init: function() {
return auth = $firebaseSimpleLogin(firebaseRef());
},
/**
* @param {string} email
* @param {string} pass
* @param {Function} [callback]
* @returns {*}
*/
login: function(email, pass, callback) {
assertAuth();
auth.$login('password', {
email: email,
password: pass,
rememberMe: true
}).then(function(user) {
if( callback ) {
//todo-bug https://github.com/firebase/angularFire/issues/199
$timeout(function() {
callback(null, user);
});
}
}, callback);
},
logout: function() {
assertAuth();
auth.$logout();
},
changePassword: function(opts) {
assertAuth();
var cb = opts.callback || function() {};
if( !opts.oldpass || !opts.newpass ) {
$timeout(function(){ cb('Please enter a password'); });
}
else if( opts.newpass !== opts.confirm ) {
$timeout(function() { cb('Passwords do not match'); });
}
else {
auth.$changePassword(opts.email, opts.oldpass, opts.newpass).then(function() { cb && cb(null) }, cb);
}
},
createAccount: function(email, pass, callback) {
assertAuth();
auth.$createUser(email, pass).then(function(user) { callback && callback(null, user) }, callback);
},
createProfile: profileCreator
};
function assertAuth() {
if( auth === null ) { throw new Error('Must call loginService.init() before using its methods'); }
}
}])
.factory('profileCreator', ['firebaseRef', '$timeout', function(firebaseRef, $timeout) {
return function(id, email, callback) {
firebaseRef('users/'+id).set({email: email, name: firstPartOfEmail(email)}, function(err) {
//err && console.error(err);
if( callback ) {
$timeout(function() {
callback(err);
})
}
});
function firstPartOfEmail(email) {
return ucfirst(email.substr(0, email.indexOf('@'))||'');
}
function ucfirst (str) {
// credits: http://kevin.vanzonneveld.net
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}
}]);
|
JavaScript
| 0.000001 |
@@ -188,14 +188,8 @@
ut',
- '$q',
%0A
@@ -275,12 +275,8 @@
eout
-, $q
) %7B%0A
@@ -939,190 +939,27 @@
-//todo-bug https://github.com/firebase/angularFire/issues/199%0A $timeout(function() %7B%0A callback(null, user);%0A %7D
+callback(null, user
);%0A
|
0b2c710996cf5234f5200d25ac7de382224f5710
|
Update neuron.js
|
neuron.js
|
neuron.js
|
/**
* Instantiating a neuron can be initialized empty
* var node = new Neuron();
* or by passing JSON obj with
* var obj = {
* input: [1], // an array of initial inputs
* weights: [w], // an array of initial weights
* bias: 1, // pass the starting initial bias integer
* activation: "" //pass string of the name of the activation function you wish to use
* };
* var node = new Neuron(obj);
**/
// A single neuron instance
var Neuron = function(conditions){
"use strict";
var w = (typeof conditions === "undefined") ? NeuralMathLib.randomGauss() : 1;
var obj = {
input: [1], //change this to reflect initial input
weights: [w],
bias: 1,
activation: "logsig"
};
this.obj = conditions || obj;
};
Neuron.prototype.feedForward = function(refined){
"use strict";
if(typeof refined !== "undefined"){
//refined contains the new bias and weights
this.obj.input = refined.input;
this.obj.weights = refined.weights;
this.obj.bias = refined.bias;
}
var inputsMAT = math.matrix(this.obj.input);
var weightsMAT = math.matrix(this.obj.weights);
var sumMAT = math.multiply(inputsMAT, weightsMAT);//Σ(wx)
var totalMAT = math.add(sumMAT, math.matrix([this.obj.bias]));//sumMAT + b
var result = NeuralMathLib.activations(this.obj.activation, totalMAT); //activation function
return result;
//TODO: creates 1 output and sets the new weights and bias
};
|
JavaScript
| 0.999534 |
@@ -1344,21 +1344,8 @@
AT,
-math.matrix(%5B
this
@@ -1357,10 +1357,8 @@
bias
-%5D)
);//
@@ -1549,8 +1549,9 @@
bias%0A%7D;
+%0A
|
fc50679e09003906e1ffe2ed04ff0a3b02b63089
|
Use NuvolaPlayer coding style
|
integrate.js
|
integrate.js
|
/*
* Copyright 2015 SkyghiS <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function(Nuvola)
{
"use strict";
var ADDRESS = "app.address";
var ADDRESS_DEFAULT = "http://localhost:32400/web";
// Create media player component
var player = Nuvola.$object(Nuvola.MediaPlayer);
// Handy aliases
var PlaybackState = Nuvola.PlaybackState;
var PlayerAction = Nuvola.PlayerAction;
// Create new WebApp prototype
var WebApp = Nuvola.$WebApp();
WebApp._onInitAppRunner = function(emitter)
{
Nuvola.WebApp._onInitAppRunner.call(this, emitter);
Nuvola.config.setDefault(ADDRESS, ADDRESS_DEFAULT);
Nuvola.core.connect("InitializationForm", this);
Nuvola.core.connect("PreferencesForm", this);
};
WebApp._onPreferencesForm = function(emitter, values, entries)
{
this.appendPreferences(values, entries);
};
WebApp._onInitializationForm = function(emitter, values, entries)
{
if (!Nuvola.config.hasKey(ADDRESS))
this.appendPreferences(values, entries);
};
WebApp._onHomePageRequest = function(emitter, result)
{
result.url = Nuvola.config.get(ADDRESS);
};
WebApp.appendPreferences = function(values, entries)
{
values[ADDRESS] = Nuvola.config.get(ADDRESS);
entries.push(["header", "Plex"]);
entries.push(["label", "Address of your Plex Server"]);
entries.push(["string", ADDRESS, "Address"]);
};
// Initialization routines
WebApp._onInitWebWorker = function(emitter)
{
Nuvola.WebApp._onInitWebWorker.call(this, emitter);
var state = document.readyState;
if (state === "interactive" || state === "complete")
this._onPageReady();
else
document.addEventListener("DOMContentLoaded", this._onPageReady.bind(this));
};
// Page is ready for magic
WebApp._onPageReady = function()
{
// Connect handler for signal ActionActivated
Nuvola.actions.connect("ActionActivated", this);
// Start update routine
this.update();
};
WebApp._isAvailable = function (el)
{
return el && el.className && !/(:?\s|^)(:?disabled|hidden)(:?\s|$)/.test(el.className);
};
WebApp._getAttribute = function (el, attribute)
{
if (el && el.attributes && el.attributes[attribute])
return el.attributes[attribute].value;
return null;
};
// Extract data from the web page
WebApp.update = function()
{
var playerElement = document.querySelector(".player.music");
var playElement, pauseElement, previousElement, nextElement, shuffleElement;
if (playerElement)
{
playElement = playerElement.querySelector(".play-btn");
pauseElement = playerElement.querySelector(".pause-btn");
previousElement = playerElement.querySelector(".previous-btn");
nextElement = playerElement.querySelector(".next-btn");
} else {
shuffleElement = document.querySelector(".action-bar .play-shuffled-btn");
}
// Playback state
var state = PlaybackState.UNKNOWN;
if (playerElement)
{
if (playElement && !this._isAvailable(playElement))
state = PlaybackState.PLAYING;
else if (pauseElement && !this._isAvailable(pauseElement))
state = PlaybackState.PAUSED;
}
player.setPlaybackState(state);
// Track informations
var posterElement = playerElement ? playerElement.querySelector('.media-poster') : null;
player.setTrack({
title: this._getAttribute(posterElement, 'data-title'),
artist: this._getAttribute(posterElement, 'data-grandparent-title'),
album: this._getAttribute(posterElement, 'data-parent-title'),
artLocation: this._getAttribute(posterElement, 'data-image-url')
});
// Player actions
player.setCanPlay(this._isAvailable(playElement) || this._isAvailable(shuffleElement));
player.setCanPause(this._isAvailable(pauseElement));
player.setCanGoPrev(this._isAvailable(previousElement));
player.setCanGoNext(this._isAvailable(nextElement));
// Schedule the next update
setTimeout(this.update.bind(this), 500);
};
// Handler of playback actions
WebApp._onActionActivated = function(emitter, name, param)
{
var playerElement = document.querySelector(".player.music");
var playElement, pauseElement, previousElement, nextElement;
if (playerElement)
{
playElement = playerElement.querySelector(".play-btn");
pauseElement = playerElement.querySelector(".pause-btn");
previousElement = playerElement.querySelector(".previous-btn");
nextElement = playerElement.querySelector(".next-btn");
}
switch (name)
{
case PlayerAction.TOGGLE_PLAY:
if (playerElement) {
if (this._isAvailable(playElement))
Nuvola.clickOnElement(playElement);
else
Nuvola.clickOnElement(pauseElement);
} else {
var shuffleElement = document.querySelector(".action-bar .play-shuffled-btn");
if (shuffleElement) {
Nuvola.clickOnElement(shuffleElement);
}
}
break;
case PlayerAction.PLAY:
Nuvola.clickOnElement(playElement);
break;
case PlayerAction.PAUSE:
Nuvola.clickOnElement(pauseElement);
break;
case PlayerAction.STOP:
Nuvola.clickOnElement(playerElement.querySelector(".stop-btn"));
break;
case PlayerAction.PREV_SONG:
Nuvola.clickOnElement(previousElement);
break;
case PlayerAction.NEXT_SONG:
Nuvola.clickOnElement(nextElement);
break;
}
};
WebApp.start();
})(this); // function(Nuvola)
|
JavaScript
| 0 |
@@ -3974,29 +3974,37 @@
btn%22);%0A %7D
+%0A
else
+%0A
%7B%0A s
@@ -5857,32 +5857,44 @@
(playerElement)
+%0A
%7B%0A
@@ -6079,21 +6079,45 @@
%7D
- else
+%0A else%0A
%7B%0A
@@ -6241,16 +6241,32 @@
Element)
+%0A
%7B%0A
|
6cccd1a070e88f5b6e0e9157b65a5cdf5f1e83df
|
Set MAX_DESCRIPTION_SIZE as constant
|
assets/search.js
|
assets/search.js
|
require([
'gitbook',
'jquery'
], function(gitbook, $) {
// DOM Elements
var $body = $('body');
var $bookSearchResults;
var $searchInput;
var $searchList;
var $searchTitle;
var $searchResultsCount;
var $searchQuery;
var MAX_RESULTS = 15;
// Throttle search
function throttle(fn, wait) {
var timeout;
return function() {
var ctx = this, args = arguments;
if (!timeout) {
timeout = setTimeout(function() {
timeout = null;
fn.apply(ctx, args);
}, wait);
}
};
}
// Return true if search is open
function isSearchOpen() {
return $body.hasClass('with-search');
}
// Toggle the search
function toggleSearch(_state) {
if (isSearchOpen() === _state) return;
$body.toggleClass('with-search', _state);
// If search bar is open: focus input
if (isSearchOpen()) {
gitbook.sidebar.toggle(true);
$searchInput.focus();
} else {
$searchInput.blur();
$searchInput.val('');
$bookSearchResults.removeClass('open');
}
}
function displayResults(res) {
$bookSearchResults.addClass('open');
var noResults = res.count == 0;
$bookSearchResults.toggleClass('no-results', noResults);
// Clear old results
$searchList.empty();
// Display title for research
$searchResultsCount.text(res.count);
$searchQuery.text(res.query);
// Create an <li> element for each result
res.results.forEach(function(res) {
var $li = $('<li>', {
'class': 'search-results-item'
});
var $title = $('<h3>');
var $link = $('<a>', {
'href': gitbook.state.root+res.url,
'text': res.title
});
var content = res.body;
if (content.length > 500) {
content = content.slice(0, 500)+'...';
}
var $content = $('<p>').html(content);
$link.appendTo($title);
$title.appendTo($li);
$content.appendTo($li);
$li.appendTo($searchList);
});
}
function bindSearch() {
// Bind DOM
$searchInput = $('#book-search-input');
$bookSearchResults = $('#book-search-results');
$searchList = $bookSearchResults.find('.search-results-list');
$searchTitle = $bookSearchResults.find('.search-results-title');
$searchResultsCount = $searchTitle.find('.search-results-count');
$searchQuery = $searchTitle.find('.search-query');
// Type in search bar
$(document).on('keyup', '#book-search-input', function(e) {
var key = (e.keyCode ? e.keyCode : e.which);
var q = $(this).val();
if (key == 27) {
e.preventDefault();
toggleSearch(false);
return;
}
if (q.length == 0) {
$bookSearchResults.removeClass('open');
}
else {
throttle(gitbook.search.query(q, 0, MAX_RESULTS)
.then(function(results) {
displayResults(results);
}), 1500);
}
});
// Close search
toggleSearch(false);
}
gitbook.events.bind('start', function() {
// Create the toggle search button
if (gitbook.toolbar) {
gitbook.toolbar.createButton({
icon: 'fa fa-search',
label: 'Search',
position: 'left',
onClick: toggleSearch
});
}
// Bind keyboard to toggle search
if (gitbook.keyboard) {
gitbook.keyboard.bind(['f'], toggleSearch);
}
});
gitbook.events.bind('page.change', bindSearch);
});
|
JavaScript
| 0.999547 |
@@ -53,24 +53,87 @@
tbook, $) %7B%0A
+ var MAX_RESULTS = 15;%0A var MAX_DESCRIPTION_SIZE = 500;%0A%0A
// DOM E
@@ -316,35 +316,8 @@
y;%0A%0A
- var MAX_RESULTS = 15;%0A%0A
@@ -2032,16 +2032,23 @@
res.body
+.trim()
;%0A
@@ -2074,19 +2074,36 @@
ength %3E
-500
+MAX_DESCRIPTION_SIZE
) %7B%0A
@@ -2141,19 +2141,43 @@
lice(0,
-500
+MAX_DESCRIPTION_SIZE).trim(
)+'...';
|
d2c06a78dfb8ff8ca8b922cdd6bf5e1332a18ef9
|
Change implementation for classify method
|
jssnips/math_numbers/perfect-numbers/perfect-numbers.js
|
jssnips/math_numbers/perfect-numbers/perfect-numbers.js
|
class PerfectNumbers{
/**
* Classifies numbers to either perfect, abundant or deficient base on their
aliquot sum
@param {Number} number to classify
@returns {String} whether the number is perfect, abundant or deficient
*/
classify(number){
// classify perfect numbers
//classify abundant numbers
// classify deficient numbers
}
/**
Gets the aliquot sum
@param {Number} num the number to derive the aliquot sum
@returns {Number} the sum of the factors of the provided number
*/
getAliquotSum(num){
// ensures a whole number, total = 1, 1 will be part of the solution
var half = Math.floor(num / 2), total = 1, i, j;
// determine the increment value for the loop and starting point
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for(i; i <= half;i += j){
num % i === 0 ? total += i: false;
}
// include the original number
total += num;
return total;
}
}
module.exports = PerfectNumbers;
|
JavaScript
| 0 |
@@ -257,43 +257,106 @@
-// classify perfect numbers%0A
+if(number %3C= 0)%7B%0A return %22Classification is only possible for natural numbers.%22%0A %7D
%0A //
+
clas
@@ -364,33 +364,233 @@
ify
-abundant numbers%0A
+deficient numbers%0A if(this.getAliquotSum(number) %3C number %7C%7C number === 1)%7B%0A return %22deficient%22;%0A %7D%0A // classify perfect numbers%0A if(this.getAliquotSum(number) == number)%7B%0A return %22perfect%22;%0A %7D
%0A //
-
clas
@@ -594,33 +594,109 @@
lassify
-deficient numbers
+abundant numbers%0A if(this.getAliquotSum(number) %3E number)%7B%0A return %22abundant%22;%0A %7D%0A
%0A %7D%0A%0A
@@ -1207,61 +1207,8 @@
%7D%0A%0A
- // include the original number%0A total += num;%0A
|
f47272e71751d0f63b92d6010f9ad442e6c67889
|
change default application timeout to 3600
|
src/localhostd_console.js
|
src/localhostd_console.js
|
import React from "react";
import { compose, withProps } from "recompose";
import _ from "lodash";
import {
Nav,
NavItem,
Panel,
Button,
ButtonGroup,
ButtonToolbar
} from "react-bootstrap";
import ApplicationForm from "./application_form.js";
import ApplicationTerminal from "./application_terminal.js";
import OpenUrl from "./open_url.js";
import OpenBlob from "./open_blob.js";
import withUIState from "./with_ui_state.js";
export default compose(
withProps({ handleMessages: true }),
withUIState
)(
class LocalhostDConsole extends React.Component {
state = {
activeApplicationIndex: -1,
creatingApplication: false,
tab: "terminal"
};
render() {
const { uiState, doAction } = this.props;
const uiApplication = uiState.applications.find(
a =>
a.domain === window.location.hostname ||
window.location.hostname.endsWith(`.${a.domain}`)
);
if (uiApplication && !uiApplication.locked && uiApplication.running)
window.location.reload();
const activeApplication =
uiApplication ||
uiState.applications[this.state.activeApplicationIndex];
return (
<>
{!uiApplication && (
<div
style={{
position: "fixed",
top: 0,
left: 0,
bottom: 0,
width: 300,
padding: 10,
overflowY: "auto"
}}
>
<Nav bsStyle="pills" stacked>
{_.sortBy(
uiState.applications.map((a, index) => ({
...a,
index
})),
a => a.name
).map(application => (
<NavItem
key={application.name}
active={
this.state.activeApplicationIndex === application.index
}
onClick={() =>
this.setState({
activeApplicationIndex: application.index,
creatingApplication: false
})
}
>
<span
className={`fa fa-fw ${
application.locked
? "fa-spin fa-spinner"
: application.running
? "fa-cube"
: ""
}`}
/>
{application.name}
</NavItem>
))}
<NavItem
active={this.state.creatingApplication}
onClick={() =>
this.setState({
creatingApplication: true,
activeApplicationIndex: -1
})
}
>
<span className="fa fa-fw fa-plus" />
New application
</NavItem>
<NavItem
active={!this.state.creatingApplication && !activeApplication}
onClick={() =>
this.setState({
creatingApplication: false,
activeApplicationIndex: -1
})
}
>
<span className="fa fa-fw fa-info-circle" />
Tips
</NavItem>
</Nav>
</div>
)}
<div
style={{
position: "fixed",
left: uiApplication ? 0 : 300,
top: 0,
right: 0,
bottom: 0,
display: "flex",
flexFlow: "column nowrap",
overflow: "hidden"
}}
>
{this.state.creatingApplication && (
<div
style={{
flex: "1 1 auto",
overflowY: "auto",
padding: 10
}}
>
<Panel>
<Panel.Heading>New application</Panel.Heading>
<Panel.Body>
<ApplicationForm
application={{
dir: uiState.homedir,
env: {},
timeout: 600
}}
creating
onSubmit={applicationData => {
doAction("CreateApplication", {
applicationData
});
this.setState({
creatingApplication: false
});
}}
>
<Button
onClick={ev =>
this.setState({
creatingApplication: false
})
}
>
Cancel
</Button>
</ApplicationForm>
</Panel.Body>
</Panel>
</div>
)}
{!this.state.creatingApplication && !!activeApplication && (
<React.Fragment key={activeApplication.name}>
<Panel
style={{
flex: "0 0 auto",
margin: 0,
borderRadius: 0
}}
>
<Panel.Body>
<ButtonToolbar>
{!uiApplication && (
<Button
onClick={() => OpenUrl(activeApplication.origin)}
>
<span className="fa fa-fw fa-globe" />
{activeApplication.origin}
</Button>
)}
{uiApplication && (
<Button
onClick={() => OpenUrl(`http://${uiState.uiHost}`)}
>
<span className="fa fa-fw fa-home" />
View all applications
</Button>
)}
<Button
disabled={activeApplication.locked}
onClick={() =>
doAction(
activeApplication.running
? "StopApplication"
: "StartApplication",
{
applicationName: activeApplication.name
}
)
}
>
<span
className={`fa fa-fw fa-${
activeApplication.locked
? "spinner fa-spin"
: activeApplication.running
? "stop"
: "play"
}`}
/>
</Button>
{!uiApplication && (
<Button
disabled={
activeApplication.locked ||
!activeApplication.running
}
onClick={() =>
doAction("RestartApplication", {
applicationName: activeApplication.name
})
}
>
<span className="fa fa-fw fa-repeat" />
</Button>
)}
<ButtonGroup>
<Button
active={this.state.tab === "terminal"}
onClick={() =>
this.setState({
tab: "terminal"
})
}
>
<span className="fa fa-fw fa-terminal" />
Terminal
</Button>
<Button
active={this.state.tab === "details"}
onClick={() =>
this.setState({
tab: "details"
})
}
>
<span className="fa fa-fw fa-info" />
Details
</Button>
</ButtonGroup>
</ButtonToolbar>
</Panel.Body>
</Panel>
{this.state.tab === "details" && (
<div
style={{
flex: "1 1 auto",
overflowY: "auto",
padding: 10
}}
>
<Panel>
<Panel.Heading>Details</Panel.Heading>
<Panel.Body>
<ApplicationForm
application={activeApplication}
onSubmit={applicationData => {
doAction("CreateApplication", {
applicationData
});
}}
>
<Button
bsStyle="danger"
onClick={() =>
doAction("DeleteApplication", {
applicationName: activeApplication.name
})
}
>
Delete
</Button>
</ApplicationForm>
</Panel.Body>
</Panel>
</div>
)}
{this.state.tab === "terminal" && (
<div
style={{
flex: "1 0 auto",
position: "relative"
}}
>
<ApplicationTerminal
applicationName={activeApplication.name}
/>
</div>
)}
</React.Fragment>
)}
{!this.state.creatingApplication && !activeApplication && (
<div
style={{
flex: "1 1 auto",
overflowY: "auto",
padding: 10
}}
>
<Panel>
<Panel.Heading>Tips:</Panel.Heading>
<Panel.Body>
<p>{uiState.usageMessage}</p>
<p>
You can also download the self-signed CA for signing SSL
connections.
<a
href="localhostd.ca.crt"
disabled={!uiState.caCertificate}
onClick={event => {
event.preventDefault();
OpenBlob(
"localhostd.ca.crt",
new Blob([uiState.caCertificate])
);
}}
>
<span className="fa fa-fw fa-download" />
SSL CA certificate
</a>
</p>
</Panel.Body>
</Panel>
</div>
)}
</div>
</>
);
}
}
);
|
JavaScript
| 0.000004 |
@@ -4426,16 +4426,17 @@
imeout:
+3
600%0A
|
460dc5c216b486d4d12396a26ff784d6b55c9657
|
Create brick ball bounce function
|
js/bounce.js
|
js/bounce.js
|
var ballContactsPaddle = function(ball, paddle){
if( ball.bottomEdge().y == paddle.topSide()){
if (ball.x >= paddle.surfaceRange()[0] && ball.x <= paddle.surfaceRange()[1]){
return true;
}
}
return false
}
var paddleBounce = function(ball, paddle){
if ( ball.x.isBetween(paddle.leftEdge()[0],paddle.leftEdge()[1])){
sharpBounce('left', ball);
} else if ( ball.x.isBetween(paddle.rightEdge()[1],paddle.rightEdge()[0])){
sharpBounce('right', ball);
} else {
ball.reverseYVelocity()
}
};
var sharpBounce = function (side, ball) {
if (side == 'left'){
console.log('sharp left')
if ( ball.velocityX > 0 ){
ball.velocityX += 3
ball.velocityX = -ball.velocityX
ball.reverseYVelocity()
} else {
ball.velocityX += -3
ball.reverseYVelocity()
}
} else if (side == 'right'){
console.log('sharp right')
if ( ball.velocityX > 0 ){
ball.velocityX += 3
ball.reverseYVelocity()
} else {
ball.velocityX += -3
ball.velocityX = -ball.velocityX
ball.reverseYVelocity()
}
}
}
var ballContactsBrick = function(ball, bricks){
// debugger;
for (var layer in bricks){
bricks[layer].map(function(brick){
if ( ball.topEdge().y == brick.verticalRange()[1]){
if ( ball.topEdge().x >= brick.horizontalRange()[0] && ball.topEdge().x <= brick.horizontalRange()[1]){
return true;
};
};
})
};
}
|
JavaScript
| 0.008063 |
@@ -1456,8 +1456,55 @@
%0A %7D;%0A%7D%0A
+%0Avar brickBounce = function(ball, brick)%7B%0A %0A%7D%0A
|
403329f6dfa88540edf107b734ff1627dc4cdff4
|
Add watch task to gulp
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
// var mocha = require('gulp-mocha');
var through2 = require('through2');
gulp.task('bundle', function () {
// return bundler.bundle()
// .pipe(gulp.dest('./client/public/scripts'));
return gulp
.src('./server/client/index.js')
.pipe(through2.obj(function (file, enc, next) {
browserify(file.path, {debug : true})
.transform(babelify)
.bundle(function (err, res) {
if (err) {
return next(err);
}
file.contents = res;
next(null, file);
});
}))
.pipe(gulp.dest('./server/client/public/scripts'));
});
gulp.task('test', function (){
return gulp.src('./specs/serverspecs/*.spec.js')
});
// gulp.task('testClient', function () {
// return gulp.src('./specs/clientspecs/*.spec.js')
// .transform(babelify)
// });
|
JavaScript
| 0.000032 |
@@ -32,24 +32,152 @@
re('gulp');%0A
+var sourcemaps = require('gulp-sourcemaps');%0Avar source = require('vinyl-source-stream');%0Avar buffer = require('vinyl-buffer');%0A
var browseri
@@ -200,24 +200,60 @@
owserify');%0A
+var watchify = require('watchify');%0A
var babelify
@@ -276,19 +276,17 @@
lify');%0A
-//
+%0A
var moch
@@ -316,24 +316,22 @@
');%0Avar
-through2
+eslint
= requi
@@ -338,297 +338,130 @@
re('
-through2');%0A%0Agulp.task('bundle', function () %7B%0A // return bundler.bundle()%0A // .pipe(gulp.dest('./client/public/scripts'));%0A return gulp%0A .src('./server/client/index.js')%0A .pipe(through2.obj(function (file, enc, next) %7B%0A browserify(file.path, %7B
+gulp-eslint');%0A%0Afunction compile(watch) %7B%0A var bundler = watchify(browserify('./server/client/index.js', %7B
debug
-
: true
+
%7D)
-%0A
.tra
@@ -480,33 +480,84 @@
ify)
-%0A .bundle(
+);%0A%0A function rebundle() %7B%0A bundler.bundle()%0A .on('error',
function
(er
@@ -556,220 +556,547 @@
tion
-
(err
-, res) %7B%0A if (err) %7B%0A return next(err);%0A %7D%0A file.contents = res;%0A next(null, file);%0A %7D);%0A %7D))%0A .pipe(gulp.dest('./server/client/public/scripts'));%0A
+) %7B console.error(err); this.emit('end'); %7D)%0A .pipe(source('build.js'))%0A .pipe(buffer())%0A .pipe(sourcemaps.init(%7B loadMaps: true %7D))%0A .pipe(sourcemaps.write('./'))%0A .pipe(gulp.dest('./server/client/public/scripts'));%0A %7D%0A%0A if (watch) %7B%0A bundler.on('update', function() %7B%0A console.log('-%3E bundling...');%0A rebundle();%0A %7D);%0A %7D%0A%0A rebundle();%0A%7D%0A%0Afunction watch() %7B%0A return compile(true);%0A%7D;%0A%0Agulp.task('bundle', function() %7B return compile(); %7D);%0Agulp.task('watch', function() %7B return watch();
%7D);%0A
@@ -1107,20 +1107,55 @@
p.task('
-test
+default', %5B'watch'%5D);%0A%0Agulp.task('mocha
', funct
@@ -1160,16 +1160,17 @@
ction ()
+
%7B%0A retu
@@ -1199,24 +1199,27 @@
erverspecs/*
+*/*
.spec.js')%0A%0A
@@ -1221,17 +1221,111 @@
s')%0A
+ .pipe(mocha(%7Breporter: 'spec'%7D))%0A .once('end', function () %7B%0A process.exit();%0A %7D);
%0A%7D);%0A%0A
-//
gulp
@@ -1335,16 +1335,10 @@
sk('
-testC
li
-e
nt',
@@ -1352,19 +1352,16 @@
on () %7B%0A
-//
return
@@ -1374,71 +1374,198 @@
src(
-'./specs/clientspecs/*.spec
+%5B'server/**/*.js', '!server/client/public/scripts/index
.js'
+%5D
)%0A
-//
+
.
-transform(babelify)%0A%0A// %7D
+pipe(eslint())%0A .pipe(eslint.format())%0A // .pipe(eslint.failOnError());%0A%7D);%0A%0Agulp.task('test', %5B'mocha', 'lint'%5D
);%0A
|
11ead6685986ba7eb7565ad54b6c5cda3ad2b736
|
Update search API usage
|
app/controllers/records/list.js
|
app/controllers/records/list.js
|
var facetsDef = [
{
name: 'type',
label: 'Type de résultat',
valueLabels: {
dataset: 'Jeu de données',
service: 'Service',
map: 'Carte',
other: 'Autre',
none: 'Non renseigné'
}
},
{
name: 'representationType',
label: 'Type de donnée',
valueLabels: {
vector: 'Vecteur',
grid: 'Imagerie / Raster',
other: 'Autre',
none: 'Non renseigné'
}
},
{
name: 'opendata',
label: 'Donnée ouverte',
valueLabels: {
yes: 'Oui',
'not-determined': 'Indéterminé'
}
},
{
name: 'availability',
label: 'Disponibilité',
valueLabels: {
yes: 'Oui',
'not-determined': 'Indéterminé'
}
},
{
name: 'organization',
label: 'Organismes'
},
{
name: 'keyword',
label: 'Mot-clés'
},
{
name: 'distributionFormat',
label: 'Format de distribution',
valueLabels: {
'wfs-featureType': 'WFS',
'file-package': 'Package fichier'
}
}
];
angular.module('mainApp').controller('ServiceRecords', function ($scope, $http, $location, $stateParams) {
function buildQueryString() {
if (!$scope.datasets) {
return _.pick($stateParams, 'organization', 'keyword', 'type', 'representationType', 'opendata', 'availability', 'distributionFormat', 'q', 'offset');
} else {
var qs = {};
$scope.activeFacets.forEach(function (activeFacet) {
if (!qs[activeFacet.name]) qs[activeFacet.name] = [];
qs[activeFacet.name].push(activeFacet.value);
});
qs.q = $scope.q;
qs.offset = $scope.offset;
return qs;
}
}
$scope.fetchDatasets = function() {
$http
.get('/api/geogw/services/' + $scope.currentService._id + '/datasets', { params: buildQueryString() })
.success(function(data) {
$scope.datasets = data.results;
$scope.count = data.count;
$scope.offset = data.query.offset;
$scope.firstResultPos = data.query.offset + 1;
$scope.lastResultPos = data.query.offset + data.results.length;
$scope.activeFacets = data.query.facets;
$scope.computeFacets(data.facets);
});
};
$scope.computeFacets = function (facets) {
$scope.facets = _.map(facetsDef, function(def) {
return { name: def.name, label: def.label, values: facets[def.name], valueLabels: def.valueLabels };
});
};
$scope.updateResults = function (paginate) {
if (!paginate) $scope.offset = null;
$location.search(buildQueryString());
$scope.fetchDatasets();
};
$scope.hasPreviousResults = function() {
return $scope.datasets && ($scope.offset > 0);
};
$scope.hasNextResults = function() {
return $scope.datasets && ($scope.offset + $scope.datasets.length < $scope.count);
};
$scope.paginatePrevious = function() {
$scope.offset = $scope.offset - 20;
$scope.updateResults(true);
};
$scope.paginateNext = function() {
$scope.offset = $scope.offset + 20;
$scope.updateResults(true);
};
$scope.toggleFacet = function (facet) {
if (!$scope.facetIsActive(facet)) {
$scope.activeFacets.push(facet);
} else {
_.remove($scope.activeFacets, facet);
}
$scope.updateResults();
};
$scope.facetIsActive = function (facet) {
return _.find($scope.activeFacets, facet);
};
$scope.applyFacet = function (facet) {
$scope.activeFacets = [facet];
$scope.updateResults();
};
$scope.encodeURIComponent = encodeURIComponent;
$scope.$watch('q', $scope.updateResults, true);
$scope.fetchDatasets();
});
|
JavaScript
| 0 |
@@ -1002,32 +1002,97 @@
s'%0A %7D,%0A %7B%0A
+ name: 'catalog',%0A label: 'Catalogue'%0A %7D,%0A %7B%0A
name: 'd
@@ -2106,23 +2106,22 @@
_id + '/
-dataset
+record
s', %7B pa
|
f3b66a24761b4e121ab4374496cf7505b1393ce4
|
Make widget independent from jquery
|
payments/static/payments/js/wallet.js
|
payments/static/payments/js/wallet.js
|
// Success handler
var successHandler = function(status){
if (window.console != undefined) {
console.log("Purchase completed successfully: ", status);
}
window.location = $('input#google-wallet-id').data('success-url');
};
// Failure handler
var failureHandler = function(status){
if (window.console != undefined) {
console.log("Purchase failed ", status);
}
window.location = $('input#google-wallet-id').data('failure-url');
};
function purchase() {
var generated_jwt = $('input#google-wallet-id').data('jwt');
google.payments.inapp.buy({
'jwt' : generated_jwt,
'success' : successHandler,
'failure' : failureHandler
});
return false
}
jQuery(document).ready(function() {
purchase();
});
|
JavaScript
| 0 |
@@ -1,9 +1,27 @@
-%0A
+(function() %7B%0A%0A
// Succe
@@ -27,24 +27,28 @@
ess handler%0A
+
var successH
@@ -70,32 +70,36 @@
on(status)%7B%0A
+
if (window.conso
@@ -109,32 +109,36 @@
!= undefined) %7B%0A
+
console.
@@ -183,38 +183,46 @@
%22, status);%0A
-%7D%0A
+ %7D%0A
+
window.location
@@ -219,33 +219,49 @@
.location =
-$('input#
+document.getElementById('
google-walle
@@ -267,22 +267,35 @@
et-id').
+getAttribute('
data
-('
+-
success-
@@ -301,20 +301,28 @@
-url');%0A
-%7D;%0A%0A
+ %7D;%0A%0A
// Failu
@@ -332,16 +332,20 @@
handler%0A
+
var fail
@@ -371,24 +371,28 @@
on(status)%7B%0A
+
if (wind
@@ -410,32 +410,36 @@
!= undefined) %7B%0A
+
console.
@@ -467,24 +467,28 @@
%22, status);%0A
+
%7D%0A wi
@@ -481,24 +481,28 @@
%7D%0A
+
window.locat
@@ -507,25 +507,41 @@
ation =
-$('input#
+document.getElementById('
google-w
@@ -551,22 +551,35 @@
et-id').
+getAttribute('
data
-('
+-
failure-
@@ -585,20 +585,28 @@
-url');%0A
-%7D;%0A%0A
+ %7D;%0A%0A
function
@@ -619,24 +619,28 @@
ase() %7B%0A
+
var generate
@@ -651,17 +651,33 @@
t =
-$('input#
+document.getElementById('
goog
@@ -695,22 +695,35 @@
d').
+getAttribute('
data
-('
+-
jwt');%0A%0A
@@ -718,16 +718,20 @@
jwt');%0A%0A
+
goog
@@ -760,16 +760,22 @@
%7B%0A
+
'jwt'
@@ -799,16 +799,22 @@
,%0A
+
'success
@@ -839,16 +839,22 @@
,%0A
+
'failure
@@ -876,20 +876,28 @@
ler%0A
+
%7D);%0A
+
retu
@@ -909,51 +909,91 @@
lse%0A
-%7D%0A%0AjQuery(document).ready(function(
+ %7D%0A%0A $ = this.jQuery %7C%7C this.Zepto %7C%7C this.ender %7C%7C this.$;%0A%0A if($
) %7B%0A
purc
@@ -988,24 +988,30 @@
) %7B%0A
+ $(
purchase
();%0A%7D);%0A
@@ -1006,12 +1006,63 @@
hase
-();%0A%7D);
+)%0A %7D else %7B%0A window.onload = purchase%0A %7D%0A%7D)()
%0A
|
011481deb3604bb6308d1fa55f48dac7af416041
|
Fix for event handling
|
dist/leaflet.easyPrint.js
|
dist/leaflet.easyPrint.js
|
L.Control.EasyPrint = L.Control.extend({
options: {
title: 'Print map',
position: 'topleft'
},
onAdd: function () {
var container = L.DomUtil.create('div', 'leaflet-control-easyPrint leaflet-bar leaflet-control');
this.link = L.DomUtil.create('a', 'leaflet-control-easyPrint-button leaflet-bar-part', container);
this.link.id = "leafletEasyPrint";
this.link.title = this.options.title;
L.DomEvent.addListener(this.link, 'click', printPage, this.options);
L.DomEvent.disableClickPropagation(container);
return container;
}
});
L.easyPrint = function(options) {
return new L.Control.EasyPrint(options);
};
function printPage(){
if (this.elementsToHide){
var htmlElementsToHide = document.querySelectorAll(this.elementsToHide);
for (var i = 0; i < htmlElementsToHide.length; i++) {
htmlElementsToHide[i].className = htmlElementsToHide[i].className + ' _epHidden';
}
}
this.map.fire("beforePrint");
window.print();
this.map.fire("afterPrint");
if (this.elementsToHide){
var htmlElementsToHide = document.querySelectorAll(this.elementsToHide);
for (var i = 0; i < htmlElementsToHide.length; i++) {
htmlElementsToHide[i].className = htmlElementsToHide[i].className.replace(' _epHidden','');
}
}
}
|
JavaScript
| 0.000001 |
@@ -470,24 +470,16 @@
ge, this
-.options
);%0D%0A%09%09L.
@@ -671,32 +671,40 @@
)%7B%0D%0A%0D%0A%09if (this.
+options.
elementsToHide)%7B
@@ -755,32 +755,40 @@
electorAll(this.
+options.
elementsToHide);
@@ -943,32 +943,33 @@
%0A%09%09%7D%0D%0A%09%7D%0D%0A%09this.
+_
map.fire(%22before
@@ -1002,16 +1002,17 @@
%0D%0A%09this.
+_
map.fire
@@ -1034,24 +1034,32 @@
%0D%0A%09if (this.
+options.
elementsToHi
@@ -1122,16 +1122,24 @@
ll(this.
+options.
elements
|
386608d8a3562e55874527909ddb3b74a72bc547
|
Fix oauth/slack route
|
server/back-end/routes/oauth.js
|
server/back-end/routes/oauth.js
|
// Routes for oauth
// /oauth
var express = require('express');
var router = express.Router();
var errors = require('@holmwell/errors');
var ensure = require('circle-blvd/auth-ensure');
var guard = errors.guard;
var handle = require('circle-blvd/handle');
var request = require('request');
module.exports = function (db) {
var settings = require('circle-blvd/settings')(db);
router.get('/oauth/slack', ensure.auth, function (req, res) {
var payload = req.query;
if (payload.state && payload.code) {
// Verify that we have access to the circle
// specified in state
var memberships = req.user.memberships;
for (var index in memberships) {
if (memberships[index].circle === payload.state) {
settings.get(guard(res, processSettings));
return;
}
}
}
function processSettings(settings) {
// Get Slack access, save the tokens
var oauthUrl = [
'https://slack.com/api/oauth.access',
'?client_id=',
settings['slack-client-id'].value,
'&client_secret=',
settings['slack-client-secret'].value,
'&code=',
payload.code
].join('');
request.get(oauthUrl, handleOauthReply);
}
function handleOauthReply(err, httpResponse, body) {
var access = JSON.parse(body);
if (access && access.ok) {
var circleId = payload.state;
db.circles.get(circleId, guard(res, updateCircle));
}
else {
// Didn't work out
console.log(err);
res.redirect('/#/');
}
}
function updateCircle(circle) {
circle.access = circle.access || {};
circle.access.slack = access;
circle.webhooks = circle.webhooks || {};
circle.webhooks.slack = circle.webhooks.slack || {};
circle.webhooks.slack.url = access.incoming_webhook.url;
db.circles.update(circle, guard(res, function () {
res.redirect('/#/');
}));
}
// fallback / invalid request
res.redirect('/#/');
});
return {
router: router
};
};
|
JavaScript
| 0.999775 |
@@ -393,14 +393,8 @@
t('/
-oauth/
slac
|
65774e04adea7546642b921f7e39affc58ff76d0
|
remove console statements
|
src/modules/count/count.js
|
src/modules/count/count.js
|
/* @flow */
import { TABLES, ROLES } from '../../lib/schema';
import { bus, cache } from '../../core-server';
import * as Constants from '../../lib/Constants';
import log from 'winston';
import User from '../../models/user';
import Counter from '../../lib/counter';
// import ThreadRel from '../../models/threadrel';
// import RoomRel from '../../models/roomrel';
bus.on('change', (changes, next) => {
if (!changes.entities) {
next();
return;
}
const counter = new Counter();
for (const id in changes.entities) {
const entity = changes.entities[id];
// 1. Increment children counts on parents
if (
entity.type === Constants.TYPE_TEXT ||
entity.type === Constants.TYPE_THREAD
) {
if (!entity.createTime || entity.createTime !== entity.updateTime || (!entity.parents || !entity.parents.length)) {
continue;
}
let inc;
log.info('Count module reached: ', entity);
if (entity.createTime === entity.updateTime) {
log.info('increase count');
inc = 1;
} else if (entity.deleteTime) {
inc = -1;
}
const parent = changes.entities[entity.parents[0]] || {};
parent.counts = parent.counts || {};
parent.counts.children = [ inc, '$add' ];
parent.id = entity.parents[0];
parent.type = (entity.type === Constants.TYPE_TEXT) ?
Constants.TYPE_THREAD : Constants.TYPE_ROOM;
// if (entity.type === Constants.TYPE_TEXT) {
//
// }
// console.log('parents count module: ', parent);
changes.entities[entity.parents[0]] = parent;
// 2. Increment text/thread count of user
const user = changes.entities[entity.creator] || new User({ id: entity.creator });
user.counts = user.counts || {};
user.counts[TABLES[entity.type]] = [ inc, '$add' ];
user.id = entity.creator;
changes.entities[entity.creator] = user;
}
// 3. Increment related counts on items
if (
entity.type === Constants.TYPE_TEXTREL ||
entity.type === Constants.TYPE_THREADREL ||
entity.type === Constants.TYPE_ROOMREL ||
entity.type === Constants.TYPE_PRIVREL ||
entity.type === Constants.TYPE_TOPICREL
) {
if (!entity.id) entity.id = entity.user + '_' + entity.item;
console.log('roomrel: , entity: ', entity);
// if (entity.roles.length === 0) {
// decrementCount(changes, entity);
// continue;
// }
counter.inc();
cache.getEntity(entity.id, (err, result) => {
let exist = [], inc = 1;
if (err) {
counter.err(err);
return;
}
console.log("result: ", result);
if (result) {
entity.roles.forEach((role) => {
if (result.roles.indexOf(role) === -1) {
exist.push(role);
}
});
if (entity.roles.length === 0) {
console.log('got roles empty');
inc = -1;
exist = result.roles;
}
if (exist.length === 0) {
counter.dec();
return;
}
} else {
exist = entity.roles;
}
const item = changes.entities[entity.item] || {};
item.counts = item.counts || {};
// if (entity.__op__ && entity.__op__.role && entity.__op__.roles[0] === 'union') {
// const rem = entity.__op__.roles[0].slice(1);
//
// rem.forEach((role) => {
// if (ROLES[role]) {
// item.counts[ROLES[role]] = -1;
// item.counts.__op__[ROLES[role]] = 'inc';
// }
// });
// }
// console.log("exist: entity.roles: ", exist, entity.roles );
exist.forEach((role) => {
if (ROLES[role]) {
item.counts[ROLES[role]] = [ inc, '$add' ];
}
});
item.id = entity.item;
switch (entity.type) {
case Constants.TYPE_TEXTREL:
item.type = Constants.TYPE_TEXT;
break;
case Constants.TYPE_THREADREL:
item.type = Constants.TYPE_THREAD;
break;
case Constants.TYPE_ROOMREL:
item.type = Constants.TYPE_ROOM;
break;
case Constants.TYPE_PRIVREL:
item.type = Constants.TYPE_PRIV;
break;
case Constants.TYPE_TOPICREL:
item.type = Constants.TYPE_TOPIC;
break;
}
changes.entities[entity.item] = item;
console.log("item count module: ", item);
counter.dec();
});
}
}
counter.then(next);
}, Constants.APP_PRIORITIES.COUNT);
log.info('Count module ready.');
|
JavaScript
| 0.00002 |
@@ -2145,24 +2145,27 @@
ty.item;%0A%09%09%09
+//
console.log(
@@ -2453,24 +2453,27 @@
;%0A%09%09%09%09%7D%0A%09%09%09%09
+//
console.log(
@@ -2679,24 +2679,27 @@
0) %7B%0A%09%09%09%09%09%09
+//
console.log(
|
5c4792038474fe2c8107f925c066c260be09b2a5
|
Remove String.prototype.split polyfill warning (#7629)
|
src/renderers/dom/ReactDOM.js
|
src/renderers/dom/ReactDOM.js
|
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactDOMComponentTree = require('ReactDOMComponentTree');
var ReactDefaultInjection = require('ReactDefaultInjection');
var ReactMount = require('ReactMount');
var ReactReconciler = require('ReactReconciler');
var ReactUpdates = require('ReactUpdates');
var ReactVersion = require('ReactVersion');
var findDOMNode = require('findDOMNode');
var getHostComponentFromComposite = require('getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
var warning = require('warning');
ReactDefaultInjection.inject();
var ReactDOM = {
findDOMNode: findDOMNode,
render: ReactMount.render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer,
/* eslint-enable camelcase */
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
ComponentTree: {
getClosestInstanceFromNode:
ReactDOMComponentTree.getClosestInstanceFromNode,
getNodeFromInstance: function(inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
inst = getHostComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
} else {
return null;
}
},
},
Mount: ReactMount,
Reconciler: ReactReconciler,
});
}
if (__DEV__) {
var ExecutionEnvironment = require('ExecutionEnvironment');
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if ((navigator.userAgent.indexOf('Chrome') > -1 &&
navigator.userAgent.indexOf('Edge') === -1) ||
navigator.userAgent.indexOf('Firefox') > -1) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 &&
navigator.userAgent.indexOf('Firefox') === -1;
console.debug(
'Download the React DevTools ' +
(showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') +
'for a better development experience: ' +
'https://fb.me/react-devtools'
);
}
}
var testFunc = function testFn() {};
warning(
(testFunc.name || testFunc.toString()).indexOf('testFn') !== -1,
'It looks like you\'re using a minified copy of the development build ' +
'of React. When deploying React apps to production, make sure to use ' +
'the production build which skips development warnings and is faster. ' +
'See https://fb.me/react-minification for more details.'
);
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode =
document.documentMode && document.documentMode < 8;
warning(
!ieCompatibilityMode,
'Internet Explorer is running in compatibility mode; please add the ' +
'following tag to your HTML to prevent this from happening: ' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge" />'
);
var expectedFeatures = [
// shims
Array.isArray,
Array.prototype.every,
Array.prototype.forEach,
Array.prototype.indexOf,
Array.prototype.map,
Date.now,
Function.prototype.bind,
Object.keys,
String.prototype.split,
String.prototype.trim,
];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
warning(
false,
'One or more ES5 shims expected by React are not available: ' +
'https://fb.me/react-warning-polyfills'
);
break;
}
}
}
}
if (__DEV__) {
var ReactInstrumentation = require('ReactInstrumentation');
var ReactDOMUnknownPropertyHook = require('ReactDOMUnknownPropertyHook');
var ReactDOMNullInputValuePropHook = require('ReactDOMNullInputValuePropHook');
ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook);
ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook);
}
module.exports = ReactDOM;
|
JavaScript
| 0 |
@@ -4336,38 +4336,8 @@
ys,%0A
- String.prototype.split,%0A
|
9cc428864a593468f7f28fe59dbbd7f1d60a4359
|
rename var mocha to fix redefinition
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var javascriptGlobs = ['*.js', 'src/**/*.js', 'test/**/*.js'];
var testGlobs = ['test/**/*.js'];
gulp.task('style', function() {
gulp.src(javascriptGlobs)
.pipe(jscs())
.pipe(jscs.reporter())
.pipe(jscs.reporter('fail'));
});
gulp.task('lint', function() {
gulp.src(javascriptGlobs)
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter())
.pipe(jshint.reporter('fail'));
});
gulp.task('test', function() {
gulp.src(testGlobs)
.pipe(mocha());
});
gulp.task('build', ['lint', 'style', 'test'], function() {
gulp.src('/');
});
gulp.task('default', ['build']);
|
JavaScript
| 0 |
@@ -110,17 +110,21 @@
');%0Avar
-m
+gulpM
ocha = r
@@ -611,17 +611,21 @@
.pipe(
-m
+gulpM
ocha());
|
2516a52873b70afb1b90b0b0ed13b8f7240be2e1
|
Change init.
|
src/mb/app/Application.js
|
src/mb/app/Application.js
|
import AdaptiveApplication from "sap/a/app/Application";
import MapView from "../map/MapView";
export default class Application extends AdaptiveApplication
{
init()
{
super.init();
this.addStyleClass("mb-app");
this._initMapView();
}
_initMapView()
{
this.mapView = new MapView("map-view", {
defaultValue: 10
});
this.addSubview(this.mapView);
}
}
|
JavaScript
| 0.000001 |
@@ -157,17 +157,22 @@
n%0A%7B%0A
-i
+afterI
nit()%0A
@@ -189,17 +189,22 @@
super.
-i
+afterI
nit();%0A
|
99906dadc8d35af503fac9c068be02d7c75397cc
|
add "focus" to focused btns with button plugin
|
js/button.js
|
js/button.js
|
/* ========================================================================
* Bootstrap: button.js v3.1.1
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.1.1'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
$el[val](data[state] == null ? this.options[state] : data[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
}(jQuery);
|
JavaScript
| 0 |
@@ -2676,24 +2676,235 @@
this%0A %7D%0A%0A%0A
+ // FOCUS SHIM (FOR BUTTON GROUPS)%0A // ==============================%0A%0A function getBtnTarget(target) %7B%0A var $target = $(target)%0A return $target.hasClass('btn') ? $target : $target.parent('.btn')%0A %7D%0A%0A%0A
// BUTTON
@@ -2947,16 +2947,21 @@
ocument)
+%0A
.on('cli
@@ -3026,24 +3026,26 @@
n (e) %7B%0A
+
var $btn = $
@@ -3051,24 +3051,26 @@
$(e.target)%0A
+
if (!$bt
@@ -3120,16 +3120,18 @@
n')%0A
+
Plugin.c
@@ -3146,24 +3146,26 @@
, 'toggle')%0A
+
e.preven
@@ -3175,16 +3175,284 @@
fault()%0A
+ %7D)%0A .on('focus.bs.button.data-api', '%5Bdata-toggle%5E=%22button%22%5D', function (e) %7B%0A getBtnTarget(e.target).addClass('focus')%0A %7D)%0A .on('blur.bs.button.data-api', '%5Bdata-toggle%5E=%22button%22%5D', function (e) %7B%0A getBtnTarget(e.target).removeClass('focus')%0A
%7D)%0A%0A%7D(
|
2fdb07200ab712e0f731a63d53a43378690c2fd0
|
Change type to ordinal if there are few unique values.
|
src/app/dataset/dataset.js
|
src/app/dataset/dataset.js
|
'use strict';
var datasets = [{
name: 'Barley',
url: 'data/barley.json',
table: 'barley_json'
},{
name: 'Cars',
url: 'data/cars.json',
table: 'cars_json'
},{
name: 'Crimea',
url: 'data/crimea.json',
table: 'crimea_json'
},{
name: 'Driving',
url: 'data/driving.json',
table: 'driving_json'
},{
name: 'Iris',
url: 'data/iris.json',
table: 'iris_json'
},{
name: 'Jobs',
url: 'data/jobs.json',
table: 'jobs_json'
},{
name: 'Population',
url: 'data/population.json',
table: 'population_json'
},{
name: 'Movies',
url: 'data/movies.json',
table: 'movies_json'
},{
name: 'Birdstrikes',
url: 'data/birdstrikes.json',
table: 'birdstrikes_json'
},{
name: "Burtin",
url: "data/burtin.json",
table: 'burtin_json'
},{
name: "Budget 2016",
url: "data/budget.json",
table: 'budget_json'
},{
name: "Climate Normals",
url: "data/climate.json",
table: 'climate_json'
},{
name: "Campaigns",
url: "data/weball26.json",
table: 'weball26_json'
}];
function getNameMap(dataschema) {
return dataschema.reduce(function(m, field) {
m[field.name] = field;
return m;
}, {});
}
angular.module('vleApp')
.factory('Dataset', function($http, Config, _, Papa, vl, consts) {
var Dataset = {};
var countField = vl.field.count();
Dataset.datasets = datasets;
Dataset.dataset = datasets[7]; //Movies
Dataset.dataschema = [];
Dataset.dataschema.byName = {};
Dataset.stats = {};
// TODO move these to constant to a universal vlui constant file
Dataset.typeNames = {
O: 'text',
Q: 'number',
T: 'time',
G: 'geo'
};
Dataset.fieldOrder = vl.field.order.typeThenName;
// update the schema and stats
Dataset.update = function (dataset) {
//set schema and stats
if (Config.useVegaServer) {
var url = Config.serverUrl + '/stats/?name=' + dataset.table;
return $http.get(url, {cache: true}).then(function(response) {
var parsed = Papa.parse(response.data, {header: true});
var dataschema=[], stats = {};
_.each(_.filter(parsed.data, function(d) {return d.name;}), function(row) {
var fieldStats = {};
fieldStats.min = +row.min;
fieldStats.max = +row.max;
fieldStats.cardinality = +row.cardinality;
stats[row.name] = fieldStats;
// TODO add "geo" and "time"
var type = row.type === 'integer' || row.type === 'real' ? 'Q' : 'O';
dataschema.push({name: row.name, type: type});
stats.count = row.count;
});
if (consts.addCount) {
dataschema.push(countField);
}
Dataset.dataschema = dataschema;
Dataset.dataschema.byName = getNameMap(Dataset.dataschema);
Dataset.stats = stats;
});
} else {
return $http.get(dataset.url, {cache: true}).then(function(response) {
Dataset.data = response.data;
var dataschema = vl.data.getSchema(response.data);
if (consts.addCount) {
dataschema.push(countField);
}
Dataset.dataschema = dataschema;
Dataset.dataschema.byName = getNameMap(Dataset.dataschema);
Dataset.stats = vl.data.getStats(response.data);
});
}
};
return Dataset;
});
|
JavaScript
| 0 |
@@ -3293,32 +3293,468 @@
response.data);%0A
+%0A _.each(Dataset.dataschema, function(field) %7B%0A // if fewer than 2%25 of values or unique, assume the field to be ordinal,%0A // or %3C= 7 unique values%0A var stats = Dataset.stats%5Bfield.name%5D;%0A if (stats !== undefined && (field.type === 'Q' && stats.cardinality %3C (stats.count - stats.numNulls)/50 %7C%7C stats.cardinality %3C= 7)) %7B%0A field.type = 'O';%0A %7D%0A %7D);%0A%0A
%7D);%0A
|
86f87b1269c6a7cd5a55703ab314793e5c579bd4
|
Remove deprecated auth code
|
public/app/auth/auth.js
|
public/app/auth/auth.js
|
angular.module('headcount.auth', [])
.controller('AuthController', function ($scope, $window, $location, $http, Auth) {
/**
* $scope.user holds onto any input on the signin.html and signup.html input
* fields.
*/
$scope.user = {};
/**
* $scope.signin & $scope.signup both make a POST request to the routes/auth.js file
* with the attempted login information from $scope.user. On successful authentication,
* it sets the session item 'user' to the username, so that we can render the content
* specifically to the user that's currently signed in.
*/
$scope.signin = function () {
return $http({
method: 'POST',
url: '/auth/local',
data: $scope.user
})
.then(function (resp) {
$window.sessionStorage.setItem('user', resp.config.data.username);
$window.location.href = "/";
})
.catch(function(error) {
$window.alert("Incorrect login, please try again!");
});
};
$scope.signup = function () {
return $http({
method: 'POST',
url: '/auth/local-signup',
data: $scope.user
})
.then(function (resp) {
$window.sessionStorage.setItem('user', resp.config.data.username);
$window.location.href = "/";
})
.catch(function(error) {
$window.alert("Username already exists, please try again!");
});
};
/**
* $scope.signout calls Auth.signout on the 'Auth' factory, under the services.js
* file. It destroys the session item 'user', and then resets the view to the sign-in
* page. It also makes a GET request to routes/auth.js's logout route, which will also
* destroy the express-session token on the backend, then alerts the user on a
* successful request.
*/
$scope.signout = function(){
Auth.signout();
$scope.auth = Auth.isAuth();
return $http({
method: 'GET',
url: '/auth/logout'
})
.then(function(resp) {
$window.alert("You've signed out!");
});
};
});
|
JavaScript
| 0.000021 |
@@ -1778,41 +1778,8 @@
();%0A
- $scope.auth = Auth.isAuth();%0A
|
1345bfe6bb2adc0511e7bd9395a3b40359bea993
|
update docs
|
lib/packages/browser/js/views/example/index.js
|
lib/packages/browser/js/views/example/index.js
|
var BaseView = require("../base"),
AceEditor = require("./ace/index.js"),
paperclip = require("paperclip"),
BindableObject = require("bindable-object"),
traverse = require("traverse");
module.exports = BaseView.extend({
template: require("./index.pc"),
willRender: function () {
var self = this;
this.set("files", [
new BindableObject({ name: "template", source: this.source, lang: "html" }),
new BindableObject({ name: "config", source: this.config.replace(/(^[\s\r\n\t]+|[\s\r\n\t]+$)/,""), lang: "javascript" })
]);
this.set("editor", new AceEditor({
onSourceChange: function (file) {
self.updatePreview();
}
}));
this.setFile(this.files[0]);
},
setFile: function (file) {
if (this.selectedFile) this.selectedFile.set("selected", false);
file.set("selected", true);
this.editor.set("file", this.set("selectedFile", file));
},
updatePreview: function () {
var tpl = this.files[0].source, conf = this.files[1].source;
this.__config = (new Function("return " + conf.replace(/[\n\r]/g,"")));
this.__compiled = paperclip.template("<div>" + tpl + "</div>");
this.run();
},
run: function () {
if (this._disposable && this._disposable.dispose) {
this._disposable.dispose();
}
var conf = this.__config();
if (typeof conf === "function") {
this._disposable = conf = conf(this);
}
var _confirmed = true;
console.log(conf);
// safe guard incase
traverse(conf).forEach(function (x) {
if (x.length > 30000) _confirmed = confirm("Looks like your config is super big - this might take a while. Continue?")
});
if (!_confirmed) return;
var start = Date.now();
var preview = this.__compiled.bind(conf).render();
this.set("speed", Date.now() - start);
this.set("preview", preview);
}
});
|
JavaScript
| 0.000001 |
@@ -1467,32 +1467,8 @@
e;%0A%0A
- console.log(conf);%0A%0A
|
dcd245438d276171e4ded51d3d0717657576d283
|
Switch to /server as soon as the connection opens
|
scripts/controllers/login.js
|
scripts/controllers/login.js
|
Controllers.controller("LoginCtrl",
["$log", "$scope", "$http", "$rootScope", "$location", "$timeout", "$filter",
"Connection", "User", "Channel", "Parser",
function ($log, $scope, $http, $rootScope, $location, $timeout, $filter,
Connection, User, Channel, Parser)
{
var mustKill = false;
$scope.user = User.get("~");
$scope.user.nickName = $.cookie("nickName");
if ($.cookie("color"))
{
$scope.user.color = $.cookie("color");
}
$location.hash("");
$http.jsonp("http://geoip.yonom.org/index.php?callback=JSON_CALLBACK")
.success(function (data)
{
$scope.user.country = data.geoplugin_countryName;
$scope.user.flag = data.geoplugin_countryCode;
});
$rootScope.$on("err_nicknameinuse", function (evt)
{
if ($scope.user.password)
{
Connection.send("NICK " + $scope.user.nickName + "_");
mustKill = true;
return;
}
Connection.close();
$scope.reset();
$rootScope.$apply(function ()
{
$scope.error = "Nickname is in use";
});
});
$rootScope.$on("channel.joined", function (evt, channel)
{
$scope.connecting = false;
$scope.connected = false;
$scope.error = "";
});
$scope.reset = function ()
{
$scope.connecting = false;
$scope.connected = false;
$scope.hostToken = "";
if (VERSION === "local")
{
$scope.port = 81;
} else
{
$scope.port = 82;
}
$scope.error = "";
}
$scope.login = function ()
{
$scope.reset();
User.register($scope.user.nickName);
User.alias("~", $scope.user.nickName);
$http.jsonp("http://kaslai.us/coldstorm/fixip2.php?nick=" +
encodeURI($scope.user.nickName) + "&random=" +
Math.floor(Math.random() * 10000000) +
"&callback=JSON_CALLBACK").success(function (data)
{
$scope.hostToken = data.tag;
});
$.cookie("nickName", $scope.user.nickName, { expires: new Date(2017, 00, 01) });
$.cookie("color", $scope.user.color, { expires: new Date(2017, 00, 01) });
$scope.connect();
};
$scope.connect = function ()
{
if ($scope.connecting === false)
{
$scope.connecting = true;
// Attempt to connect
$log.log("connecting to ws://frogbox.es:" + $scope.port)
Connection.connect("ws://frogbox.es:" + $scope.port);
Connection.onOpen(function ()
{
// Connection successfully opened
$scope.reset();
$scope.connected = true;
Connection.send("NICK " + $scope.user.nickName);
Connection.send("USER " +
$scope.user.color.substring(1).toUpperCase() +
$scope.user.flag + " - - :New coldstormer");
Connection.onWelcome(function ()
{
if (mustKill)
{
Connection.send("PRIVMSG NickServ :GHOST " +
$scope.user.nickName + " " +
$scope.user.password);
}
if ($scope.user.password)
{
Connection.send("PRIVMSG NickServ :identify " +
$scope.user.password);
}
if ($scope.hostToken)
{
Connection.send("PRIVMSG Jessica :~fixmyip " +
$scope.hostToken);
}
});
});
Connection.onMessage(function (message)
{
if (message.indexOf("NOTICE " + $scope.user.nickName +
" :Tada") > -1)
{
if (VERSION == "local")
{
var test = Channel.register("#test");
test.join();
$location.path("/channels/#test");
} else
{
var cs = Channel.register("#Coldstorm");
var two = Channel.register("#2");
cs.join();
two.join();
$location.path("/channels/#Coldstorm");
}
}
if (message.indexOf("NOTICE " + $scope.user.nickName +
"_ :Ghost with your nick has been killed.") > -1 &&
mustKill)
{
Connection.send("NICK " + $scope.user.nickName);
Connection.send("PRIVMSG NickServ :IDENTIFY " +
$scope.user.password);
mustKill = false;
if ($scope.hostToken)
{
Connection.send("PRIVMSG Jessica :~fixmyip " +
$scope.hostToken);
}
}
Parser.parse(message);
});
Connection.onClose(function ()
{
$scope.connecting = false;
if ($scope.connected)
{
// We were already connected and on the chat view, go back to login
$location.path("/login");
$scope.reset();
}
else
{
if ($scope.port < 85)
{
$scope.port++;
$scope.connect();
} else
{
$rootScope.$apply(function ()
{
$scope.error = "Couldn't connect to the server";
})
}
}
});
}
};
}]);
|
JavaScript
| 0 |
@@ -3057,32 +3057,80 @@
nected = true;%0A%0A
+ $location.path(%22/server%22);%0A%0A
|
a119ad216b8e9c9ae84e43dbdbb82fdc3468717d
|
remove log
|
app/lib/handlers/sqs-message.js
|
app/lib/handlers/sqs-message.js
|
'use strict';
var LAMBDA_WORKER_FUNCTION_NAME = process.env.LAMBDA_FUNCTION;
var validate = require('../validate.js')
, parseJson = require('../parse-json.js')
, lambda = require('../lambda.js');
var errorHandlers = require('./errors.js');
var forwardMessageToLambdaWorker = function(req, res, body) {
var sqsMessage = parseJson(body, function(err) {
return body; // use raw body
});
console.log('body', body);
var lambdaEvent = lambda.createLambdaEventFromSqsMessage(req, sqsMessage);
lambda.trigger(LAMBDA_WORKER_FUNCTION_NAME, lambdaEvent, function(err, data) {
if (err) {
// local, app error
errorHandlers.generic(req, res, 500, err.message);
return;
}
else if (data instanceof Error) {
// remote lamba had error; "bad gateway"
errorHandlers.generic(req, res, 502, data.message);
return;
}
else {
// yay?
if (data.Action) {
switch (data.Action) {
case 'DELETE':
// yay! tells EB worker sqsd that message was processed and it issues a DeleteMessage
res.writeHead(200);
res.end();
return;
default:
// nothing else is supported
errorHandlers.generic(req, res, 501, 'Invalid response Action: ' + data.Action);
return;
}
}
else {
errorHandlers.generic(req, res, 502, 'Lambda Worker Response Formatted Incorrectly');
return;
}
}
});
};
module.exports = function(req, res) {
var body = '';
if (!validate.isContentTypeJson(req.headers['content-type'])) {
errorHandlers.notAcceptable(req, res);
return;
}
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
forwardMessageToLambdaWorker(req, res, body);
});
};
|
JavaScript
| 0.000001 |
@@ -394,16 +394,19 @@
%0A %7D);%0A
+ //
console
|
6033fe51b7f679bf970e42a80c3dc2e4f3cef573
|
fix text field: better height for textarea
|
modules/text-field/js/text-field_directive.js
|
modules/text-field/js/text-field_directive.js
|
/* global angular */
'use strict'; // jshint ignore:line
angular.module('lumx.text-field', [])
.filter('unsafe', ['$sce', function($sce)
{
return $sce.trustAsHtml;
}])
.directive('lxTextField', ['$timeout', function($timeout)
{
return {
restrict: 'E',
scope: {
label: '@',
disabled: '&',
error: '&',
valid: '&',
fixedLabel: '&',
icon: '@',
theme: '@'
},
templateUrl: 'text-field.html',
replace: true,
transclude: true,
link: function(scope, element, attrs, ctrl, transclude)
{
if (angular.isUndefined(scope.theme))
{
scope.theme = 'light';
}
var modelController,
$field;
scope.data = {
focused: false,
model: undefined
};
function focusUpdate()
{
scope.data.focused = true;
scope.$apply();
}
function blurUpdate()
{
scope.data.focused = false;
scope.$apply();
}
function modelUpdate()
{
scope.data.model = modelController.$modelValue || $field.val();
}
function valueUpdate()
{
modelUpdate();
scope.$apply();
}
function updateTextareaHeight()
{
$timeout(function()
{
var tmpTextArea = angular.element('<textarea class="text-field__input">' + $field.val() + '</textarea>');
tmpTextArea.appendTo('body');
$field.css({ height: tmpTextArea[0].scrollHeight + 'px' });
tmpTextArea.remove();
});
}
transclude(function()
{
$field = element.find('textarea');
if ($field[0])
{
updateTextareaHeight();
$field.on('cut paste drop keydown', function()
{
updateTextareaHeight();
});
}
else
{
$field = element.find('input');
}
$field.addClass('text-field__input');
$field.on('focus', focusUpdate);
$field.on('blur', blurUpdate);
$field.on('propertychange change click keyup input paste', valueUpdate);
modelController = $field.data('$ngModelController');
scope.$watch(function()
{
return modelController.$modelValue;
}, modelUpdate);
});
}
};
}]);
|
JavaScript
| 0.000006 |
@@ -1887,16 +1887,57 @@
__input%22
+ style=%22width: ' + $field.width() + 'px;%22
%3E' + $fi
|
3e70dd6490f8691f39288640a7e95e4cb0c366af
|
Change server URL to openkudos.com/api without www
|
src/app/services/server.js
|
src/app/services/server.js
|
/**
* Created by vytautassugintas on 06/04/16.
*/
"use strict";
angular.module("myApp").constant("SERVER", {
"ip": "http://www.openkudos.com/api"
})
|
JavaScript
| 0 |
@@ -123,12 +123,8 @@
p://
-www.
open
|
352c53322dfd78f0acc6d1671fc84b6d7d498f19
|
correct mapping
|
app/model/Collection.js
|
app/model/Collection.js
|
Ext.define('doweown.model.Collection', {
extend: 'Ext.data.Model',
config: {
belongsTo: 'Branch',
hasMany: { model: 'ItemRecord', name: 'items', associationKey: 'itemrecord' },
hasOne: { model: 'HoldTag', name: 'holdtag', associationKey: 'holdtag' },
hasOne: { model: 'Online', name: 'online', associationKey: 'online' },
fields: [
{name: 'collectionname', type: 'string', mapping: 'collectionname'},
{name: 'callnumber', type: 'string', mapping: 'callnumber'}
]
}
});
|
JavaScript
| 0.000329 |
@@ -127,16 +127,30 @@
model: '
+doweown.model.
ItemReco
@@ -194,14 +194,9 @@
item
-record
+s
' %7D,
@@ -216,16 +216,30 @@
model: '
+doweown.model.
HoldTag'
@@ -282,16 +282,17 @@
holdtag'
+
%7D,%0A%09has
@@ -307,16 +307,30 @@
model: '
+doweown.model.
Online',
|
bd67d0b44d093410faff4b26ea2e7ba114821aae
|
Store the position metadata
|
scripts/createsearchindex.js
|
scripts/createsearchindex.js
|
console.log(" 🌙 Creating Lunr index...");
const lunr = require('lunr');
const fs = require('fs');
const data = fs.readFileSync('site/documents.json');
const documents = JSON.parse(data);
// field and document BOOST docs:
// https://github.com/olivernn/lunr.js/issues/267
const index = lunr(function() {
this.field('title', { boost: 10 });
this.field('description' , { boost: 5 });
this.field('body');
this.ref('id');
documents.forEach(function(doc) {
this.add(doc, { boost: doc.boost });
}, this)
})
const serialisedIndex = JSON.stringify(index);
fs.writeFile('site/search_index.json', serialisedIndex, (err) => {
if (err) throw err;
console.log('💾 The Lunr search index has been created -> site/search_index.json');
});
|
JavaScript
| 0.998749 |
@@ -417,16 +417,56 @@
f('id');
+%0A%09this.metadataWhitelist = %5B'position'%5D;
%0A%0A%09docum
|
cd5d1bb8bd7371b62ba783ccad074c587a8b7c82
|
Change from default delay to 800 ms (#91)
|
src/main/javascript/form/SearchRegisterenhet.js
|
src/main/javascript/form/SearchRegisterenhet.js
|
/**
* Combobox that searches from LM with type ahead.
*/
Ext.define('OpenEMap.form.SearchRegisterenhet', {
extend : 'Ext.form.field.ComboBox',
alias: 'widget.searchregisterenhet',
require: ['Ext.data.*',
'Ext.form.*'],
initComponent : function() {
var registeromrade;
var zoom;
if (this.search && this.search.options){
registeromrade = this.search.options.municipalities.join(',');
zoom = this.search.options.zoom;
}
var layer = this.mapPanel.searchLayer;
function doSearch(id) {
this.mapPanel.setLoading(true);
this.mapPanel.searchLayer.destroyFeatures();
OpenEMap.requestLM({
url: 'registerenheter/' + id + '/enhetsomraden?',
success: function(response) {
this.resultPanel.expand();
var features = new OpenLayers.Format.GeoJSON().read(response.responseText);
layer.addFeatures(features);
var extent = layer.getDataExtent();
if (zoom) {
this.mapPanel.map.setCenter(extent.getCenterLonLat(), zoom);
} else {
this.mapPanel.map.zoomToExtent(extent);
}
},
failure: function() {
Ext.Msg.alert('Fel', 'Ingen träff.');
},
callback: function() {
this.mapPanel.setLoading(false);
},
scope: this
});
}
this.store = Ext.create('Ext.data.Store', {
proxy: {
type: 'ajax',
url : OpenEMap.basePathLM + 'registerenheter',
extraParams: {
lmuser: OpenEMap.lmUser
},
reader: {
type: 'json',
root: 'features'
}
},
fields: [
{name: 'id', mapping: 'properties.objid'},
{name: 'name', mapping: 'properties.name'}
]
});
this.labelWidth = 60;
this.displayField = 'name';
this.valueField = 'id';
this.queryParam = 'q';
this.typeAhead = true;
this.forceSelection = true;
this.listeners = {
'select': function(combo, records) {
var id = records[0].get('id');
doSearch.call(this, id);
},
'beforequery': function(queryPlan) {
if (registeromrade && queryPlan.query.match(registeromrade) === null) {
queryPlan.query = registeromrade + ' ' + queryPlan.query;
}
},
scope: this
};
this.callParent(arguments);
}
});
|
JavaScript
| 0 |
@@ -240,16 +240,37 @@
rm.*'%5D,%0A
+ queryDelay: 800,%0A
init
|
ef08eb1ff593bb5383cb9162c753b50166f7c594
|
fix file sys test
|
source/controllers/filesysManager.js
|
source/controllers/filesysManager.js
|
/**
* Created by chendi on 9/3/16.
*/
var mkdirp = require('mkdirp');
var fs = require('fs');
var app = require('../../app');
var path = require ('path');
var del = require('del');
var File = require('../Models/File');
/**
* Get user file directory, if directory not exists then create one
*
* @param userID
* @return directory path
* */
var getUserDirectory = function(userID) {
var userDirPath = generateUserDirPath(userID);
if(!dirExists(userDirPath)) {
createDirectory(userDirPath);
}
return userDirPath;
};
/**
* Get the stardard path of a user directory
*
* @param userID
* @return directory path
* */
var generateUserDirPath = function(userID) {
var USER_FILE_PATH = app.get('userFiles');
return path.join(USER_FILE_PATH, userID);
};
/**
* Check if a directory exists
*
* @param directory path
* @return <boolean>
* */
var dirExists = function(userDirPath) {
try {
fs.accessSync(userDirPath, fs.F_OK, function(){});
return true;
} catch (e) {
return false;
}
};
/**
* Create directory
*
* Create directory, do nothing if directory already exists
*
* @param directory path
* @return void
* */
var createDirectory = function(path) {
mkdirp.sync(path, function(err) {
throw "Cannot create path" + err;
});
};
/**
* Create User directory
*
* Create user directory, do nothing if directory already exists
*
* @param userID
* @return void
* */
var createUserDirectory = function(userID) {
var userDirPath = generateUserDirPath(userID);
if(!dirExists(userDirPath)) {
createDirectory(userDirPath);
}
};
/**
* Remove Directory
*
* @param directory path
* @return void
* */
var removeDirectory = function(path) {
del.sync(path, function(err) {
console.log(err);
})
};
/**
* Remove User Directory
*
* Remove a user's file directory and all the files inside
*
* @param userID
* @return void
* */
var removeUserDirectory = function(userID) {
var userFileDirPath = generateUserDirPath(userID);
removeDirectory(userFileDirPath);
};
/**
* File filter
*
* @param mimeType
* @return boolean
* */
var isValidFileTypeUpload = function(mimeType) {
return mimeType == 'application/pdf' || mimeType == 'image/jpeg';
};
/**
* Save File to database
*
* @param userID
* @filepath filepath
* @return void
* */
var saveFileInfoToDatabase = function(userID, fileName, fileOriginalName, fileMimeType, filePath) {
File.create(
{
name: fileName,
mimeType: fileMimeType,
filePath: filePath,
userID: userID
}
);
};
var getAllUserFiles = function(userID) {
return File.getAllUserFiles(userID).then(function(result) {
return result;
})
};
module.exports.getUserDirectory = getUserDirectory;
module.exports.generateUserDirPath = generateUserDirPath;
module.exports.dirExists = dirExists;
module.exports.createDirectory = createDirectory;
module.exports.removeDirectory = removeDirectory;
module.exports.removeUserDirectory = removeUserDirectory;
module.exports.createUserDirectory = createUserDirectory;
module.exports.isValidFileTypeUpload = isValidFileTypeUpload;
module.exports.saveFileInfoToDatabase = saveFileInfoToDatabase;
module.exports.getAllUserFiles = getAllUserFiles;
|
JavaScript
| 0.000001 |
@@ -199,17 +199,17 @@
ire('../
-M
+m
odels/Fi
|
3cac1cad6ceee5c7f53a3a42876024251d3eb70a
|
fix bug
|
db/index.js
|
db/index.js
|
var r = require('rethinkdb');
var service = require('../Service');
r.connect({
host: 'localhost',
port: 28015,
db: 'FJCU'
}, function (err, conneciton){
if(err){
console.log(err);
process.exit();
}
global.connection = conneciton;
r.table('people').changes().run(global.connection, function (err, cursor) {
cursor.each(function (err, row) {
if(err){
console.log(err);
process.exit();
}
console.log(row);
service.emit('insertData', { data: row } );
});
});
});
|
JavaScript
| 0.000001 |
@@ -54,9 +54,9 @@
'../
-S
+s
ervi
|
64684e13cef7f67ca2b6cff46183658bfb2cd452
|
test live data v3
|
server/v1/sockets/connection.js
|
server/v1/sockets/connection.js
|
import jwt from 'jsonwebtoken';
import config from '../../../config/config';
import User from '../models/user.model';
const debug = true;
const socketConnection = (io) => {
io.on('connection', (client) => {
client.on('authenticate', async (data) => {
try {
const decoded = jwt.verify(data.token, config.jwtSecret);
if (decoded !== undefined) {
client.authenticated = true; // eslint-disable-line
// join user to a room according to his unique id
client.join(decoded.id);
// mark user as online
const user = await User.get(decoded.id);
user.online = true;
await user.save();
client.emit('authenticated', { auth: true });
io.to(user._id).emit('update_feed', {});
} else {
client.emit('authenticated', { auth: false });
}
} catch (err) {
client.emit('authenticated', { auth: false });
client.authenticated = false; // eslint-disable-line
client.disconnect(); // force disconnect not authorized client
}
});
client.on('disconnect', async () => {
try {
const user = await User.get(client.id);
user.online = false;
await user.save();
client.disconnect();
} catch (e) {
client.authenticated = false; // eslint-disable-line
client.disconnect();
}
});
});
};
const socketEmitter = (io) => {
const object = {
sendToUser(follower, post) {
io.sockets.emit('update_feed', {});
io.to(follower._id).emit('update_feed', post);
}
};
return object;
};
export { socketConnection, socketEmitter };
|
JavaScript
| 0 |
@@ -132,16 +132,34 @@
= true;%0A
+let clients = %7B%7D;%0A
const so
@@ -217,24 +217,25 @@
lient) =%3E %7B%0A
+%0A
client.o
@@ -677,32 +677,72 @@
it user.save();%0A
+ clients%5Bdecoded.id%5D = client;%0A
client
@@ -785,59 +785,8 @@
%7D);%0A
- io.to(user._id).emit('update_feed', %7B%7D);%0A
@@ -1507,69 +1507,103 @@
-io.sockets.emit('update_feed', %7B%7D);%0A io.to(follower._id)
+console.log('sendingg', follower._id);%0A const socket = clients%5Bfollower._id%5D;%0A socket
.emi
|
f94b55a274adf1d1a20089d6c1f597dc13fa7d8e
|
add the followup calls
|
app/scripts/branches.js
|
app/scripts/branches.js
|
var branches = new Vue({
el: '#branches',
data: {
payload: [],
count: 0
},
methods: {
load_branches: function(){
this.make_gh_call();
},
make_gh_call: function() {
vt = this;
auth_data = this.creds().username + ":" + this.creds().token;
jQuery.ajax
({
type: "GET",
url: "https://api.github.com/repos/" + this.creds().org + "/"+ this.creds().repo +"/branches",
dataType: 'json',
headers: {"Authorization": "Basic " + btoa(auth_data)},
success: function (data){
vt.payload = vt.buildBranches(data, vt.payload);
},
error: function() {
alert('error');
}
});
},
creds: function() {
return github_details();
},
buildBranches: function (data, payload) {
payload = [];
$.each(data, function (_, v) {
name = v.name;
isStale = '',
status = ''
payload.push({
name: name,
isStale: isStale,
status: status
});
});
return payload;
}
},
watch: {
payload: function() {
this.count = this.payload.length;
}
}
});
$(document).ready(function () {
setTimeout(function(){
branches.load_branches();
},2000);
});
|
JavaScript
| 0.000001 |
@@ -712,382 +712,1977 @@
-creds: function() %7B%0A return github_details();%0A %7D,%0A%0A buildBranches: function (data, payload) %7B%0A payload = %5B%5D;%0A $.each(data, function (_, v) %7B%0A name = v.name;%0A isStale = '',%0A status = ''%0A payload.push(%7B%0A name: name,%0A isStale: isStale,%0A status: status%0A %7D);%0A %7D);%0A return payload
+buildBranches: function (data, payload) %7B%0A vt = this;%0A payload = %5B%5D;%0A $.each(data, function (_, v) %7B%0A name = v.name;%0A isStale = '';%0A status = 'fetching';%0A branch = %7B name: name,%0A isStale: isStale,%0A status: status%0A %7D;%0A payload.push(branch);%0A vt.fetch_gh_age(branch);%0A %7D);%0A return payload;%0A %7D,%0A%0A fetch_gh_age: function(branch) %7B%0A vt = this;%0A auth_data = this.creds().username + %22:%22 + this.creds().token;%0A jQuery.ajax%0A (%7B%0A type: %22GET%22,%0A url: %22https://api.github.com/repos/%22 + this.creds().org + %22/%22+ this.creds().repo +%22/branches/%22 + branch.name,%0A dataType: 'json',%0A headers: %7B%22Authorization%22: %22Basic %22 + btoa(auth_data)%7D,%0A success: function (data)%7B%0A vt.updateStale(data, branch);%0A vt.fetch_gh_status(data, branch);%0A %7D,%0A error: function() %7B%0A alert('error');%0A %7D%0A %7D);%0A %7D,%0A%0A updateStale: function(data, branch) %7B%0A lastCommit = data.commit.commit.committer.date;%0A lastCommitDate = new Date(lastCommit);%0A today = new Date();%0A daysOld = (today - lastCommitDate) / 1000 / 60 / 60 / 24;%0A branch.isStale = daysOld %3E 14;%0A %7D,%0A%0A fetch_gh_status: function(data, branch) %7B%0A vt = this;%0A url = data.commit.url;%0A auth_data = this.creds().username + %22:%22 + this.creds().token;%0A jQuery.ajax%0A (%7B%0A type: %22GET%22,%0A url: url + %22/statuses%22,%0A dataType: 'json',%0A headers: %7B%22Authorization%22: %22Basic %22 + btoa(auth_data)%7D,%0A success: function (data)%7B%0A vt.updateStatus(data, branch);%0A %7D,%0A error: function() %7B%0A alert('error');%0A %7D%0A %7D);%0A %7D,%0A%0A updateStatus: function(data, branch) %7B%0A if(data.length %3E 0) %7B%0A branch.status = data%5B0%5D.state;%0A %7D%0A %7D,%0A%0A%0A creds: function() %7B%0A return github_details()
;%0A %7D
+,%0A
%0A %7D
|
6005497df9a6157a09fee61067b00c05842d5577
|
Allow settings to disable jshint
|
public/js/chrome/errors.js
|
public/js/chrome/errors.js
|
// (function () {
// return
//= require "../vendor/jshint/jshint"
var jshint = function () {
var source = editors.javascript.editor.getCode();
var ok = JSHINT(source);
return ok ? true : JSHINT.data();
};
var detailsSupport = 'open' in document.createElement('details');
// yeah, this is happening. Fucking IE...sheesh.
var html = $.browser.msie && $.browser.version < 9 ? '<div class="details"><div class="summary">warnings</div>' : '<details><summary class="summary">warnings</summary></details>';
var $error = $(html).appendTo('#source .javascript').hide();
$error.find('.summary').click(function () {
if (!detailsSupport) {
$(this).nextAll().toggle();
$error[0].open = !$error[0].open;
}
// trigger a resize after the click has completed and the details is close
setTimeout(function () {
$document.trigger('sizeeditors');
}, 10);
});
if (!detailsSupport) {
$error[0].open = false;
}
// modify JSHINT to only return errors that are of value (to me, for displaying)
JSHINT._data = JSHINT.data;
JSHINT.data = function (onlyErrors) {
var data = JSHINT._data(),
errors = [];
if (onlyErrors && data.errors) {
for (var i = 0; i < data.errors.length; i++) {
if (data.errors[i] !== null && data.errors[i].evidence) { // ignore JSHINT just quitting
errors.push(data.errors[i]);
} else if (data.errors[i] !== null && data.errors[i].reason.indexOf('Stopping') === 0) {
errors.push('Fatal errors, unable to continue');
}
}
return {
errors: errors
};
} else {
data.errors = [];
return data;
}
};
$error.delegate('li', 'click', function () {
var errors = JSHINT.data(true).errors;
if (errors.length) {
var i = $error.find('li').index(this);
if (errors[i].reason) {
editors.javascript.editor.setSelection({ line: errors[i].line - 1, ch: 0 }, { line: errors[i].line - 1 });
editors.javascript.editor.focus();
}
// var line = editors.javascript.nthLine(errors[0].line);
// editors.javascript.jumpToLine(line);
// editors.javascript.selectLines(line, 0, editors.javascript.nthLine(errors[0].line + 1), 0);
return false;
}
});
var checkForErrors = function () {
// exit if the javascript panel isn't visible
if (!editors.javascript.visible) return;
var hint = jshint(),
jshintErrors = JSHINT.data(true),
errors = '',
visible = $error.is(':visible');
if (hint === true && visible) {
$error.hide();
$document.trigger('sizeeditors');
} else if (jshintErrors.errors.length) {
var html = ['<ol>'],
errors = jshintErrors.errors;
for (var i = 0; i < errors.length; i++) {
if (typeof errors[i] == 'string') {
html.push(errors[i]);
} else {
html.push('Line ' + errors[i].line + ': ' + errors[i].evidence + ' --- ' + errors[i].reason);
}
}
html = html.join('<li>') + '</ol>';
$error.find('.summary').text(jshintErrors.errors.length == 1 ? '1 warning' : jshintErrors.errors.length + ' warnings');
$error.find('ol').remove();
if (!detailsSupport && $error[0].open == false) html = $(html).hide();
$error.append(html).show();
$document.trigger('sizeeditors');
}
};
$(document).bind('codeChange', throttle(checkForErrors, 1000));
$(document).bind('jsbinReady', checkForErrors);
// })();
|
JavaScript
| 0 |
@@ -3240,16 +3240,95 @@
%7D%0A%7D;%0A%0A
+if (jsbin.settings.jshint === true %7C%7C jsbin.settings.jshint === undefined) %7B%0A
$(docume
@@ -3383,16 +3383,18 @@
1000));%0A
+
$(docume
@@ -3432,16 +3432,19 @@
Errors);
+%0A%7D
%0A%0A// %7D)(
|
c0e4c54ea3085ce29b824d97750352d08637db9e
|
Use `instantiate` instead of `invoke` for controller
|
app/providers/extended-route.js
|
app/providers/extended-route.js
|
define(['require', 'app', 'angular', 'ngRoute', 'authentication'], function(require, app, angular) { 'use strict';
var baseUrl = require.toUrl('');
app.provider('extendedRoute', ["$routeProvider", function($routeProvider) {
var __when = $routeProvider.when.bind($routeProvider);
//============================================================
//
//
//============================================================
function new_when(path, route) {
var templateUrl = route.templateUrl;
var templateModule;
if(templateUrl) {
if(templateUrl.indexOf('/')!==0) {
route.templateUrl = baseUrl + templateUrl;
templateModule = changeExtension(templateUrl, '');
}
else {
templateModule = changeExtension(templateUrl, '.js');
}
}
var ext = { resolve: route.resolve || {} };
if(!route.controller && route.resolveController && typeof(route.resolveController)=="string")
templateModule = route.resolveController;
if(!route.controller && route.resolveController) {
ext.controller = proxy;
ext.resolve.controller = resolveController(templateModule);
}
if(route.resolveUser) {
ext.resolve.user = resolveUser();
}
return __when(path, angular.extend(route, ext));
}
//********************************************************************************
//********************************************************************************
//********************************************************************************
//********************************************************************************
function changeExtension(path, ext) {
return path.replace(/(\.[a-z0-9]+$)/gi, ext);
}
//============================================================
//
//
//============================================================
function proxy($injector, $scope, $route, controller) {
if(!controller)
return;
var locals = angular.extend($route.current.locals, { $scope: $scope });
return $injector.invoke(controller, undefined, locals);
}
proxy.$inject = ['$injector', '$scope', '$route', 'controller'];
//============================================================
//
//
//============================================================
function resolveUser() {
return ['$q', '$rootScope', 'authentication', function($q, $rootScope, authentication) {
return $q.when(authentication.getUser()).then(function (user) {
$rootScope.user = user;
return user;
});
}];
}
//============================================================
//
//
//============================================================
function resolveController(controllerModule) {
return ['$q', function($q) {
var deferred = $q.defer();
require([controllerModule], function (module) {
deferred.resolve(module);
}, function(){
deferred.reject("controller not found: " + controllerModule);
});
return deferred.promise;
}];
}
return angular.extend($routeProvider, { when: new_when });
}]);
});
|
JavaScript
| 0.000001 |
@@ -2426,11 +2426,16 @@
r.in
-vok
+stantiat
e(co
@@ -2447,19 +2447,8 @@
ler,
- undefined,
loc
|
40ec1ae7d5c2c29f608c96b31595ac90669b374c
|
Fix RadioButton depth
|
public/js/object/button.js
|
public/js/object/button.js
|
/**
Constructor for Button
@constructor
*/
var ButtonObject = function()
{
//Call the parent constructor!!!!
RealObject.call(this);
//Add a property "font" and "text" to button
this.font = "18px Arial";
this.text = "";
this.checkForInput = true;
//Let's override the method "update"
//Even though the update in RealObject is exactly same
this.update = function()
{
//Call this to update the bounding box of the object
//Otherwise, the object would be unclickable
this.updateRealObject();
}
//Declare a new method called setText
//so we can change the button text
this.setText = function(text)
{
//Temporarily change the canvas' font
context.font = this.font;
//context.measureText(text) gets the approximate
//width of the button text
var width = context.measureText(text).width;
//Our button size will be that width plus some extra
this.size.x = width+25;
//Nice hardcoded height
this.size.y = 32;
this.text = text;
}
//Override the draw function a bit
this.draw = function()
{
context.lineWidth = 2;
//Set the current drawing font
context.font = this.font;
//this.mouseHover is set by the Engine
//if the mouse is over the object
if (this.mouseHover) //if mouse.hover
context.fillStyle = "#AAAAAA"; //use some darker background
else
context.fillStyle = "#FFFFFF";
//Fill the area from position to position+size
context.fillRect(this.position.x, this.position.y, this.size.x, this.size.y);
//Stroke a nice shadow
context.strokeStyle = "#888888";
context.strokeRect(this.position.x, this.position.y, this.size.x-2, this.size.y-2);
//Stroke dat edges 2
context.strokeStyle = "#000000";
context.strokeRect(this.position.x, this.position.y, this.size.x, this.size.y);
//Change color to black
context.fillStyle = "#000000";
//And print our text
context.fillText(this.text,this.position.x+10,this.position.y+22);
}
//Override this in instantiation to
//do some cool stuff
this.onClick = function()
{
alert("ERROR: No button action!!!")
}
}
//The "inheritance"
ButtonObject.prototype = new RealObject();
//The constructor assignment
ButtonObject.constructor = ButtonObject;
var InvisibleButton = function()
{
this.draw = function()
{
}
}
//The "inheritance"
InvisibleButton.prototype = new ButtonObject();
//The constructor assignment
InvisibleButton.constructor = InvisibleButton;
var RadioButton = function(pos, buttonnumber)
{
this.selected = false;
this.value = 0;
this.position = pos;
this.size = new Vector2(48, 48);
this.font = "18px Arial";
this.text = this.value;
this.depth = 1000;
this.buttonnumber = buttonnumber;
this.inputContext += Context.map["gameCalculationScreen"];
this.drawContext += Context.map["gameCalculationScreen"];
this.checkForInput = true;
this.setText = function(text)
{
//Temporarily change the canvas' font
context.font = this.font;
//context.measureText(text) gets the approximate
//width of the button text
var width = context.measureText(text).width;
//Our button size will be that width plus some extra
this.size.x = width+25;
//Nice hardcoded height
this.size.y = 32;
this.text = text;
}
this.draw = function()
{
context.lineWidth = 2;
//Set the current drawing font
context.font = this.font;
//this.mouseHover is set by the Engine
//if the mouse is over the object
if (this.mouseHover || this.selected) //if mouse.hover or button selected
context.fillStyle = "#AAAAAA"; //use some darker background
else
context.fillStyle = "#FFFFFF";
//Fill the area from position to position+size
context.fillRect(this.position.x, this.position.y, this.size.x, this.size.y);
//Stroke a nice shadow
context.strokeStyle = "#888888";
context.strokeRect(this.position.x, this.position.y, this.size.x-2, this.size.y-2);
//Stroke dat edges 2
context.strokeStyle = "#000000";
context.strokeRect(this.position.x, this.position.y, this.size.x, this.size.y);
//Change color to black
context.fillStyle = "#000000";
//And print our text
context.fillText(this.text,this.position.x+10,this.position.y+22);
}
this.update = function()
{
this.updateRealObject();
}
this.onClick = function()
{
this.selected = true;
RadioButtons.checkForSelections(this.buttonnumber);
}
}
RadioButton.prototype = new ButtonObject();
RadioButton.constructor = RadioButton;
var RadioButtons =
{
buttons : [],
buttonsAmount : 4,
position : new Vector2(1235, 232),
size : new Vector2(1,1),
depth : 0,
changeButtonValues : function(values)
{
for(var i = 0; i < this.buttonsAmount; i++)
{
this.buttons[i].value = values[i];
this.buttons[i].setText(values[i]);
}
this.reSize();
},
reSize : function()
{
if(this.buttons[0])
this.size = new Vector2(this.buttons[0].size.x, this.buttons[0].size.y + this.buttonsAmount * 20);
},
generateButtons : function()
{
for(var i = 0; i < this.buttonsAmount; i++)
{
this.buttons.push(new RadioButton(new Vector2(this.position.x, this.position.y + i * 50), i));
}
for(var i = 0; i < this.buttonsAmount; i++)
Engine.addObject(this.buttons[i]);
},
checkForSelections : function(num)
{
for(var i = 0; i < this.buttonsAmount; i++)
{
if(this.buttons[i].selected && this.buttons[i].buttonnumber != num)
{
this.buttons[i].selected = false;
}
}
},
update : function()
{
},
draw : function()
{
},
}
|
JavaScript
| 0.000001 |
@@ -2679,18 +2679,17 @@
depth =
-10
+5
00;%0A
|
0dd45088f4dbbca490df2b073712c5da0cc41708
|
configure gulp tasks
|
gulpfile.js
|
gulpfile.js
|
JavaScript
| 0.000034 |
@@ -0,0 +1,1893 @@
+var gulp = require('gulp');%0Avar gutil = require('gulp-util')%0Avar uglify = require('gulp-uglify');%0Avar concat = require('gulp-concat');%0Avar browserify = require('browserify');%0Avar reactify = require('reactify');%0Avar watchify = require('watchify');%0Avar nodemon = require('gulp-nodemon');%0Avar del = require('del');%0Avar rename = require('gulp-rename');%0Avar sourcemaps = require('gulp-sourcemaps');%0Avar source = require('vinyl-source-stream');%0Avar buffer = require('vinyl-buffer');%0A%0Agulp.paths = %7B%0A app: 'app',%0A builds: 'assets/dist',%0A test: 'test'%0A%7D;%0A%0Agulp.task('clean', function() %7B%0A del(%5B'assets/dist/*.js', 'assets/dist/*.css'%5D).then(function() %7B%0A console.log(%22removed previous build%22);%0A %7D);%0A%7D);%0A%0Agulp.task('join', function() %7B%0A return gulp.src(%5B'app/components/*.js', 'app/app.js'%5D)%0A .pipe(sourcemaps.init())%0A .pipe(concat('app.js'))%0A .pipe(gulp.dest(gulp.paths.builds));%0A%7D);%0A%0Agulp.task('build', %5B'join'%5D, function() %7B%0A%0A var bundler = browserify(%7B%0A entries: %5Bgulp.paths.builds + '/app.js'%5D,%0A transform: %5Breactify%5D,%0A debug: true,%0A cache: %7B%7D,%0A packageCache: %7B%7D,%0A fullPaths: true%0A %7D);%0A bundler.external('react');%0A%0A return watchify(bundler)%0A .bundle()%0A .pipe(source('main.js'))%0A .pipe(buffer())%0A .pipe(sourcemaps.init())%0A .pipe(uglify())%0A .pipe(rename(%7B%0A extname: '.min.js'%0A %7D))%0A .pipe(sourcemaps.write())%0A .pipe(gulp.dest(gulp.paths.builds));%0A%7D);%0A%0A%0Agulp.task('nodemon', %5B'join', 'build'%5D, function() %7B%0A nodemon(%7B%0A script: 'server.js',%0A ext: 'js',%0A ignore: %5B'.package.json'%5D%0A %7D)%0A .on('restart', function() %7B%0A console.log('server restarted');%0A %7D);%0A%7D);%0A%0Agulp.task('watch', function() %7B%0A gulp.watch(gulp.paths.app+ '/**/*.js', %5B'clean', 'join', 'build', 'nodemon'%5D);%0A%7D);%0A%0A%0Agulp.task('default', %5B'clean', 'join', 'build', 'nodemon'%5D, function() %7B%0A gulp.start('watch');%0A%7D);%0A%0Amodule.exports = gulp;%0A
|
|
d23ffd0c9bf7c389d425db1295487bf85f0ad2bd
|
Add missing task dependencies.
|
gulpfile.js
|
gulpfile.js
|
/* global __dirname */
(function (pkg, gulp, jshint, jscs, stylish, mocha, connect, less, requirejs, uglify, replace, header, yargs, rimraf, mkdirp, recursive) {
'use strict';
var environment = yargs.argv.env || 'development',
headerTemplate =
'/**\n' +
' * ${pkg.name}\n' +
' * ${pkg.description}\n' +
' * \n' +
' * @version ${pkg.version}\n' +
' * @link ${pkg.homepage}\n' +
' * @license ${pkg.license}\n' +
' */\n\n';
gulp.task(
'qa:lint',
function () {
return gulp
.src([
'*.js',
'public/app/**/*.js',
'test/**/*.js'
])
.pipe(jshint())
.pipe(jscs())
.pipe(stylish.combineWithHintResults())
.pipe(jshint.reporter('jshint-stylish'));
}
);
gulp.task(
'qa:test',
[
'qa:lint'
],
function () {
return gulp
.src('test/runner.html')
.pipe(mocha());
}
);
gulp.task(
'qa',
[
'qa:lint',
'qa:test'
]
);
gulp.task(
'build:clean',
function (callback) {
rimraf('public/css', callback);
}
);
gulp.task(
'build:less',
function () {
return gulp
.src('public/less/main.less')
.pipe(less({
paths: [ 'public/less' ]
}))
.pipe(gulp.dest('public/css'));
}
);
gulp.task(
'build',
[
'build:clean',
'build:less'
]
);
gulp.task(
'package:clean',
function (callback) {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
rimraf('dist/' + environment, function () {
mkdirp('dist/' + environment, callback);
});
}
);
gulp.task(
'package:less',
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/less/main.less')
.pipe(less({
paths: [ 'public/less' ],
optimize: true
}))
.pipe(gulp.dest('dist/' + environment));
}
);
gulp.task(
'package:javascript',
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
// Dynamically generate the `include` list, because most of the modules are dynamically `require`d.
recursive('public/app', function (err, files) {
return gulp
.src('public/app/main.js')
.pipe(requirejs({
mainConfigFile: 'public/app/main.js',
name: '../lib/requirejs/require',
optimize: 'none',
out: 'application.js',
include: files.map(function (file) {
// Strip common path prefix; return .js files without extension, and others via text plugin.
file = file.replace(/^public\/app\//, '');
return file.match(/\.js$/) ? file.replace(/\.js$/, '') : 'text!' + file;
})
}))
.pipe(replace(/var environment = 'development';/g, 'var environment = "' + environment + '";'))
.pipe(uglify())
.pipe(header(headerTemplate, { pkg: pkg }))
.pipe(gulp.dest('dist/' + environment));
});
}
);
gulp.task(
'package:html',
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/index.html')
.pipe(replace(/src="\/lib\/requirejs\/require\.js"/g, 'src="/application.js"'))
.pipe(replace(/href="\/css\/main\.css"/g, 'href="/main.css"'))
.pipe(gulp.dest('dist/' + environment));
}
);
gulp.task(
'package:images',
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/images/**/*')
.pipe(gulp.dest('dist/' + environment + '/images'));
}
);
gulp.task(
'package',
[
'package:clean',
'package:less',
'package:javascript',
'package:html',
'package:images'
]
);
gulp.task(
'server',
function () {
connect.server({
port: 8888,
root: 'public',
fallback: 'public/index.html'
});
}
);
gulp.task(
'dist-server',
function () {
connect.server({
port: 8889,
root: 'dist/' + environment,
fallback: 'dist/' + environment + '/index.html'
});
}
);
gulp.task(
'watch:qa',
function () {
return gulp
.watch(
[
'*.js',
'public/app/**',
'test/**/*.js'
],
[
'qa'
]
);
}
);
gulp.task(
'watch:less',
function () {
return gulp
.watch(
[
'public/less/**/*.less',
'public/app/ui/**/*.less'
],
[
'build:less'
]
);
}
);
gulp.task(
'watch',
[
'watch:qa',
'watch:less'
]
);
gulp.task(
'default',
[
'qa',
'build',
'watch'
]
);
}(
require('./package.json'),
require('gulp'),
require('gulp-jshint'),
require('gulp-jscs'),
require('gulp-jscs-stylish'),
require('gulp-mocha-phantomjs'),
require('gulp-connect'),
require('gulp-less'),
require('gulp-requirejs-optimize'),
require('gulp-uglify'),
require('gulp-replace'),
require('gulp-header'),
require('yargs'),
require('rimraf'),
require('mkdirp'),
require('recursive-readdir')
));
|
JavaScript
| 0.000001 |
@@ -1425,32 +1425,79 @@
'build:less',%0A
+ %5B%0A 'build:clean'%0A %5D,%0A
function
@@ -1494,32 +1494,32 @@
function () %7B%0A
-
retu
@@ -2245,32 +2245,81 @@
'package:less',%0A
+ %5B%0A 'package:clean'%0A %5D,%0A
function
@@ -2789,32 +2789,81 @@
ge:javascript',%0A
+ %5B%0A 'package:clean'%0A %5D,%0A
function
@@ -4262,32 +4262,81 @@
'package:html',%0A
+ %5B%0A 'package:clean'%0A %5D,%0A
function
@@ -4817,32 +4817,32 @@
%0A gulp.task(%0A
-
'package
@@ -4847,24 +4847,73 @@
ge:images',%0A
+ %5B%0A 'package:clean'%0A %5D,%0A
func
|
5ca38c66f6391c9f09123bd742ce1d365a04a985
|
create the 'test' task
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp')
|
JavaScript
| 1 |
@@ -20,8 +20,139 @@
'gulp')%0A
+var mocha = require('gulp-mocha')%0A%0Agulp.task('test', function () %7B%0A gulp.src('./tests/connect-sequence.spec.js').pipe(mocha())%0A%7D)%0A
|
52d6463f2c1473198c3c554bf7d84848581ca760
|
Tag releases
|
gulpfile.js
|
gulpfile.js
|
/*
* Copyright 2015 The Closure Compiler Authors.
*
* 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.
*/
/**
* @fileoverview Build process for closure-compiler-npm package
*
* Since the package doesn't require building, this file runs
* tests and auto-increments the version number. Auto-increment
* is used to support continuous delivery.
*
* @author Chad Killingsworth ([email protected])
*/
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var mocha = require('gulp-mocha');
var git = require('simple-git')(__dirname);
var Semver = require('semver');
var fs = require('fs');
var packageInfo = require('./package.json');
var currentVer = new Semver(packageInfo.version);
gulp.task('test', function() {
return gulp.src('./test/**.js', {read: false})
.pipe(mocha());
});
gulp.task('default', ['test']);
/**
* Check the git diff for package.json to return whether it included
* a change to the version number.
* @return {Promise<boolean>}
*/
var didLastCommitChangeVersionNumber = function() {
return new Promise(function (resolve, reject) {
git.diff(['HEAD^', 'HEAD', 'package.json'], function(err, data) {
if (err) {
return reject(err);
}
var versionData = (data || '').match(/^[+-]\s*"version": "[^"]+",$/mg);
var versionChanged = versionData === null ? false : versionData.length === 2;
return resolve(versionChanged);
});
});
};
/**
* If the previous commit didn't include a version number change,
* calculate what the new version should be.
*
* @param {boolean} alreadyChanged
* @returns {Promise<Semver>}
*/
var getNextVersionNumber = function(alreadyChanged) {
return new Promise(function(resolve, reject) {
if (alreadyChanged) {
gutil.log('Most recent commit incremented version number. No changes needed.');
return resolve(currentVer);
}
var Compiler = require('./lib/node/closure-compiler');
var compiler = new Compiler({version: true});
compiler.run(function(code, data, err) {
if (code !== 0) {
return reject(new Error('Non-zero exit code: ' + code));
}
var versionNum = (data || '').match(/Version:\sv(.*)$/m);
if (versionNum.length !== 2) {
return resolve(new Error('Unable to parse compiler version number'));
}
var compilerVer = new Semver(versionNum[1] + '.0.0');
if (compilerVer.compare(currentVer) > 0) {
gutil.log('New compiler version detected. Increment major version.');
return resolve(compilerVer);
}
var nextVersion = new Semver(packageInfo.version);
nextVersion.inc('minor');
gutil.log('Changes detected. Increment minor version.');
return resolve(nextVersion);
});
});
};
/**
* Given a semver object, update package.json (if needed) to the
* new version number. If changed, add and commit package.json.
*
* @param {Semver} newVersion
* @returns {Promise<boolean>}
*/
var updatePackageToNewVersion = function(newVersion) {
return new Promise(function(resolve, reject) {
if (currentVer.compare(newVersion) >= 0) {
return resolve(false);
}
packageInfo.version = newVersion.version;
fs.writeFileSync('./package.json', JSON.stringify(packageInfo, null, 2) + '\n');
git.add('package.json', function(err, data) {})
.commit('Increment version number to ' + newVersion.version, function(err, data) {
gutil.log('New version committed: ' + newVersion.version);
return resolve(true);
});
});
};
/**
* Task to determine whether a bump in the version number is needed.
* This task is intended to be called by a continuous integration system
* that will auto-push any changes back to the main repository.
*/
gulp.task('release-if-changed', function(callback) {
var nodeVersion = new Semver(process.version);
if (nodeVersion.compare(new Semver('5.0.0')) < 0) {
return callback();
}
didLastCommitChangeVersionNumber()
.then(getNextVersionNumber)
.then(updatePackageToNewVersion)
.catch(function(err) {
throw err;
});
});
|
JavaScript
| 0 |
@@ -3922,32 +3922,83 @@
ction(err, data)
+ %7B%7D)%0A .addTag(newVersion.version, function()
%7B%0A gut
|
b5214d1ca91ac14c9700ff7ad35276d7ed33e59e
|
Modify loadUsers.js script - now registers users and reset passwords
|
scripts/zen-etl/loadUsers.js
|
scripts/zen-etl/loadUsers.js
|
'use strict'
var fs = require('fs');
var seneca = require('seneca')();
var async = require('async');
var dojos = JSON.parse(fs.readFileSync('./data/users.json', 'utf8'));
var plugin = "load-users";
var config = require('config');
var ENTITY_NS = "cd/users";
seneca.use('mongo-store', config.db)
seneca.ready(function() {
seneca.add({ role: plugin, cmd: 'insert' }, function (args, done) {
function createUser(user, cb){
seneca.make$(ENTITY_NS).save$(user, function(err, response) {
if(err){
return cb(err);
}
return cb(null, response);
});
}
var loadUsers = function (done) {
async.eachSeries(dojos, createUser , done);
};
async.series([
loadUsers
], done);
});
seneca.act({ role: plugin, cmd: 'insert', timeout: false }, function(err){
if(err){
throw err;
} else{
console.log("complete");
}
});
});
|
JavaScript
| 0 |
@@ -100,20 +100,20 @@
);%0A%0Avar
-dojo
+user
s = JSON
@@ -148,16 +148,21 @@
ta/users
+-test
.json',
@@ -255,16 +255,21 @@
cd/users
+-test
%22;%0A%0Asene
@@ -300,16 +300,36 @@
nfig.db)
+%0Aseneca.use('user');
%0A%0Aseneca
@@ -348,16 +348,109 @@
ion() %7B%0A
+ var userpin = seneca.pin(%7Brole:'user',cmd:'*'%7D);%0A var userent = seneca.make('sys/user');%0A%0A
seneca
@@ -476,22 +476,30 @@
, cmd: '
-insert
+register-users
' %7D, fun
@@ -533,22 +533,24 @@
unction
-c
re
-a
+gis
te
+r
User(use
@@ -567,37 +567,106 @@
-seneca.make$(ENTITY_NS).save$
+console.log(%22registering %25s%22, user.email);%0A user.name = user.username;%0A userpin.register
(use
@@ -686,18 +686,12 @@
rr,
-response)
+out)
%7B%0A
@@ -736,26 +736,34 @@
);%0A %7D
-%0A%0A
+ else %7B%0A
retu
@@ -778,72 +778,601 @@
ll,
-response);%0A %7D);%0A %7D%0A%0A var loadUsers = function
+out.ok);%0A %7D%0A %7D);%0A %7D%0A%0A function resetUser(user, cb)%7B%0A console.log(%22resetting %25s%22, user.email);%0A userpin.create_reset(%7Bemail: user.email%7D, function(err, out)%7B%0A if(err)%7B%0A return cb(err);%0A %7D else %7B%0A userpin.execute_reset(%7B%0A token: out.reset.id,%0A password: %22a%22,%0A repeat: %22a%22%0A %7D, function(err, out)%7B%0A if(err)%7B%0A return cb(err);%0A %7D else %7B%0A return cb(null, out.ok);%0A %7D%0A %7D)%0A %7D%0A%0A %7D)%0A %7D%0A%0A function registerUsers
(done)
-
%7B%0A
@@ -1396,26 +1396,27 @@
ies(
-dojo
+user
s,
-c
re
-a
+gis
te
+r
User
-
, do
@@ -1429,50 +1429,199 @@
%7D
-;
%0A%0A
-async.series(%5B%0A loadUsers%0A
+function resetUsers(done)%7B%0A %0A userent.list$(function(err, users)%7B%0A async.eachSeries(users, resetUser, done);%0A %7D)%0A %7D%0A%0A async.series(%5BregisterUsers, resetUsers
%5D, d
@@ -1630,16 +1630,16 @@
e);%0A
-%0A
%7D);%0A%0A
+%0A
se
@@ -1673,14 +1673,22 @@
d: '
-insert
+register-users
', t
@@ -1700,19 +1700,22 @@
t: false
-
%7D,
+%0A
functio
@@ -1722,24 +1722,26 @@
n(err)%7B%0A
+
if(err)%7B%0A
@@ -1733,24 +1733,26 @@
if(err)%7B%0A
+
throw
@@ -1764,16 +1764,18 @@
+
%7D else%7B%0A
@@ -1770,16 +1770,18 @@
%7D else%7B%0A
+
co
@@ -1811,22 +1811,22 @@
+
%7D %0A
+
%7D);%0A
- %0A
%7D);
-%0A
|
483240a7a11e1b9cb6d62a99d834d5abb3f00e4a
|
Make the chart move constantly
|
public/scripts/chart.js
|
public/scripts/chart.js
|
define(['chart-pings'], function(pings) {
var element = d3.select('#chart').append('svg:svg')
var elementWidth = parseInt(element.style('width'))
var elementHeight = parseInt(element.style('height'))
var maxPing = 5000 // TODO DRY
var yScale = d3.scale.linear().domain([0, maxPing]).range([0, elementHeight])
// TODO It is not displayed correctly if results in a float
var barWidth = elementWidth / pings.max()
var selections = (function() {
var enter, update, exit
return {
entered: function() { return enter },
updated: function() { return update },
exited: function() { return exit },
update: function() {
update = element.selectAll('rect')
.data(pings.all(), function(ping, i) { return ping.start() })
enter = update.enter().append('svg:rect')
exit = update.exit()
}
}
})()
selections.update()
setInterval(function() {
var updated = selections.updated()
updated
.attr('x', function(ping, i) { return i * barWidth })
.attr('y', function(ping) { return yScale(maxPing - ping.lag()) })
.attr('height', function(ping) { return yScale(ping.lag()) })
.style('fill-opacity', function(ping) { return ping.end() ? 1 : 0.7 })
}, 50)
return {
addPing: function() {
var ping = pings.add()
selections.update()
var entered = selections.entered()
entered.attr('width', barWidth)
selections.exited().remove()
return ping
}
}
})
|
JavaScript
| 0.000009 |
@@ -241,16 +241,55 @@
TODO DRY
+%0A var pingInterval = 500 // TODO DRY
%0A%0A va
@@ -363,16 +363,76 @@
Height%5D)
+%0A var xScale = d3.scale.linear().range(%5B0, elementWidth%5D)
%0A%0A //
@@ -592,16 +592,18 @@
nter
+ed
, update
, ex
@@ -602,14 +602,17 @@
date
+d
, exit
+ed
%0A
@@ -671,16 +671,18 @@
rn enter
+ed
%7D,%0A
@@ -724,16 +724,17 @@
n update
+d
%7D,%0A
@@ -773,16 +773,18 @@
urn exit
+ed
%7D,%0A
@@ -834,16 +834,17 @@
update
+d
= eleme
@@ -967,16 +967,18 @@
enter
+ed
= updat
@@ -982,16 +982,17 @@
date
+d
.enter()
.app
@@ -991,27 +991,8 @@
er()
-.append('svg:rect')
%0A
@@ -1008,16 +1008,18 @@
exit
+ed
= updat
@@ -1019,16 +1019,17 @@
= update
+d
.exit()%0A
@@ -1086,20 +1086,16 @@
pdate()%0A
-
%0A set
@@ -1120,29 +1120,16 @@
) %7B%0A
-
+%0A
-var updated =
sel
@@ -1150,90 +1150,8 @@
d()%0A
- updated%0A .attr('x', function(ping, i) %7B return i * barWidth %7D)%0A
@@ -1386,16 +1386,294 @@
%7D)%0A
+%0A var now = new Date().getTime()%0A xScale.domain(%5Bnow - pings.max() * pingInterval, now%5D)%0A ;%5Bselections.updated(), selections.exited()%5D.forEach(function(selection) %7B%0A selection.attr('x', function(ping) %7B return xScale(ping.start()) %7D)%0A %7D)%0A%0A
%7D,
-5
+6
0)%0A%0A
@@ -1800,22 +1800,8 @@
- var entered =
sel
@@ -1813,24 +1813,43 @@
ns.entered()
+.append('svg:rect')
%0A
@@ -1849,23 +1849,20 @@
-entered
+
.attr('w
@@ -1910,16 +1910,98 @@
exited()
+.transition()%0A .duration(pingInterval) // TODO DRY%0A
.remove(
|
07bc10fa503513bd49014d8c9c5df424bd2a5c9b
|
Update sass task options
|
gulpfile.js
|
gulpfile.js
|
var browsersync = require('browser-sync');
var reload = browsersync.reload;
var gulp = require('gulp');
var runSequence = require('run-sequence');
var pngquant = require('imagemin-pngquant');
var pkg = require( process.cwd() + '/package.json');
var autoprefixerBrowsers = ['> 1%', 'last 2 versions'];
var headerBanner = [
'/*!',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @author <%= pkg.author %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('browserify', function(){
return require(process.cwd() + '/lib/browserify')({
bundleName: "bundle.js",
src: './sandbox/src/browserify/main.js',
dest: './sandbox/build/browserify',
});
});
gulp.task('rubysass', function(){
return require(process.cwd() + '/lib/rubysass')({
src: './sandbox/src/scss/sass.scss',
dest: './sandbox/build/rubysass/',
rubySassOptions: {
sourcemap: true,
noCache: true,
},
autoprefixer: autoprefixerBrowsers,
fallback:{
use:true,
colorHexOptions:{rgba: true}
},
filter:'**/*.css',
headerBanner : true,
banner:headerBanner,
pkg: pkg,
notify :"Compiled RubySass"
});
});
gulp.task('cssmin', function(){
return require(process.cwd() + '/lib/cssmin')({
src: './sandbox/build/**/*.css',
dest: './sandbox/build/cssmin/'
});
});
gulp.task('csslint', function(){
return require(process.cwd() + '/lib/csslint')({
// csslint: './.csslintrc',
src: './sandbox/build/**/*.css',
});
});
gulp.task('concat', function(){
return require(process.cwd() + '/lib/concat')({
src: './sandbox/src/js/*.js',
dest: './sandbox/build/js',
name: 'concat.js'
});
});
gulp.task('jsmin', function(){
return require(process.cwd() + '/lib/jsmin')({
src: './sandbox/src/js/concat.js',
dest: './sandbox/build/js/'
});
});
gulp.task('jshint', function(){
return require(process.cwd() + '/lib/jshint')({
// jshintPath: './.jshintrc',
src: './sandbox/build/js/concat.js'
});
});
gulp.task('image', function(){
return require(process.cwd() + '/lib/image')({
src: './sandbox/src/images/**/*',
dest: './sandbox/build/images',
options:{
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}
});
});
gulp.task('svg2png', function(){
return require(process.cwd() + '/lib/svg2png')({
src: './sandbox/src/images/**/*.svg',
dest: './sandbox/src/images'
});
});
gulp.task('iconfont', function(){
return require(process.cwd() + '/lib/iconfont')({
name: 'icon',
svgSrc: './sandbox/src/icon/svg/*.svg',
cssSrc: './sandbox/src/icon/css/template.css',
cssDest: './sandbox/build/icon/css',
fontPath: '../font/',
dest: './sandbox/build/icon/font'
});
});
gulp.task('sftp', function(){
return require(process.cwd() + '/lib/sftp')({
src:'production',
options: {
host: 'example.com',
port: '22',
user: 'user_name',
pass: '1234',
remotePath: ''
}
});
});
gulp.task('banner', function(){
return require(process.cwd() + '/lib/banner')({
src: './sandbox/build/js/concat.js',
dest: './sandbox/build/js/banner',
pkg: pkg,
banner:headerBanner
});
});
gulp.task('bump', function(){
return require(process.cwd() + '/lib/bump')({
version: pkg.version,
src: './bower.json',
dest: '.'
});
});
gulp.task('uninstall', function(){
return require(process.cwd() + '/lib/uninstall')({
files:[
"./sandbox/build"
]
});
});
gulp.task('browsersync', function(){
browsersync({
server: "./sandbox",
});
});
gulp.task('default',['browsersync'], function(){
gulp.watch(['./sandbox/src/scss/*.scss'], ['rubysass']);
gulp.watch(['./sandbox/src/browserify/*.js'], ['browserify']);
gulp.watch("./sandbox/build/*/*.{css,js}").on('change', reload);
});
gulp.task('build', function(){
runSequence(
'uninstall',
'browserify',
'rubysass',
'concat',
['cssmin','jsmin','svg2png'],
'image',
'banner',
'jshint',
// 'csslint',
'iconfont'
);
});
|
JavaScript
| 0.000001 |
@@ -784,20 +784,16 @@
p.task('
-ruby
sass', f
@@ -842,20 +842,16 @@
+ '/lib/
-ruby
sass')(%7B
@@ -919,20 +919,16 @@
x/build/
-ruby
sass/',%0A
@@ -939,23 +939,16 @@
rubySass
-Options
: %7B%0A
@@ -1002,68 +1002,98 @@
-autoprefixer: autoprefixerBrowsers,%0A fallback:%7B
+fallback:%7B%0A autoprefixer: %5B'%3E 1%25', 'last 2 versions'%5D,%0A opacity:true,
%0A
-use
+rgba
:tru
@@ -1105,36 +1105,19 @@
-colorHexOptions:%7Brgba:
+pixrem:
true
-%7D
%0A
@@ -1128,63 +1128,33 @@
-filter:'**/*.css',%0A headerB
+b
anner
-
:
-true,%0A banner:
+%7B%0A content:
head
@@ -1163,32 +1163,34 @@
Banner,%0A
+
pkg: pkg
,%0A notify
@@ -1181,41 +1181,14 @@
pkg
-,
%0A
-notify :%22Compiled RubySass%22
+%7D
%0A %7D
@@ -3283,164 +3283,8 @@
;%0A%0A%0A
-gulp.task('bump', function()%7B%0A return require(process.cwd() + '/lib/bump')(%7B%0A version: pkg.version,%0A src: './bower.json',%0A dest: '.'%0A %7D);%0A%7D);%0A%0A%0A
gulp
|
7fefb1afd657b69345487c8a2d81a3d14afb7042
|
Update beta flag
|
js/consts.js
|
js/consts.js
|
var consts = {};
consts.isBeta = false;
|
JavaScript
| 0 |
@@ -31,10 +31,9 @@
a =
-fals
+tru
e;
|
e04e87dfc09668b15e4acddf3ffdb22f7bb7f40b
|
add missing prop doc for "cookieExpiration"
|
src/CookieBanner.js
|
src/CookieBanner.js
|
import React from 'react';
import cx from 'classnames';
import omit from 'lodash.omit';
import { t, props } from 'tcomb-react';
import { cookie as cookieLite } from 'browser-cookie-lite';
import styleUtils from './styleUtils';
t.interface.strict = true;
const Props = {
children: t.maybe(t.ReactChildren),
message: t.maybe(t.String),
onAccept: t.maybe(t.Function),
link: t.maybe(t.interface({
msg: t.maybe(t.String),
url: t.String,
target: t.maybe(t.enums.of(['_blank', '_self', '_parent', '_top', 'framename']))
})),
buttonMessage: t.maybe(t.String),
cookie: t.maybe(t.String),
cookieExpiration: t.maybe(t.union([
t.Integer,
t.interface({
years: t.maybe(t.Number),
days: t.maybe(t.Number),
hours: t.maybe(t.Number)
})
])),
dismissOnScroll: t.maybe(t.Boolean),
dismissOnScrollThreshold: t.maybe(t.Number),
closeIcon: t.maybe(t.String),
disableStyle: t.maybe(t.Boolean),
styles: t.maybe(t.Object),
className: t.maybe(t.String)
};
/** React Cookie banner dismissable with just a scroll!
* @param children - custom component rendered if user has not accepted cookies
* @param message - message written inside default cookie banner
* @param onAccept - called when user accepts cookies
* @param link - object with infos used to render a link to your cookie-policy page
* @param buttonMessage - message written inside the button of the default cookie banner
* @param cookie - cookie-key used to save user's decision about you cookie-policy
* @param dismissOnScroll - wheter the cookie banner should be dismissed on scroll or not
* @param dismissOnScrollThreshold - amount of pixel the user need to scroll to dismiss the cookie banner
* @param closeIcon - className passed to close-icon
* @param disableStyle - pass `true` if you want to disable default style
* @param styles - object with custom styles used to overwrite default ones
*/
@props(Props, { strict: false })
export default class CookieBanner extends React.Component {
static defaultProps = {
onAccept: () => {},
dismissOnScroll: true,
cookie: 'accepts-cookies',
cookieExpiration: { years: 1 },
buttonMessage: 'Got it',
dismissOnScrollThreshold: 0,
styles: {}
};
state = { listeningScroll: false }
componentDidMount() {
this.addOnScrollListener();
}
addOnScrollListener = (props) => {
props = props || this.props;
if (!this.state.listeningScroll && !this.hasAcceptedCookies() && props.dismissOnScroll) {
if (window.attachEvent) {
//Internet Explorer
window.attachEvent('onscroll', this.onScroll);
} else if(window.addEventListener) {
window.addEventListener('scroll', this.onScroll, false);
}
this.setState({ listeningScroll: true });
}
}
removeOnScrollListener = () => {
if (this.state.listeningScroll) {
if (window.detachEvent) {
//Internet Explorer
window.detachEvent('onscroll', this.onScroll);
} else if(window.removeEventListener) {
window.removeEventListener('scroll', this.onScroll, false);
}
this.setState({ listeningScroll: false });
}
}
onScroll = () => {
// tacit agreement buahaha! (evil laugh)
if (window.pageYOffset > this.props.dismissOnScrollThreshold) {
this.onAccept();
}
}
getSecondsSinceExpiration = cookieExpiration => {
if (t.Integer.is(cookieExpiration)) {
return cookieExpiration;
}
const SECONDS_IN_YEAR = 31536000;
const SECONDS_IN_DAY = 86400;
const SECONDS_IN_HOUR = 3600;
const _cookieExpiration = {
years: 0, days: 0, hours: 0,
...cookieExpiration
};
const { years, days, hours } = _cookieExpiration;
return (years * SECONDS_IN_YEAR) + (days * SECONDS_IN_DAY) + (hours * SECONDS_IN_HOUR);
}
onAccept = () => {
const { cookie, cookieExpiration, onAccept } = this.props;
cookieLite(cookie, true, this.getSecondsSinceExpiration(cookieExpiration));
onAccept({ cookie });
if (this.state.listeningScroll) {
this.removeOnScrollListener();
} else {
this.forceUpdate();
}
}
getStyle = (style) => {
const { disableStyle, styles } = this.props;
if (!disableStyle) {
// apply custom styles if available
return { ...styleUtils.getStyle(style), ...styles[style] };
}
}
getCloseButton = () => {
const { closeIcon, buttonMessage } = this.props;
if (closeIcon) {
return <i className={closeIcon} onClick={this.onAccept} style={this.getStyle('icon')}/>;
}
return (
<div className='button-close' onClick={this.onAccept} style={this.getStyle('button')}>
{buttonMessage}
</div>
);
}
getLink = () => {
const { link } = this.props;
if (link) {
return (
<a
href={link.url}
target={link.target}
className='cookie-link'
style={this.getStyle('link')}>
{link.msg || 'Learn more'}
</a>
);
}
}
getBanner = () => {
const { children, className, message } = this.props;
if (children) {
return children;
}
const props = omit(this.props, Object.keys(Props));
return (
<div {...props} className={cx('react-cookie-banner', className)} style={this.getStyle('banner')}>
<span className='cookie-message' style={this.getStyle('message')}>
{message}
{this.getLink()}
</span>
{this.getCloseButton()}
</div>
);
}
hasAcceptedCookies = () => {
return (typeof window !== 'undefined') && cookieLite(this.props.cookie);
}
render() {
return this.hasAcceptedCookies() ? null : this.getBanner();
}
componentWillReceiveProps(nextProps) {
if (nextProps.dismissOnScroll) {
this.addOnScrollListener(nextProps);
} else {
this.removeOnScrollListener();
}
}
componentWillUnmount() {
this.removeOnScrollListener();
}
}
|
JavaScript
| 0 |
@@ -1508,16 +1508,79 @@
-policy%0A
+ * @param cookieExpiration - used to set the cookie expiration%0A
* @para
@@ -1603,16 +1603,17 @@
l - whet
+h
er the c
|
00f7a562e774cd6875a1acf4e2d250286f383f46
|
Add option to livereload css.
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
gutil = require('gulp-util'),
buffer = require('vinyl-buffer'),
source = require('vinyl-source-stream'),
connect = require('gulp-connect'),
plumber = require('gulp-plumber'),
babelify = require('babelify'),
sourcemap = require('gulp-sourcemaps'),
browserify = require('browserify');
gulp.task('default', ['watch-www', 'watch-src', 'watch-styles', 'build', 'serve'], function () {});
gulp.task('build', ['build-sass', 'build-es6'], function () {});
gulp.task('build-sass', function () {
return gulp.src('./styles/**/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('./public/styles/'));
});
gulp.task('build-es6', function () {
return browserify({debug: true})
.transform(babelify)
.require('./src/scripts/bootstrap.js', {entry: true})
.bundle()
.on('error', function (err) {
gutil.log('Browserify error.');
})
.pipe(plumber())
.pipe(source('bootstrap.js'))
.pipe(buffer())
.pipe(sourcemap.init({loadMaps: true}))
.pipe(sourcemap.write('./'))
.pipe(gulp.dest('./public/scripts/'));
});
gulp.task('serve', function () {
return connect.server({
root: './public',
port: 3000,
livereload: true
});
});
gulp.task('watch-src', function () {
return gulp.watch('./src/**/*.js', ['build-es6']);
});
gulp.task('watch-www', function () {
return gulp.watch('./public/**/*.{js,html,css}', ['livereload']);
});
gulp.task('watch-styles', function () {
return gulp.watch('./styles/**/*.scss', ['build-sass']);
});
gulp.task('livereload', function () {
return gulp.src('./public/**/*.{js,html}')
.pipe(connect.reload());
});
|
JavaScript
| 0 |
@@ -1772,16 +1772,20 @@
%7Bjs,html
+,css
%7D')%0A
|
e54a6a0ded7b6f6a0061141c2c39d85d32ccfa95
|
Update custom.js
|
js/custom.js
|
js/custom.js
|
/*!
* Custom Code file for kraftychocolates
*/
function show_callus_modal() {
console.log("Callus modal shown");
return false;
}
var callus_switcher = function() {
if($(window).width() <=768) {
$('.callus').addClass("callus-popup");
$(".callus-popup").on("click",show_callus_modal);
}
else {
if($(".callus-popup").length){
$(".callus-popup").off("click");
$('.callus').removeClass("callus-popup");
}
}
};
$(document).ready(callus_switcher);
$( window ).resize(callus_switcher);
|
JavaScript
| 0.000001 |
@@ -192,9 +192,9 @@
h()
-%3C
+%3E
=768
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.