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
|
---|---|---|---|---|---|---|---|
f106a6cff11f7e4b1a42a6ea20eb59343a80e18a
|
delete error: 'route: command not found'
|
profile/mac.js
|
profile/mac.js
|
module.exports = function(Formatter) {
function MacUpFormatter() {
}
$inherit(MacUpFormatter, Formatter, {
format: function(rules) {
var up = [];
up.push('#!/bin/sh');
up.push('export PATH="/bin:/sbin:/usr/sbin:/usr/bin"');
up.push('OLDGW=`netstat -nr | grep "^default" | grep -v "ppp" | awk -F\' \' \'{print $2}\'`');
up.push('dscacheutil -flushcache');
up.push('echo $OLDGW > /tmp/pptp_oldgw');
up.push('route add 10.0.0.0/8 $OLDGW');
up.push('route add 172.16.0.0/12 $OLDGW');
up.push('route add 192.168.0.0/16 $OLDGW');
rules.forEach(function(rule) {
if (rule.gateway === 'vpn') {
up.push('route add ' + rule.prefix + '/' + rule.length + ' $4');
} else {
up.push('route add ' + rule.prefix + '/' + rule.length + ' $OLDGW');
}
});
return up.join('\n');
}
});
function MacDownFormatter() {
}
$inherit(MacDownFormatter, Formatter, {
format: function(rules) {
var up = [];
up.push('#!/bin/sh');
up.push('[ -s /tmp/pptp_oldgw ] || exit 1');
up.push('OLDGW=`cat /tmp/pptp_oldgw`');
up.push('route delete 10.0.0.0/8 $OLDGW');
up.push('route delete 172.16.0.0/12 $OLDGW');
up.push('route delete 192.168.0.0/16 $OLDGW');
rules.forEach(function(rule) {
if (rule.gateway === 'vpn') {
up.push('route delete ' + rule.prefix + '/' + rule.length + ' $4');
} else {
up.push('route delete ' + rule.prefix + '/' + rule.length + ' $OLDGW');
}
});
up.push('rm -f /tmp/pptp_oldgw');
return up.join('\n');
}
});
return {
'ip-up': {
mode: 0777,
Formatter: MacUpFormatter
},
'ip-down': {
mode: 0777,
Formatter: MacDownFormatter
}
};
};
|
JavaScript
| 0.000004 |
@@ -978,32 +978,92 @@
h('#!/bin/sh');%0A
+ up.push('export PATH=%22/bin:/sbin:/usr/sbin:/usr/bin%22');%0A
up.push('%5B -
@@ -1541,24 +1541,65 @@
%7D%0A %7D);%0A
+ up.push('route add default $OLDGW');%0A
up.push(
|
020c52f60a0fc7c9f8909d4633ff781f65091d76
|
Send conditional POST req to netlify build hook
|
lambda/snipcart-webhook-listener.js
|
lambda/snipcart-webhook-listener.js
|
exports.handler = async (event, context) => {
console.log('Snipcart webhook received!');
console.log('event', event);
console.log('context', context);
return {
statusCode: 200,
body: 'Thanks for the webhook snipcart!'
};
};
|
JavaScript
| 0 |
@@ -1,8 +1,331 @@
+const https = require('https');%0A%0Aconsole.log('Snipcart webhook received!');%0A%0Aconst method = 'POST';%0Aconst host = 'api.netlify.com';%0Aconst path =%0A '/build_hooks/5ef219aec0c4ea9331e5fe67?trigger_branch=master&trigger_title=Triggered+by+Netlify+Functions+via+Snipcart+webhook';%0Aconst options = %7B%0A method,%0A host,%0A path%0A%7D;%0A%0A
exports.
@@ -346,25 +346,16 @@
c (event
-, context
) =%3E %7B%0A
@@ -363,47 +363,96 @@
cons
-ole.log('Snipcart webhook receiv
+t body = event.body;%0A%0A if (body.eventName && body.eventName === 'order.complet
ed
-!
')
-;%0A
+ %7B%0A
co
@@ -466,58 +466,260 @@
og('
-event', event);%0A console.log('context', context);
+ORDER UP %F0%9F%8E%89');%0A%0A const post = https.request(options, (res) =%3E %7B%0A console.log(%60POST response status: $%7Bres.statusCode%7D%60);%0A %7D);%0A%0A post.on('error', (e) =%3E %7B%0A console.error(%60Problem with POST: $%7Be.message%7D%60);%0A %7D);%0A%0A post.end();%0A %7D%0A
%0A r
|
7bb20f314dd76ffffbf623626fc60411a0931a4e
|
update extglob tests
|
test/extglob1a.js
|
test/extglob1a.js
|
/*!
* micromatch <https://github.com/jonschlinkert/micromatch>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License
*/
'use strict';
var path = require('path');
var should = require('should');
var argv = require('minimist')(process.argv.slice(2));
var ref = require('./support/reference');
var mm = require('..');
if ('minimatch' in argv) {
mm = ref.minimatch;
}
describe.skip('extglob1a', function () {
it('should match character classes:', function () {
mm.match(['a', 'ab'], 'a!(x)').should.eql(['a', 'ab']);
mm.match(['a'], 'a?(x)').should.eql(['a']);
mm.match(['ba'], 'a!(x)').should.eql([]);
mm.match(['ba'], 'a*?(x)').should.eql([]);
mm.match(['a', 'ab'], 'a*!(x)/b/?(y)/c').should.eql([]);
mm.match(['ba'], 'a*!(x)').should.eql([]);
mm.match(['a.js', 'a.md', 'a.js.js', 'c.js', 'a.', 'd.js.d'], '*.!(js)').should.eql(['a.md', 'a.', 'd.js.d']);
});
it('failing:', function () {
mm.match(['ab', 'ba'], 'a?(x)').should.eql([]);
mm.match(['a', 'ab'], 'a*?(x)').should.eql(['a', 'ab']);
mm.match(['a', 'ab'], 'a*!(x)').should.eql(['a', 'ab']);
mm.match(['a', 'x'], 'a*!(x)').should.eql(['a']);
mm.match(['a', 'x', 'ab', 'ax'], 'a*!(x)').should.eql(['a']);
});
it.skip('should match negation patterns on extglobs:', function () {
mm.makeRe('a*!(x)').should.eql(/^(?:a(?!\.)(?=.)[^/]*?(?:(?!x)[^/]*?))$/);
mm.makeRe('?(a*|b)').should.eql(/^(?:(?:(?!a*|b)[^/]*?))$/);
});
it.skip('failing:', function () {
mm.makeRe('a*!(x)').should.eql(/^(?:(?=.)a[^/]*?(?:(?!x)[^/]*?))$/);
});
it('should match negation patterns on extglobs:', function () {
mm.makeRe('*.!(js)').should.eql(/^(?:(?!\.)(?=.)[^/]*?\.(?:(?!js)[^/]*?))$/);
});
})
|
JavaScript
| 0 |
@@ -400,21 +400,16 @@
describe
-.skip
('extglo
@@ -477,32 +477,35 @@
unction () %7B%0A
+ //
mm.match(%5B'a',
@@ -504,24 +504,29 @@
h(%5B'a', 'ab'
+, 'x'
%5D, 'a!(x)').
@@ -545,32 +545,35 @@
'a', 'ab'%5D);%0A
+ //
mm.match(%5B'a'%5D,
@@ -747,32 +747,84 @@
should.eql(%5B%5D);%0A
+ mm.match(%5B'ab', 'ba'%5D, 'a?(x)').should.eql(%5B%5D);%0A
mm.match(%5B'b
@@ -849,32 +849,35 @@
uld.eql(%5B%5D);%0A
+ //
mm.match(%5B'a.js
@@ -983,16 +983,21 @@
);%0A%0A it
+.skip
('failin
@@ -1027,37 +1027,37 @@
mm.match(%5B'a
-b
', '
-b
a
+b
'%5D, 'a
+*
?(x)').shoul
@@ -1055,32 +1055,41 @@
)').should.eql(%5B
+'a', 'ab'
%5D);%0A mm.match
@@ -1097,33 +1097,33 @@
%5B'a', 'ab'%5D, 'a*
-?
+!
(x)').should.eql
@@ -1149,34 +1149,33 @@
mm.match(%5B'a', '
-ab
+x
'%5D, 'a*!(x)').sh
@@ -1179,38 +1179,32 @@
.should.eql(%5B'a'
-, 'ab'
%5D);%0A mm.match
@@ -1205,32 +1205,44 @@
.match(%5B'a', 'x'
+, 'ab', 'ax'
%5D, 'a*!(x)').sho
@@ -1270,62 +1270,69 @@
m.ma
-tch(%5B'a', 'x', 'ab', 'ax'%5D, 'a*!(x)').should.eql(%5B'a'%5D
+keRe('a*!(x)').should.eql(/%5E(?:(?=.)a%5B%5E/%5D*?(?:(?!x)%5B%5E/%5D*?))$/
);%0A
@@ -1341,21 +1341,16 @@
);%0A%0A it
-.skip
('should
@@ -1448,39 +1448,17 @@
(?:a
-(?!%5C.)(?=.)%5B%5E/%5D*?(?:(?!x)
%5B%5E/%5D*?
+!(x
))$/
@@ -1505,220 +1505,28 @@
%5E(?:
-(?:(?!a*%7Cb)%5B%5E/%5D*?))$/);%0A %7D);%0A%0A it.skip('failing:', function () %7B%0A mm.makeRe('a*!(x)').should.eql(/%5E(?:(?=.)a%5B%5E/%5D*?(?:(?!x)%5B%5E/%5D*?))$/);%0A %7D);%0A%0A it('should match negation patterns on extglobs:', function () %7B
+%5B%5E/%5D(a%5B%5E/%5D*?%7Cb))$/);
%0A
@@ -1586,23 +1586,12 @@
*?%5C.
-(?:(?!js)%5B%5E/%5D*?
+!(js
))$/
|
7b98c2b9ef3d82bdb25a938ba736dd5023fd1546
|
Add reports.state.create
|
list/reports/state/create.js
|
list/reports/state/create.js
|
/*!
* hackerone.reports.state.create (https://github.com/xc0d3rz/hackerone)
* Copyright 2016-2017 xc0d3rz([email protected])
* Licensed under the MIT license
*/
/**
*
* @param id
* @param param
* @param callback
*/
module.exports = function (id, param, callback) {
this.post('reports/' + id + '/assignee', {
data: {
id: param.id,
type: 'state-change',
attributes: {
message: param.message,
state: param.state
}
}
}, callback);
};
|
JavaScript
| 0.000001 |
@@ -310,16 +310,21 @@
+ '/
-assignee
+state_changes
', %7B
@@ -344,34 +344,8 @@
: %7B%0A
- id: param.id,%0A
|
d9479b1df11eb7e52a9c5badf66b29d09ff08d02
|
FIX sequence generation
|
scripts/generate_seq.js
|
scripts/generate_seq.js
|
$('#cleaner').click(function () {
$('#seq-id').val("");
$('#seq-id1').val("");
$('#seq-id2').val("");
$('#seq-id3').val("");
$('#seq_length').val("");
$('p#length-meter').text("");
$('textarea').trigger('autoresize');
cleaner();
});
$('#generator').click(function () {
var seq_length = $('#seq_length').val();
$('#seq-id1').val("");
$('#seq-id2').val("");
$('#seq-id3').val("");
if (seq_length) {
var sequence = createSequence(seq_length);
} else {
var sequence = createSequence(Math.floor((Math.random() * 1000) + 3));
}
$('#seq-id').val(this.sequence);
$('#seq-id').trigger('autoresize');
$('p#length-meter').text("Length: " + this.sequence.length);
});
function createSequence(size) {
var sequence = "";
for (var i = 0; i < size; i++) {
sequence += getRandomChar();
}
return sequence;
}
function getRandomChar() {
var chars = ["A", "T", "C", "G"];
return chars[Math.floor((Math.random() * chars.length))];
}
function cleaner() {
document.getElementById('length').innerHTML = "";
document.getElementById('mass').innerHTML = "";
document.getElementById('pI').innerHTML = "";
document.getElementById('charge').innerHTML = "";
document.getElementById('hydrophobicity').innerHTML = "";
document.getElementById('extinction1').innerHTML = "";
document.getElementById('extinction2').innerHTML = "";
}
|
JavaScript
| 0.000001 |
@@ -637,21 +637,16 @@
d').val(
-this.
sequence
@@ -734,13 +734,8 @@
%22 +
-this.
sequ
|
f8c5ee5640e949708ec09fbb536644a30a1abe1f
|
Remove old test remains
|
test/template-engine/template/templateSpec.js
|
test/template-engine/template/templateSpec.js
|
import Template from '../../../src/template.js';
describe('Template', () => {
describe('create', () => {
let dom = document.createElement('div');
let sut = new Template(dom);
it('should expose the dom', () => {
expect(sut.dom).to.equal(dom);
});
});
describe('create given named container and 2 named children ', () => {
let containerElementName = 'container',
firstElementName = 'first',
firstElementTranslateId = 'hello',
secondElementName = 'second',
rawTemplate = `
<div data-name=${containerElementName}>
<div data-name="${firstElementName}">Hello</div>
<div data-name="${secondElementName}"></div>
</div>`;
let dom = document.createElement('div');
dom.innerHTML = rawTemplate;
let sut = new Template(dom);
it('exposes named container', () => {
let actual = sut.namedElements[containerElementName];
expect(actual).is.not.undefined;
});
it('exposes first named child', () => {
let actual = sut.namedElements[firstElementName];
expect(actual).is.not.undefined;
});
it('exposes second named child', () => {
let actual = sut.namedElements[secondElementName];
expect(actual).is.not.undefined;
});
});
describe('create given 2 elements marked as property on different levels', () => {
let firstPropertyName = 'first',
secondPropertyName = 'second',
thirdPropertyName = 'third',
rawTemplate = `
<div>
<div data-property="${firstPropertyName}"></div>
<div>
<div data-property="${secondPropertyName}"></div>
<div data-property="${thirdPropertyName}"></div>
</div>
</div>`;
let dom = document.createElement('div');
dom.innerHTML = rawTemplate;
let sut = new Template(dom);
it('exposes first propertyElement', () => {
let actual = sut.propertyElements[firstPropertyName];
expect(actual).is.not.undefined;
});
it('exposes second propertyElement', () => {
let actual = sut.propertyElements[secondPropertyName];
expect(actual).is.not.undefined;
});
it('exposes third property element', () => {
let actual = sut.propertyElements[thirdPropertyName];
expect(actual).is.not.undefined;
});
});
describe('create given several elements on the root level', () => {
let rawTemplate = '<div></div><p></p>';
let dom = document.createElement('div');
dom.innerHTML = rawTemplate;
let sut = new Template(dom);
it('exposes all of them', () => {
expect(sut.childNodes.length).to.equal(2);
});
});
describe('create given element with i18n', () => {
let translateId = 'hello';
let translatedContent = 'Hei';
let translationProvider = {
translate: function(id, element) {
if(id === translateId)
return translatedContent;
}
};
let rawTemplate = `<div data-translate="${translateId}">Hello</div>`;
let dom = document.createElement('div');
dom.innerHTML = rawTemplate;
let sut = new Template(dom, translationProvider);
it('translates textContent of elements with data-translate', () => {
let actual = dom.children[0].textContent;
expect(actual).to.equal(translatedContent);
});
})
describe('reclaimChildren attached to an external node ', () => {
let dom = document.createElement('div');
let rawTemplate = '<div></div>';
dom.innerHTML = rawTemplate;
let sut = new Template(dom);
let testElement = sut.childNodes[0];
let region = document.createElement('div');
region.appendChild(testElement);
sut.reclaimChildren();
it('removes the element from the original parent', () => {
expect(region.children.length).to.equal(0);
});
});
function getByName(collection, name) {
return collection.filter(i => {
return i.name === name;
})[0];
}
});
|
JavaScript
| 0.000012 |
@@ -465,55 +465,8 @@
t',%0A
- firstElementTranslateId = 'hello',%0A
@@ -644,21 +644,16 @@
tName%7D%22%3E
-Hello
%3C/div%3E%0A
|
1635a03bb7b07a072ad9b491b84718faa014e93c
|
update main test
|
test/main.test.js
|
test/main.test.js
|
import icons from '../src/data.js'
import { t } from './utils.js'
describe('CommonJS library', () => {
const Octicons = require('../')
icons.forEach(icon => {
t(Octicons[icon.camelName], icon)
})
})
|
JavaScript
| 0 |
@@ -1,12 +1,33 @@
+/* eslint-disable */%0A
import icons
@@ -118,16 +118,57 @@
() =%3E %7B%0A
+ describe('with built icons', () =%3E %7B%0A
const
@@ -193,16 +193,18 @@
('../')%0A
+
icons.
@@ -225,16 +225,18 @@
%3E %7B%0A
+
t(Octico
@@ -261,16 +261,427 @@
, icon)%0A
+ %7D)%0A %7D)%0A%0A describe('with a fake icon', () =%3E %7B%0A jest.resetModules()%0A jest.doMock(%60../lib/icons/alert.js%60, () =%3E %7B%0A return %7B%0A default: 'something else'%0A %7D%0A %7D)%0A%0A const Octicons = require('../')%0A test(%60replaces the alert icon to the fake one%60, () =%3E %7B%0A expect(Octicons.alert).toBe('something else')%0A %7D)%0A%0A jest.unmock(%60../lib/icons/alert.js%60)%0A jest.resetModules()%0A
%7D)%0A%7D)%0A
|
413ff1bac4a68d58388c1afc14f1af32a6772062
|
Use new FullscreenMessageDialog in MissingProjectConfig
|
packages/@sanity/base/src/components/MissingProjectConfig.js
|
packages/@sanity/base/src/components/MissingProjectConfig.js
|
import React from 'react'
import config from 'config:sanity'
import DialogContent from 'part:@sanity/components/dialogs/content?'
import FullscreenDialog from 'part:@sanity/components/dialogs/fullscreen?'
export default function MissingProjectConfig() {
const {root, project, plugins} = config
const {dataset, projectId} = config.api || {}
const api = {projectId: projectId || 'myProjectId', dataset: dataset || 'myDatasetName'}
const desiredConfig = {root, project, api, plugins}
const missing = [!projectId && '"projectId"', !dataset && '"dataset"'].filter(Boolean)
return (
<FullscreenDialog color="default" title="Project details missing" isOpen centered>
<DialogContent size="medium" padding="none">
<p>
The <code>sanity.json</code> file in your studio folder seems to be missing the{' '}
{missing.join(' and ')} configuration {missing.length > 1 ? 'options ' : 'option '}
under the <code>api</code> key.
</p>
<p>
A valid <code>sanity.json</code> file looks something like the following:
</p>
<pre>
<code>{highlightMissing(JSON.stringify(desiredConfig, null, 2))}</code>
</pre>
</DialogContent>
</FullscreenDialog>
)
}
// eslint-disable-next-line react/no-multi-comp
function highlightMissing(jsonConfig) {
const parts = jsonConfig
.split(/("dataset": "myDatasetName"|"projectId": "myProjectId")/)
.reduce((els, part, i) => {
if (i % 2 === 0) {
return els.concat(part)
}
return els.concat(<strong key={part}>{part}</strong>)
}, [])
return <>{parts}</>
}
|
JavaScript
| 0 |
@@ -58,77 +58,8 @@
ty'%0A
-import DialogContent from 'part:@sanity/components/dialogs/content?'%0A
impo
@@ -67,24 +67,31 @@
t Fullscreen
+Message
Dialog from
@@ -133,17 +133,24 @@
llscreen
-?
+-message
'%0A%0Aexpor
@@ -547,30 +547,21 @@
reen
-Dialog color=%22default%22
+MessageDialog
tit
@@ -592,91 +592,20 @@
ing%22
- isOpen centered%3E%0A %3CDialogContent size=%22medium%22 padding=%22none%22%3E%0A %3Cp%3E%0A
+%3E%0A %3Cp%3E%0A
@@ -701,18 +701,16 @@
-
%7Bmissing
@@ -781,26 +781,24 @@
'option '%7D%0A
-
unde
@@ -827,26 +827,24 @@
key.%0A
-
%3C/p%3E%0A
@@ -838,32 +838,28 @@
%3C/p%3E%0A
-
%3Cp%3E%0A
-
A va
@@ -930,26 +930,24 @@
wing:%0A
-
%3C/p%3E%0A
@@ -949,18 +949,14 @@
-
-
%3Cpre%3E%0A
-
@@ -1041,40 +1041,15 @@
-
%3C/pre%3E%0A
- %3C/DialogContent%3E%0A
@@ -1060,16 +1060,23 @@
llscreen
+Message
Dialog%3E%0A
|
434dda9eedda786f82d91675b2b171e9e2fdb17b
|
add logout in auth hoc
|
packages/bonde-admin-canary/src/services/auth/context/hoc.js
|
packages/bonde-admin-canary/src/services/auth/context/hoc.js
|
import React from 'react'
import { AuthContext } from './Context'
const auth = () => Component => (props) => (
<AuthContext.Consumer>
{user => (<Component user={user} {...props} />)}
</AuthContext.Consumer>
)
export default auth
|
JavaScript
| 0 |
@@ -19,16 +19,83 @@
'react'%0A
+import %7B connect %7D from '../../redux'%0Aimport AuthAPI from '../api'%0A
import %7B
@@ -174,10 +174,110 @@
=%3E
-(%0A
+%7B%0A %0A const ComponentRedux = connect(undefined, %7B logout: AuthAPI.logout %7D)(Component)%0A%0A return (%0A
%3CA
@@ -301,16 +301,18 @@
er%3E%0A
+
+
%7Buser =%3E
@@ -323,16 +323,21 @@
omponent
+Redux
user=%7Bu
@@ -357,16 +357,18 @@
s%7D /%3E)%7D%0A
+
%3C/Auth
@@ -385,18 +385,21 @@
nsumer%3E%0A
+
)%0A
+%7D
%0Aexport
|
a4c15c0eb3c270083143227b3c8cd5bc4f9db6b6
|
fix err check
|
packages/coinstac-api-server/src/data/subscriptions/index.js
|
packages/coinstac-api-server/src/data/subscriptions/index.js
|
const rethink = require('rethinkdb');
const helperFunctions = require('../../auth-helpers');
const pipelineChangedSubsPreprocess = require('./pipelineChanged');
const userMetadataChangedSubsPreprocess = require('./userMetadataChanged');
// Add new tables here to create a new changefeed on server start
const tables = [
{ tableName: 'computations', idVar: 'computationId', subVar: 'computationChanged' },
{ tableName: 'consortia', idVar: 'consortiumId', subVar: 'consortiumChanged' },
{
tableName: 'pipelines', idVar: 'pipelineId', subVar: 'pipelineChanged', preprocess: pipelineChangedSubsPreprocess,
},
{ tableName: 'users', idVar: 'userId', subVar: 'userChanged' },
{
tableName: 'users', idVar: 'userId', subVar: 'userMetadataChanged', preprocess: userMetadataChangedSubsPreprocess,
},
{ tableName: 'runs', idVar: 'runId', subVar: 'userRunChanged' },
];
/**
* Initialize RethinkDB changefeeds to detect table changes and fire off GraphQL subscription topics
* @param {object} pubsub GraphQL publish and subscribe object
*/
const initSubscriptions = (pubsub) => {
tables.forEach((table) => {
helperFunctions.getRethinkConnection()
.then(connection => rethink.table(table.tableName).changes().run(connection))
.then(feed => feed.each((err, change) => {
console.log(`GraphQL changefeed error: ${err}`);
let val = {};
if (!change.new_val) {
val = Object.assign({}, change.old_val, { delete: true });
} else {
val = change.new_val;
}
const preprocessPromise = table.preprocess ? table.preprocess(val) : Promise.resolve(val);
preprocessPromise
.then(result => pubsub.publish(table.subVar, {
[table.subVar]: result,
[table.idVar]: result.id,
}));
}));
});
};
module.exports = initSubscriptions;
|
JavaScript
| 0.000001 |
@@ -1297,24 +1297,33 @@
=%3E %7B%0A
+ if (err)
console.log
|
ebb37316c01abd2de6237bcacd9b6c26552878ad
|
Fix vertical centering of user Drop down (#267)
|
packages/components/containers/heading/UserDropdownButton.js
|
packages/components/containers/heading/UserDropdownButton.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { DropdownCaret } from 'react-components';
import { getInitial } from 'proton-shared/lib/helpers/string';
const UserDropdownButton = ({ user, isOpen, buttonRef, ...rest }) => {
const { Email, DisplayName, Name } = user;
// DisplayName is null for VPN users without any addresses, cast to undefined in case Name would be null too.
const initials = getInitial(DisplayName || Name || undefined);
return (
<button
type="button"
className="inline-flex dropDown-logout-button"
aria-expanded={isOpen}
ref={buttonRef}
{...rest}
>
<span className="alignright mr0-5">
<span className="bl capitalize">{DisplayName || Name}</span>
{Email ? <span className="bl smaller m0 opacity-30 lh100">{Email}</span> : null}
</span>
<span className="mtauto mbauto bordered rounded50 p0-5 inbl dropDown-logout-initials relative">
<span className="dropDown-logout-text center">{initials}</span>
<DropdownCaret isOpen={isOpen} className="icon-12p expand-caret mauto" />
</span>
</button>
);
};
UserDropdownButton.propTypes = {
user: PropTypes.object,
className: PropTypes.string,
isOpen: PropTypes.bool,
buttonRef: PropTypes.object
};
export default UserDropdownButton;
|
JavaScript
| 0 |
@@ -560,16 +560,34 @@
ne-flex
+flex-items-center
dropDown
|
00a640e4733e8ce21d10a38f7e428a2b9418daac
|
fix highlighting of closing brace
|
lib/ace/mode/nix_highlight_rules.js
|
lib/ace/mode/nix_highlight_rules.js
|
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var NixHighlightRules = function() {
var constantLanguage = "true|false";
var keywordControl = "with|import|if|else|then";
var keywordDeclaration = "let|in|rec";
var keywordMapper = this.createKeywordMapper({
"constant.language.nix": constantLanguage,
"keyword.control.nix": keywordControl,
"keyword.declaration.nix": keywordDeclaration
}, "identifier");
this.$rules = {
"start": [{
token: "comment",
regex: /#.*$/
}, {
token: "comment",
regex: /\/\*/,
next: "comment"
}, {
token: "constant",
regex: "<[^>]+>"
}, {
regex: "(==|!=|<=?|>=?)",
token: ["keyword.operator.comparison.nix"]
}, {
regex: "((?:[+*/%-]|\\~)=)",
token: ["keyword.operator.assignment.arithmetic.nix"]
}, {
regex: "=",
token: "keyword.operator.assignment.nix"
}, {
token: "string",
regex: "''",
next: "qqdoc"
}, {
token: "string",
regex: "'",
next: "qstring"
}, {
token: "string",
regex: '"',
push: "qqstring"
}, {
token: "constant.numeric", // hex
regex: "0[xX][0-9a-fA-F]+\\b"
}, {
token: "constant.numeric", // float
regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token: keywordMapper,
regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
regex: "}",
token: function(val, start, stack) {
return stack[1] == "qqstring" ? "constant.language.escape" : "text"
},
next: "pop"
}],
"comment": [{
token: "comment", // closing comment
regex: ".*?\\*\\/",
next: "start"
}, {
token: "comment", // comment spanning whole line
regex: ".+"
}],
"qqdoc": [
{
token: "constant.language.escape",
regex: /\$\{/,
push: "start"
}, {
token: "string",
regex: "''",
next: "pop"
}, {
defaultToken: "string"
}],
"qqstring": [
{
token: "constant.language.escape",
regex: /\$\{/,
push: "start"
}, {
token: "string",
regex: '"',
next: "pop"
}, {
defaultToken: "string"
}],
"qstring": [
{
token: "constant.language.escape",
regex: /\$\{/,
push: "start"
}, {
token: "string",
regex: "'",
next: "pop"
}, {
defaultToken: "string"
}]
};
this.normalizeRules();
};
oop.inherits(NixHighlightRules, TextHighlightRules);
exports.NixHighlightRules = NixHighlightRules;
});
|
JavaScript
| 0 |
@@ -2281,20 +2281,35 @@
%5B1%5D
-== %22qqstring
+&& stack%5B1%5D.charAt(0) == %22q
%22 ?
@@ -2343,16 +2343,17 @@
: %22text%22
+;
%0A
|
b17a07e701c95896bfa566275bca489e4bf750b8
|
Remove excessive validation
|
lib/builders/BootstrapperBuilder.js
|
lib/builders/BootstrapperBuilder.js
|
var path = require('path');
var util = require('util');
var pfs = require('../promises/fs');
var hrTimeHelper = require('../helpers/hrTimeHelper');
var moduleHelper = require('../helpers/moduleHelper');
var requireHelper = require('../helpers/requireHelper');
const BOOTSTRAPPER_FILENAME = 'Bootstrapper.js';
const BROWSER_ROOT_PATH = path.join(__dirname, '..', '..', 'browser');
const COMPONENT_FORMAT = '\n{' +
'name: \'%s\', ' +
'constructor: %s, ' +
'properties: %s, ' +
'templateSource: \'%s\', ' +
'errorTemplateSource: %s' +
'}';
const ENTITY_FORMAT = '\n{name: \'%s\', definition: %s}';
const COMPONENTS_REPLACE = '/**__components**/';
const WATCHERS_REPLACE = '/**__watchers**/';
const SIGNALS_REPLACE = '/**__signals**/';
const ROUTE_DEFINITIONS_REPLACE = '\'__routes\'';
const ROUTE_DEFINITIONS_FILENAME = 'routes.js';
const REQUIRE_FORMAT = 'require(\'%s\')';
const INFO_BUILDING_BOOTSTRAPPER = 'Building bootstrapper...';
const INFO_BOOTSTRAPPER_BUILT = 'Bootstrapper has been built (%s)';
class BootstrapperBuilder {
constructor ($serviceLocator) {
this._eventBus = $serviceLocator.resolve('eventBus');
this._templateProvider = $serviceLocator.resolve('templateProvider');
this._logger = $serviceLocator.resolve('logger');
}
/**
* Current template provider.
* @type {TemplateProvider}
* @private
*/
_templateProvider = null;
/**
* Current logger.
* @type {Logger}
* @private
*/
_logger = null;
/**
* Current event bus.
* @type {EventEmitter}
* @private
*/
_eventBus = null;
/**
* Creates real bootstrapper code for bundle build.
* @param {Object} components
* @param {Object} signals
* @param {Object} watchers
* @returns {Promise<string>} Promise for source code of real bootstrapper.
*/
build (components, signals, watchers) {
var bootstrapperTemplatePath = path.join(BROWSER_ROOT_PATH, BOOTSTRAPPER_FILENAME);
var routeDefinitionsPath = path.join(process.cwd(), ROUTE_DEFINITIONS_FILENAME);
var startTime = hrTimeHelper.get();
this._logger.info(INFO_BUILDING_BOOTSTRAPPER);
return pfs.readFile(bootstrapperTemplatePath, {
encoding: 'utf8'
})
.then(file => {
return Promise.all([
this._generateRequiresForComponents(components),
this._generateRequires(signals),
this._generateRequires(watchers)
])
.then(results => ({
file: file,
components: results[0],
signals: results[1],
watchers: results[2]
}));
})
.then(context => {
// check if paths exist and create require statements or undefined
return pfs.exists(routeDefinitionsPath)
.then(isExists => {
var requireString = isExists ? util.format(
REQUIRE_FORMAT,
'./' +
path.relative(
process.cwd(),
requireHelper.getValidPath(routeDefinitionsPath)
)) : 'null';
return context.file
.replace(COMPONENTS_REPLACE, context.components)
.replace(WATCHERS_REPLACE, context.watchers)
.replace(SIGNALS_REPLACE, context.signals)
.replace(ROUTE_DEFINITIONS_REPLACE, requireString);
});
})
.then(boostrapper => {
this._logger.info(util.format(
INFO_BOOTSTRAPPER_BUILT,
hrTimeHelper.toMessage(hrTimeHelper.get(startTime))
));
return boostrapper;
})
.catch(reason => this._eventBus.emit('error', reason));
}
/**
* Generates replacements for every component.
* @param {Object} components
* @returns {Promise<string>} Promise for JSON string that describes components.
* @private
*/
_generateRequiresForComponents (components) {
var promises = [];
Object.keys(components)
.forEach(componentName => {
var componentDetails = components[componentName];
var componentPath = path.dirname(componentDetails.path);
var logicFile = components[componentName].properties.logic || moduleHelper.DEFAULT_LOGIC_FILENAME;
var logicPath = path.resolve(componentPath, logicFile);
var relativeLogicPath = path.relative(process.cwd(), logicPath);
var constructor;
try {
constructor = require(logicPath);
} catch (e) {
this._eventBus.emit('error', e);
}
if (typeof (constructor) !== 'function' ||
typeof (componentDetails.properties.template) !== 'string') {
return;
}
var templates = [];
templates.push({
name: componentDetails.name,
isErrorTemplate: false,
path: path.resolve(componentPath, componentDetails.properties.template)
});
if (componentDetails.properties.errorTemplate) {
var errorTemplateName = moduleHelper.getNameForErrorTemplate(componentDetails.name);
var errorTemplatePath = path.resolve(componentPath, componentDetails.properties.errorTemplate);
templates.push({
name: errorTemplateName,
isErrorTemplate: true,
path: errorTemplatePath
});
}
// load sources
var templatePromises = templates.map(template => {
return pfs.readFile(template.path)
.then(source => {
var result = Object.create(template);
result.source = source.toString();
return result;
});
});
var promise = Promise.all(templatePromises)
// compile sources
.then(templates => {
var compilePromises = templates
.map(template => {
var compiled = this._templateProvider.compile(template.source, template.name);
return Promise.resolve(compiled)
.then(compiled => {
var result = Object.create(template);
result.compiledSource = compiled;
return result;
});
});
return Promise.all(compilePromises);
})
.then(templates => {
var requireString = util.format(
REQUIRE_FORMAT,
'./' +
requireHelper.getValidPath(relativeLogicPath)
);
var templatesString = templates.length > 1 &&
typeof (templates[1].compiledSource) === 'string' ?
'\'' + escapeTemplateSource(
templates[1].compiledSource
) + '\'' : 'null';
return util.format(COMPONENT_FORMAT,
componentName, requireString,
JSON.stringify(componentDetails.properties),
escapeTemplateSource(templates[0].compiledSource),
templatesString
);
});
promises.push(promise);
});
return Promise.all(promises)
.then(components => components.join(','));
}
/**
* Generates replacements for every signal or watcher.
* @param {Object} entities
* @returns {Promise<string>} Promise for JSON string that describes entity.
* @private
*/
_generateRequires (entities) {
var entitiesRequires = [];
Object
.keys(entities)
.forEach(entityName => {
var requireExpression = entities[entityName].path ?
util.format(
REQUIRE_FORMAT,
requireHelper.getValidPath(
'./' +
path.relative(process.cwd(), entities[entityName].path)
)
) : null;
if (!requireExpression) {
return;
}
entitiesRequires.push(util.format(ENTITY_FORMAT, entityName, requireExpression));
});
return Promise.resolve(entitiesRequires.join(','));
}
}
/**
* Escapes template source for including to bootstrapper.
* @param {string} source Template compiled source.
* @returns {string} escaped string.
*/
function escapeTemplateSource (source) {
return source
.replace(/(\\.)/g, '\\$&')
.replace(/'/g, '\\\'')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t');
}
module.exports = BootstrapperBuilder;
|
JavaScript
| 0.000016 |
@@ -4223,229 +4223,21 @@
h);%0A
- var constructor;%0A%0A try %7B%0A constructor = require(logicPath);%0A %7D catch (e) %7B%0A this._eventBus.emit('error', e);%0A %7D%0A%0A if (typeof (constructor) !== 'function' %7C%7C%0A
+%0A if (
type
|
f34a0f5a78416cca37562f9374db2315d4ba2201
|
fix test
|
test/node/node.js
|
test/node/node.js
|
var should = require('should')
var cheerio = require('cheerio')
var path = require('path')
describe('node', function () {
var inst = require('../../index.js')
after(function () {
inst.remove()
})
it('->register', function () {
inst.register()
var style = require('../assets/simple.styl')
style.should.have.property('id').which.is.a.String()
style.should.have.property('css').which.is.a.String()
})
it('->remove', function () {
inst.remove();
(function removeException() {
require('../assets/simple-cp.styl')
}).should.throw(SyntaxError)
})
})
describe('express', function () {
require('babel-register')
var express = require('express')
var inst = require('../../index.js')
var app = express()
var fs = require('fs')
var fetch = require('node-fetch')
before(function () {
inst.register()
app.use(inst.styleInterceptor)
var reactEngine = require('react-engine')
var engine = reactEngine.server.create({
})
app.engine('.jsx', engine)
app.set('views', path.join(__dirname, '../assets/react/'))
app.set('view engine', 'jsx')
app.set('view', require('react-engine/lib/expressView'))
})
after(function () {
inst.remove()
})
it('->intercept', function () {
var stylusFiles = [
'../assets/react/Sample.styl',
'../assets/react/Second.styl',
'../assets/react/Child/Child.styl'
];
app.render('Sample.jsx', function (err, html) {
var $ = cheerio;
var $document = $.load(html)
stylusFiles.forEach(function (item) {
var itemStyle = require(item)
var $itemDOM = $document('#' + itemStyle.id)
$itemDOM.should.be.instanceOf(Object)
$itemDOM.html().should.be.eql(itemStyle.css)
});
})
})
})
|
JavaScript
| 0.000002 |
@@ -1500,16 +1500,40 @@
heerio;%0A
+ console.log(html)%0A
va
|
9e8f9cfb709f577ee65e1f344013124faa5031ba
|
enable tsc to typecheck statistic definitions
|
src/server/api/statistic-definitions.js
|
src/server/api/statistic-definitions.js
|
/**
* @license Copyright 2019 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/** @typedef {(lhrs: Array<LH.Result>) => ({value: number})} StatisticFn */
/**
*
* @param {string} auditId
* @return {StatisticFn}
*/
function auditNumericValueAverage(auditId) {
return lhrs => {
const values = lhrs
.map(lhr => lhr.audits[auditId] && lhr.audits[auditId].numericValue)
.filter(
/** @return {value is number} */ value =>
typeof value === 'number' && Number.isFinite(value)
);
const sum = values.reduce((x, y) => x + y, 0);
const count = values.length;
if (count === 0) return {value: 0};
return {value: sum / count};
};
}
/** @type {Record<LHCI.ServerCommand.StatisticName, StatisticFn>} */
module.exports = {
audit_interactive_average: auditNumericValueAverage('interactive'),
'audit_speed-index_average': auditNumericValueAverage('speed-index'),
'audit_first-contentful-paint_average': auditNumericValueAverage('first-contentful-paint'),
};
|
JavaScript
| 0.000001 |
@@ -1279,21 +1279,24 @@
*/%0A
-module.export
+const definition
s =
@@ -1536,8 +1536,135 @@
t'),%0A%7D;%0A
+%0A// Keep the export separate from declaration to enable tsc to typecheck the %60@type%60 annotation.%0Amodule.exports = definitions;%0A
|
6001b864d698238bd14a92c7514a4701113984bd
|
Update index.js
|
templates/src/components/About/index.js
|
templates/src/components/About/index.js
|
// src/components/About/index.js
import React, { Component } from 'react';
import classnames from 'classnames';
import './style.css';
export default class About extends Component {
render() {
const { className, ...props } = this.props;
return (
<div className={classnames('About', className)} {...props}>
<h1>
About. React Router working successfully.
</h1>
</div>
);
}
}
|
JavaScript
| 0.000002 |
@@ -342,15 +342,8 @@
- About.
Rea
@@ -363,22 +363,9 @@
king
- successfully.
+!
%0A
|
89a81ae471d00457132d66f43670bd36f2b055a6
|
fix graphModel
|
lib/dataTier/graph/barChartModel.js
|
lib/dataTier/graph/barChartModel.js
|
/*jshint node: true, -W106 */
'use strict';
/*
* Name : barChartModel.js
* Module : Lib::DataTier::BarChartModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version Date Programmer Description
* =========================================================
* 0.0.1 2015-05-12 Samuele Zanella Initial code
* =========================================================
*/
var GraphModel = require('./graphModel.js');
var BarChartFlowModel = require('../flow/barChartFlowModel.js');
BarChartModel.prototype = new GraphModel({ID: 'ex'});
BarChartModel.prototype.constructor = BarChartModel;
BarChartModel.prototype.parent = GraphModel.prototype;
function BarChartModel(params) {
params.type = 'BarChart';
this.parent.constructor.call(this, params);
this._headers=[];
this._barOrientation='';
this._sortable=false;
this._xAxis='';
this._yAxis='';
this._backgroundColor='';
this._flows=[];
if(params.headers!==undefined && Array.isArray(params.headers)){
this._headers=params.headers;
}
if(params.barOrientation!==undefined && typeof params.barOrientation === 'string'/*POSSIBLE VALUES*/){
this._barOrientation=params.barOrientation;
}
if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
this._sortable=params.sortable;
}
if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
this._xAxis=params.xAxis;
}
if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
this._yAxis=params.yAxis;
}
if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
this._backgroundColor=params.backgroundColor;
}
}
BarChartModel.prototype.getProperties = function() {
var res = this.parent.getProperties.call(this);
res.headers = this._headers;
res.barOrientation = this._barOrientation;
res.sortable = this._sortable;
res.xAxis = this._xAxis;
res.yAxis = this._yAxis;
res.backgroundColor = this._backgroundColor;
return res;
};
BarChartModel.prototype.updateProperties = function(params) {
this.parent.updateProperties.call(this, params);
if(params.headers!==undefined && Array.isArray(params.headers)){
this._headers=params.headers;
}
if(params.barOrientation!==undefined && typeof params.sortable === 'boolean'){
this._barOrientation=params.barOrientation;
}
if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
this._sortable=params.sortable;
}
if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
this._xAxis=params.xAxis;
}
if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
this._yAxis=params.yAxis;
}
if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
this._backgroundColor=params.backgroundColor;
}
};
BarChartModel.prototype.addFlow = function(flow) {
if(flow instanceof BarChartFlowModel) {
this._flows.push(flow);
}
};
BarChartModel.prototype.deleteFlow = function(ID) {
if(typeof ID === 'string') {
for(var i=0; i < this._flows.length; i++) {
if(this._flows[i].getProperties().ID === ID) {
this._flows.splice(i, 1);
}
}
}
};
BarChartModel.prototype.deleteAllFlows = function() {
this._flows = [];
};
BarChartModel.prototype.updateRecord = function(flowID, index, newRecord) {
var filteredFlows = this._flows.filter(function(flow) {return flow.getProperties().ID === flowID;});
if(filteredFlows.length > 0) {
var flow = filteredFlows[0];
return flow.updateRecord(index, newRecord);
}
else {
console.log('Error: 211');
return 211;
}
};
module.exports = BarChartModel;
|
JavaScript
| 0.000001 |
@@ -509,171 +509,8 @@
);%0A%0A
-BarChartModel.prototype = new GraphModel(%7BID: 'ex'%7D);%0ABarChartModel.prototype.constructor = BarChartModel;%0ABarChartModel.prototype.parent = GraphModel.prototype;%0A%0A
func
@@ -1488,16 +1488,188 @@
;%0A%09%7D%0A%7D%0A%0A
+BarChartModel.prototype = Object.create(GraphModel.prototype);%0ABarChartModel.prototype.constructor = BarChartModel;%0ABarChartModel.prototype.parent = GraphModel.prototype;%0A%0A
%0ABarChar
|
3456ca3c2112e15b2bd4bd4b0290be4f953c62d9
|
Add Integer>>#asDouble primitive
|
src/som/primitives/IntegerPrimitives.js
|
src/som/primitives/IntegerPrimitives.js
|
/*
* Copyright (c) 2014 Stefan Marr, [email protected]
*
* 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.
*/
// @ts-check
import { intOrBigInt, isInIntRange } from '../../lib/platform.js';
import { SBigInteger } from '../vmobjects/numbers.js';
import { Primitives } from './Primitives.js';
import { universe } from '../vm/Universe.js';
import { SString } from '../vmobjects/SString.js';
function toNumber(val) {
if (val instanceof SBigInteger) {
return Number(val.getEmbeddedBigInteger());
}
return val.getEmbeddedInteger();
}
function _asString(_frame, args) {
return args[0].primAsString();
}
function _sqrt(_frame, args) {
const res = Math.sqrt(args[0].getEmbeddedInteger());
if (res === Math.floor(res)) {
return universe.newInteger(Math.floor(res));
}
return universe.newDouble(res);
}
function _atRandom(_frame, args) {
return universe.newInteger(Math.floor(args[0].getEmbeddedInteger()
* Math.random()));
}
function _plus(_frame, args) {
return args[0].primAdd(args[1]);
}
function _minus(_frame, args) {
return args[0].primSubtract(args[1]);
}
function _mult(_frame, args) {
return args[0].primMultiply(args[1]);
}
function _doubleDiv(_frame, args) {
return args[0].primDoubleDiv(args[1]);
}
function _intDiv(_frame, args) {
return args[0].primIntDiv(args[1]);
}
function _mod(_frame, args) {
return args[0].primModulo(args[1]);
}
function _and(_frame, args) {
return args[0].primAnd(args[1]);
}
function _equals(_frame, args) {
return args[0].primEquals(args[1]);
}
function _equalsEquals(_frame, args) {
return args[0].primEquals(args[1]);
}
function _lessThan(_frame, args) {
return args[0].primLessThan(args[1]);
}
function _fromString(_frame, args) {
const param = args[1];
if (!(param instanceof SString)) {
return universe.nilObject;
}
const i = BigInt(param.getEmbeddedString());
return intOrBigInt(i, universe);
}
function _leftShift(_frame, args) {
const r = toNumber(args[1]);
const l = toNumber(args[0]);
const result = l << r;
if (Math.floor(l) !== l || !isInIntRange(result) || !isInIntRange(l * (2 ** r))) {
let big = BigInt(l);
big *= BigInt(2 ** r);
return universe.newBigInteger(big);
}
return universe.newInteger(result);
}
function _bitXor(_frame, args) {
const right = toNumber(args[1]);
const left = toNumber(args[0]);
return universe.newInteger(left ^ right);
}
function _rem(_frame, args) {
const right = args[1];
const left = args[0];
return universe.newInteger(left.getEmbeddedInteger()
% right.getEmbeddedInteger());
}
function _as32BitUnsignedValue(_frame, args) {
return args[0].prim32BitUnsignedValue();
}
function _as32BitSignedValue(_frame, args) {
return args[0].prim32BitSignedValue();
}
function _unsignedRightShift(_frame, args) {
const right = toNumber(args[1]);
const left = toNumber(args[0]);
return universe.newInteger(left >>> right);
}
class IntegerPrimitives extends Primitives {
installPrimitives() {
this.installInstancePrimitive('asString', _asString);
this.installInstancePrimitive('sqrt', _sqrt);
this.installInstancePrimitive('atRandom', _atRandom);
this.installInstancePrimitive('+', _plus);
this.installInstancePrimitive('-', _minus);
this.installInstancePrimitive('*', _mult);
this.installInstancePrimitive('//', _doubleDiv);
this.installInstancePrimitive('/', _intDiv);
this.installInstancePrimitive('%', _mod);
this.installInstancePrimitive('&', _and);
this.installInstancePrimitive('=', _equals);
this.installInstancePrimitive('==', _equalsEquals, true);
this.installInstancePrimitive('<', _lessThan);
this.installInstancePrimitive('<<', _leftShift);
this.installInstancePrimitive('bitXor:', _bitXor);
this.installInstancePrimitive('rem:', _rem);
this.installInstancePrimitive('>>>', _unsignedRightShift);
this.installInstancePrimitive('as32BitUnsignedValue', _as32BitUnsignedValue);
this.installInstancePrimitive('as32BitSignedValue', _as32BitSignedValue);
this.installClassPrimitive('fromString:', _fromString);
}
}
export const prims = IntegerPrimitives;
|
JavaScript
| 0 |
@@ -3937,16 +3937,102 @@
ht);%0A%7D%0A%0A
+function _asDouble(_frame, args) %7B%0A return universe.newDouble(toNumber(args%5B0%5D));%0A%7D%0A%0A
class In
@@ -5134,24 +5134,83 @@
nedValue);%0A%0A
+ this.installInstancePrimitive('asDouble', _asDouble);%0A%0A
this.ins
|
721bbe3a78e3ab5ac8b704cf27f82cbbaa7a2d70
|
Fix typo
|
lib/common/dependency-injection/registry.js
|
lib/common/dependency-injection/registry.js
|
'use strict';
/**
* Expose `Registry`.
*/
module.exports = Registry;
/**
* Module dependencies.
*/
var utils = require('../utils'),
BaseRegistry = require('../manipulation/registry')
;
/**
* Initialize a new registry.
*
* @param {danf:object.interfacer} interfacer The interfacer.
* @param {string} interface_ The interface the context should implement (optional).
* @api public
*/
function Registry(interfacer, interface_) {
BaseRegistry.call(this);
if (interface_) {
this.interface = interface_;
}
if (interfacer) {
this.interfacer = interfacer;
}
}
utils.extend(BaseRegistry, Registry);
Registry.defineImplementedInterfaces(['danf:dependencyInjection.provider']);
Registry.defineDependency('_interface', 'string|null');
Registry.defineDependency('_interfacer', 'danf:object.interfacer');
/**
* Set the interface the context should implement (optional).
*
* @param {string}
* @api public
*/
Object.defineProperty(Registry.prototype, 'interface', {
set: function(interface_) {
this._interface = interface_;
if (this._interface) {
for (var name in this._items) {
checkInterface(this._items[name], this._interface);
}
}
}
});
/**
* @interface {danf:dependencyInjection.provider}
*/
Object.defineProperty(Registry.prototype, 'providedType', {
get: function() { return this._interface; }
});
/**
* Set the interfacer.
*
* @param {danf:object.interfacer} The interfacer.
* @api public
*/
Object.defineProperty(Registry.prototype, 'interfacer', {
set: function(interfacer) { this._interfacer = interfacer; }
});
/**
* @interface {danf:manipulation.registry}
*/
Registry.prototype.register = function(name, item) {
checkInterface(item, this._interface);
this._items[name] = item;
}
/**
* @interface {danf:dependencyInjection.provider}
*/
Registry.prototype.provide = function() {
var args = Array.prototype.slice.call(arguments, 1, 2);
return this.get(args[0]);
}
/**
* Check if the class implements the interface.
*
* @param {function} class_ The class.
* @param {string} interface_ The interface.
* @throw {error} If the class does not implement the interface.
* @api private
*/
var checkInterface = function(class_, interface_) {
try {
if (interface_) {
Object.checkType(item, interface_));
}
} catch (error) {
if (error.instead) {
throw new Error('The registered object should be {0}; {1} given instead.'.format(
error.expected,
error.instead
));
}
throw error;
}
}
|
JavaScript
| 0.999999 |
@@ -2387,17 +2387,16 @@
erface_)
-)
;%0A
|
a76e769741fdbede78f11dd942ff6732e317fe3a
|
Update up to changes in es5-ext package
|
lib/assert.js
|
lib/assert.js
|
'use strict';
var Assert = require('test/assert').Assert
, bindMethods = require('es5-ext/lib/Object/bind-methods')
, never, neverBind;
never = function (message) {
this.fail({
message: message,
operator: "never"
});
};
neverBind = function (message) {
return never.bind(this, message);
};
module.exports = function (logger) {
var assert = new Assert({
pass: logger.pass.bind(logger),
fail: logger.fail.bind(logger),
error: logger.error.bind(logger)
});
assert = bindMethods(assert.strictEqual.bind(assert),
assert, Assert.prototype);
assert.not = assert.notStrictEqual;
assert.deep = assert.deepEqual;
assert.notDeep = assert.notDeepEqual;
assert.never = never.bind(assert);
assert.never.bind = neverBind.bind(assert);
return assert;
};
|
JavaScript
| 0 |
@@ -16,19 +16,14 @@
var
-Assert
+extend
= r
@@ -34,89 +34,125 @@
re('
-t
es
-t/assert').Assert%0A , bindMethods = require('es5-ext/lib/Object/bind-methods')
+5-ext/lib/Object/extend')%0A , map = require('es5-ext/lib/Object/map')%0A , Assert = require('test/assert').Assert
%0A%0A
@@ -525,19 +525,14 @@
t =
-bindMethods
+extend
(ass
@@ -567,16 +567,12 @@
,%0A%09%09
-assert,
+map(
Asse
@@ -583,16 +583,68 @@
rototype
+, function (method) %7B return method.bind(assert); %7D)
);%0A%0A%09ass
|
4e2611e5820566e776cb088a56c5829ee8b77795
|
Update the charts to look at the correct data attribute
|
lib/memdash/server/public/charts.js
|
lib/memdash/server/public/charts.js
|
$(document).ready(function(){
$.jqplot('gets-sets', [$("#gets-sets").data("gets"), $("#gets-sets").data("sets")], {
title: 'Gets & Sets for the Past Day',
grid: {
drawBorder: false,
shadow: false,
background: '#fefefe'
},
axes:{
xaxis:{
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString:'%#I %p'
},
min: $("#gets-sets").data("gets")[0][0],
max: $("#gets-sets").data("gets")[$("#gets-sets").data("gets").length - 1][0],
tickInterval: "2 hours",
}
},
seriesDefaults: {
rendererOptions: {
smooth: true
}
},
series: [
{label: 'Gets', showMarker: false},
{label: 'Sets', showMarker: false},
],
legend: {
show: true
},
seriesColors: ["rgb(36, 173, 227)", "rgb(227, 36, 132)"]
});
$.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], {
title: 'Hits & Misses for the Past Day',
grid: {
drawBorder: false,
shadow: false,
background: '#fefefe'
},
axes:{
xaxis:{
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString:'%#I %p'
},
min: $("#hits-misses").data("hits")[0][0],
max: $("#hits-misses").data("hits")[$("#hits-misses").data("hits").length - 1][0],
tickInterval: "2 hours",
},
yaxis: {
rendererOptions: { forceTickAt0: true, forceTickAt100: true }
}
},
seriesDefaults: {
rendererOptions: {
smooth: true
}
},
series: [
{label: 'Hits', showMarker: false},
{label: 'Misses', showMarker: false}
],
legend: {
show: true
},
seriesColors: ["rgb(227, 36, 132)", "rgb(227, 193, 36)"]
});
$.jqplot('memory-usage', [$("#memory-usage").data("limit-maxbytes"), $("#memory-usage").data("bytes")], {
title: 'Cache Memory for the Past Day',
grid: {
drawBorder: false,
shadow: false,
background: '#fefefe'
},
axes:{
xaxis:{
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString:'%#I %p'
},
min: $("#memory-usage").data("limit-maxbytes")[0][0],
max: $("#memory-usage").data("limit-maxbytes")[$("#memory-usage").data("limit-maxbytes").length - 1][0],
tickInterval: "2 hours",
}
},
seriesDefaults: {
rendererOptions: {
smooth: true
}
},
series: [
{label: 'Max Size (MB)', showMarker: false},
{label: 'Used (MB)', showMarker: false}
],
legend: {
show: true
},
seriesColors: ["rgb(227, 193, 36)", "rgb(36, 173, 227)"]
});
$.jqplot('current-items', [$("#current-items").data("current-items")], {
title: 'Items over the Past Day',
grid: {
drawBorder: false,
shadow: false,
background: '#fefefe'
},
axes:{
xaxis:{
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {
formatString:'%#I %p'
},
min: $("#current-items").data("current-items")[0][0],
max: $("#current-items").data("current-items")[$("#current-items").data("current-items").length - 1][0],
tickInterval: "2 hours",
},
yaxis: {
rendererOptions: { forceTickAt0: true, forceTickAt100: true }
}
},
seriesDefaults: {
rendererOptions: {
smooth: true,
}
},
series: [
{label: 'Items', showMarker: false},
],
legend: {
show: true
},
seriesColors: ["rgb(227, 193, 36)"]
});
});
|
JavaScript
| 0 |
@@ -1855,37 +1855,38 @@
y-usage%22).data(%22
-limit
+engine
-maxbytes%22), $(%22
@@ -2222,37 +2222,38 @@
y-usage%22).data(%22
-limit
+engine
-maxbytes%22)%5B0%5D%5B0
@@ -2285,37 +2285,38 @@
y-usage%22).data(%22
-limit
+engine
-maxbytes%22)%5B$(%22#
@@ -2340,13 +2340,14 @@
ta(%22
-limit
+engine
-max
|
f9062d539578eb66602a5ee8d4c17745dccf1a85
|
update legacy file
|
lib/neuron/legacy/neuron-2.0-1.0.js
|
lib/neuron/legacy/neuron-2.0-1.0.js
|
;(function(K){
function alias(aliasKey, standardKey, noDeprecated){
var proto = DOMInit.prototype,
standard = proto[standardKey];
proto[aliasKey] = function(){
if(!noDeprecated && window.console){
console.warn && console.warn(
'WARNING: .' + aliasKey + '() method is deprecated, please use .' + standardKey + '() instead ASAP!'
);
// console.trace && console.trace();
}
return standard.apply(this, arguments);
}
};
var
DOMInit = K.DOM._;
alias('all', 'find');
alias('el', 'get');
alias('contains', 'has');
alias('match', 'is');
// alias()
})(NR);
|
JavaScript
| 0 |
@@ -628,24 +628,27 @@
l', 'get');%0A
+//
alias('conta
|
2c5acb4e8663624acd89a58996fa0b2ec4484aea
|
Remove deprecations
|
lib/common.js
|
lib/common.js
|
'use babel'
import pathUtils from 'path'
export default {
splitCells(line){
return line.trim().replace(/[ ]{2,}/g, '\t').split(/\t+/);
},
getCurrentResource(path, autocompleteRobotProvider){
// support for deprecated consumer API.
if(typeof autocompleteRobotProvider.getResourceKeys === 'undefined') return undefined
path = pathUtils.normalize(path)
for(const resourceKey of autocompleteRobotProvider.getResourceKeys()){
const resource = autocompleteRobotProvider.getResourceByKey(resourceKey)
if(resource && path===resource.path){
return resource
}
}
return undefined
}
// ,
// buildResourcesByName(autocompleteRobotProvider){
// const resourcesByName = new Map()
// for(const resourceKey of resourceKeys){
// const resource = autocompleteRobotProvider.getResourceByKey(resourceKey)
// let reslist = resourcesByName.get(resource.name)
// if(!reslist){
// reslist = []
// resourcesByName.set(resource.name, reslist)
// }
// reslist.push(resource)
// }
//
// }
}
|
JavaScript
| 0.999122 |
@@ -199,143 +199,8 @@
r)%7B%0A
- // support for deprecated consumer API.%0A if(typeof autocompleteRobotProvider.getResourceKeys === 'undefined') return undefined%0A%0A
@@ -497,463 +497,6 @@
%7D%0A
-%0A // ,%0A // buildResourcesByName(autocompleteRobotProvider)%7B%0A // const resourcesByName = new Map()%0A // for(const resourceKey of resourceKeys)%7B%0A // const resource = autocompleteRobotProvider.getResourceByKey(resourceKey)%0A // let reslist = resourcesByName.get(resource.name)%0A // if(!reslist)%7B%0A // reslist = %5B%5D%0A // resourcesByName.set(resource.name, reslist)%0A // %7D%0A // reslist.push(resource)%0A // %7D%0A //%0A // %7D%0A%0A
%7D%0A
|
76f7a4456aef23085058021582cfa522b3f2b264
|
Update dasher.js
|
lib/dasher.js
|
lib/dasher.js
|
var url = require('url')
var dashButton = require('node-dash-button');
var request = require('request')
const execFile = require('child_process').execFile;
function doLog(message) {
console.log('[' + (new Date().toISOString()) + '] ' + message);
}
function DasherButton(button) {
var options = {headers: button.headers, body: button.body, json: button.json, formData: button.formData}
var debug = button.debug || false;
this.dashButton = dashButton(button.address, button.interface, button.timeout, button.protocol)
var buttonList = {};
this.dashButton.on("detected", function() {
if(!buttonList.hasOwnProperty(button.address)){
buttonList[button.address] = 1;
} else {
buttonList[button.address]++;
}
doLog(button.name + " pressed. Count: " + buttonList[button.address]);
if (debug){
doLog("Debug mode, skipping request.");
console.log(button);
} else if (typeof button.cmd !== 'undefined' && button.cmd != "") {
doCommand(button.cmd, button.name)
} else {
doRequest(button.url, button.method, options)
}
})
doLog(button.name + " added.")
}
function doCommand(command, name, callback) {
const child = execFile(command, [name], (error, stdout, stderr) => {
if (error) {
// Stripping a trailing new line
output = stderr.replace (/\s+$/g, "");
doLog(`There was an error: ${output}`);
}
if (stdout != "") {
// Stripping a trailing new line
output = stdout.replace (/\s+$/g, "");
doLog(`Command output: ${output}`);
}
});
}
function doRequest(requestUrl, method, options, callback) {
options = options || {}
options.query = options.query || {}
options.json = options.json || false
options.headers = options.headers || {}
var reqOpts = {
url: url.parse(requestUrl),
method: method || 'GET',
qs: options.query,
body: options.body,
json: options.json,
headers: options.headers,
formData: options.formData
}
request(reqOpts, function onResponse(error, response, body) {
if (error) {
doLog("there was an error");
console.log(error);
} else {
if (response.statusCode === 401) {
doLog("Not authenticated");
}
if (response.statusCode < 200 || response.statusCode > 299) {
doLog("Unsuccessful status code");
}
}
if (callback) {
callback(error, response, body)
}
})
}
module.exports = DasherButton
|
JavaScript
| 0 |
@@ -148,16 +148,41 @@
xecFile;
+%0Aprocess.title = %22dasher%22
%0A%0Afuncti
|
0d1288a08e9236757b6b98aa3255abe96a89b939
|
remove preventdefault for j and b keys
|
lib/events.js
|
lib/events.js
|
const scoreboard = require('./scoreboard');
const collisionSound = new Audio();
const $ = require('jquery');
const startButtonClick = (game) => {
game.canvas.addEventListener('click', function checkForButtonClick(e) {
if (e.offsetY > 225 && e.offsetY < 290 && e.offsetX > 190 && e.offsetX < 300) {
game.canvas.removeEventListener('click', checkForButtonClick);
game.reset();
}
});
};
const launchJorgeMode = (game) => {
window.addEventListener('keydown', function(e) {
if (e.which === 74) {
e.preventDefault();
$('body').addClass('jorge');
game.bird.jorgeMode();
game.pipes[0].mode = 'jorge';
game.pipes[1].mode = 'jorge';
}
});
};
const launchBirdMode = (game) => {
window.addEventListener('keydown', function(e) {
if (e.which === 66) {
// e.preventDefault();
$('body').removeClass('jorge');
game.bird.birdMode();
game.pipes[0].mode = 'bird';
game.pipes[1].mode = 'bird';
}
});
};
const addBirdMoveEvents = (game) => {
game.score.increment;
game.canvas.addEventListener('click', () => { game.bird.spacebarPress; });
document.addEventListener('keydown', (e) => {
if (e.which === 32) {
e.preventDefault();
game.bird.spacebarPress;
}
});
game.collision.on('collisionEvent', () => {
collisionSound.src = `/assets/sounds/${game.bird.mode}-hit.ogg`;
collisionSound.play();
game.bird.alive = false;
game.active = false;
scoreboard.addScore(game.score.score);
});
};
module.exports = {
startButtonClick: startButtonClick,
addBirdMoveEvents: addBirdMoveEvents,
launchJorgeMode: launchJorgeMode,
launchBirdMode: launchBirdMode
};
|
JavaScript
| 0.000001 |
@@ -522,34 +522,8 @@
) %7B%0A
- e.preventDefault();%0A
@@ -786,37 +786,8 @@
) %7B%0A
- // e.preventDefault();%0A
|
a04ef24a8016b3618785f761ab472972780b6f11
|
add itunes keywords field (#59)
|
lib/fields.js
|
lib/fields.js
|
const fields = module.exports = {};
fields.feed = [
['author', 'creator'],
['dc:publisher', 'publisher'],
['dc:creator', 'creator'],
['dc:source', 'source'],
['dc:title', 'title'],
['dc:type', 'type'],
'title',
'description',
'author',
'pubDate',
'webMaster',
'managingEditor',
'generator',
'link',
];
fields.item = [
['author', 'creator'],
['dc:creator', 'creator'],
['dc:date', 'date'],
['dc:language', 'language'],
['dc:rights', 'rights'],
['dc:source', 'source'],
['dc:title', 'title'],
'title',
'link',
'pubDate',
'author',
'content:encoded',
'enclosure',
'dc:creator',
'dc:date',
];
var mapItunesField = function(f) {
return ['itunes:' + f, f];
}
fields.podcastFeed = ([
'author',
'subtitle',
'summary',
'explicit'
]).map(mapItunesField);
fields.podcastItem = ([
'author',
'subtitle',
'summary',
'explicit',
'duration',
'image',
'episode',
'image',
'season',
]).map(mapItunesField);
|
JavaScript
| 0 |
@@ -949,16 +949,30 @@
eason',%0A
+ 'keywords',%0A
%5D).map(m
|
ccae88a40dbdf46632016db11cce4d48d98d96e2
|
Fix for double getLayers in addlayer.js
|
lib/registry/components/addlayer.js
|
lib/registry/components/addlayer.js
|
var tpl = require('components/addlayer.html');
var Component = require('components/component');
var component = new Component(tpl, 'addlayer');
var Awesomplete = require('awesomplete.min');
var list = require('sources/list.json');
var utils = require('utils');
var $ = utils.$;
var olMap = require('olMap');
var map = olMap.get();
// make sure toolbar initialised
require('components/toolbar');
// add addlayertemplate to toolbar
$('#layers-content').appendChild(component.getTemplate('addlayer'));
new Awesomplete(document.querySelector('#rastercode'), {list: list, minChars: 1});
var mapDef = require('mapDef').get();
var rasters = require('rasters');
var vectors = require('vectors');
$('#addraster').addEventListener('click', function() {
var code = $('#rastercode').value;
System.import('sources/' + code)
.then(function(m) {
var options;
// use apikey if entered
if ($('#api').value) {
options = {rasters: []};
var raster = {};
raster[code] = $('#api').value;
options.rasters.push(raster);
}
rasters.add([m], options);
mapDef.rasters = mapDef.rasters || [];
mapDef.rasters.push(code);
var id = m.getLayers()[0].getProperties().id;
var bound = rasters.changeLayer.bind(map);
bound(id);
// won't exist if started from 0
var div = $('#' + id.replace(/ /g,''));
if (div) {
div.checked = true;
}
});
});
$('#addvector').addEventListener('click', function() {
var option = {
add: true
};
if ($('#mongodb').checked === true) {
option.format = 'mongo';
}
if ($('#vectorurl').value) {
var url = $('#vectorurl').value;
option.url = url;
option.id = $('#vectorname').value || url;
addVectors(option);
}
if ($('#vectorfile').files.length > 0) { // file entered
var file = $('#vectorfile').files[0];
option.type = 'file';
option.filename = file.name;
option.id = $('#vectorname').value || file.name;
var reader = new FileReader();
reader.onload = function(e) {
option.file = e.target.result;
addVectors(option);
};
reader.readAsText(file);
}
function addVectors(option) {
vectors.add({vectors: [option]});
if (rasters.getLayers().getLength() === 0) {
olMap.use4326View();
}
$('#vectorurl').value = '';
$('#fileform').reset();
delete option.add;
mapDef.vectors = mapDef.vectors || [];
mapDef.vectors.push(option);
}
});
|
JavaScript
| 0 |
@@ -1161,29 +1161,84 @@
var
-id = m.getLayers()%5B0%5D
+layers = rasters.getLayers();%0A var id = layers.item(layers.getLength()-1)
.get
|
e7ecde5bcab31eaf2bb155ea15724f4300083931
|
Add default value for `serve` callback
|
serve.js
|
serve.js
|
#!/usr/bin/env node
var express = require('express');
var taskist = require('taskist');
var sugar = require('object-sugar');
var config = require('./config');
var tasks = require('./tasks');
var api = require('./api');
if(require.main === module) {
main();
}
module.exports = main;
function main(cb) {
var db = 'db';
sugar.connect(db, function(err) {
if(err) {
return console.error('Failed to connect to database', db, err);
}
console.log('Connected to database');
console.log('Initializing tasks');
initTasks();
console.log('Starting server');
serve(cb);
});
}
function initTasks() {
taskist(config.tasks, tasks, {
instant: true
});
}
function serve(cb) {
var app = express();
var port = config.port;
app.configure(function() {
app.set('port', port);
app.disable('etag');
app.use(express.logger('dev'));
app.use(app.router);
});
app.configure('development', function() {
app.use(express.errorHandler());
});
api(app);
process.on('exit', terminator);
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS',
'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGTERM'
].forEach(function(element) {
process.on(element, function() { terminator(element); });
});
app.listen(port, function() {
console.log('%s: Node (version: %s) %s started on %d ...', Date(Date.now() ), process.version, process.argv[1], port);
cb(null);
});
}
function terminator(sig) {
if(typeof sig === 'string') {
console.log('%s: Received %s - terminating Node server ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
}
|
JavaScript
| 0.000002 |
@@ -756,24 +756,46 @@
serve(cb) %7B%0A
+ cb = cb %7C%7C noop;%0A%0A
var app
@@ -1864,12 +1864,32 @@
ow()) );%0A%7D%0A%0A
+function noop() %7B%7D%0A%0A
|
3b73d782113b83bf18f276aabbc965850c4a49da
|
Allow for no initial setup
|
setup.js
|
setup.js
|
var options = require("commander");
var q = require("q");
var BigIp = require('./lib/bigIp');
var globalSettings = {
guiSetup: 'disabled'
};
var dbVars = {};
var previousOperationMessage;
var bigIp;
var collect = function(val, collection) {
collection.push(val);
return collection;
};
var map = function(pair, map) {
var nameVal = pair.split(':');
map[nameVal[0].trim()] = nameVal[1].trim();
};
options
.option('--host <ip_address>', 'BIG-IP management IP.')
.option('-u, --user <user>', 'BIG-IP admin user.')
.option('-p, --password <password>', 'BIG-IP admin user password.')
.option('-l, --license <license_key>', 'BIG-IP license key.')
.option('-a, --add-on <add-on keys>', 'Add on license keys.', collect, [])
.option('-n, --host-name <hostname>', 'Set BIG-IP hostname')
.option('-g, --global-settings <name: value>', 'A global setting name/value pair. For multiple settings, use multiple -g entries', map, globalSettings)
.option('-d, --db <name: value>', 'A db variable name/value pair. For multiple settings, use multiple -d entries', map, dbVars)
.parse(process.argv);
bigIp = new BigIp(options.host, options.user, options.password);
console.log("Waiting for BIG-IP to be ready...");
bigIp.ready()
.then(function() {
console.log("BIG-IP is ready.");
console.log("Performing initial setup...");
var nameServers = ["10.133.20.70", "10.133.20.71"];
var timezone = 'UTC';
var ntpServers = ["0.us.pool.ntp.org", "1.us.pool.ntp.org"];
return bigIp.initialSetup(
{
dns: {
nameServers: nameServers
},
ntp: {
timezone: timezone,
servers: ntpServers
},
hostname: options.hostName,
globalSettings: globalSettings
}
);
})
.then(function() {
console.log("Initial setup complete.");
if (Object.keys(dbVars).length > 0) {
console.log("Setting DB vars");
previousOperationMessage = "Db vars set";
return bigIp.setDbVars(dbVars);
}
else {
return q();
}
})
.then(function() {
if (previousOperationMessage) {
console.log(previousOperationMessage);
}
var registrationKey = options.license;
var addOnKeys = options.addOn;
if (registrationKey || addOnKeys.length > 0) {
console.log("Licensing...");
return bigIp.license(
{
registrationKey: registrationKey,
addOnKeys: addOnKeys
}
);
}
return q();
})
.then(function(response) {
if (response) {
console.log(response);
}
console.log("BIG-IP setup complete.");
})
.catch(function(err) {
console.log("BIG-IP setup failed: " + (typeof err === 'object' ? err.message : err));
})
.done();
|
JavaScript
| 0 |
@@ -1328,60 +1328,8 @@
.%22);
-%0A console.log(%22Performing initial setup...%22);
%0A%0A
@@ -1498,53 +1498,30 @@
-return bigIp.initialSetup(%0A %7B%0A
+var initialConfig = %7B%0A
@@ -1531,28 +1531,24 @@
dns: %7B%0A
-
@@ -1584,35 +1584,27 @@
- %7D,%0A
+%7D,%0A
@@ -1606,28 +1606,24 @@
ntp: %7B%0A
-
@@ -1662,20 +1662,16 @@
-
-
servers:
@@ -1686,36 +1686,32 @@
ers%0A
-
%7D,%0A
@@ -1709,20 +1709,16 @@
-
-
hostname
@@ -1737,20 +1737,16 @@
stName,%0A
-
@@ -1792,102 +1792,468 @@
- %7D%0A );%0A %7D)%0A .then(function() %7B%0A console.log(%22Initial setup complete.%22);
+%7D;%0A%0A if (Object.keys(initialConfig).length) %7B%0A console.log(%22Performing initial setup...%22);%0A previousOperationMessage = %22Initial setup complete%22;%0A return bigIp.initialSetup(initialConfig);%0A %7D%0A else %7B%0A return q();%0A %7D%0A %7D)%0A .then(function() %7B%0A if (previousOperationMessage) %7B%0A console.log(previousOperationMessage);%0A previousOperationMessage = '';%0A %7D
%0A%0A
@@ -2610,32 +2610,75 @@
rationMessage);%0A
+ previousOperationMessage = '';%0A
%7D%0A%0A
|
4455aced53c92a6bd26d3c3fe061a61cbcab59c1
|
change default border style for Ui.ComboItem
|
era/ui/combo.js
|
era/ui/combo.js
|
Ui.Button.extend('Ui.Combo', {
field: undefined,
data: undefined,
position: -1,
current: undefined,
placeHolder: '...',
sep: undefined,
/**
* @constructs
* @class
* @extends Ui.Pressable
* @param {String} [config.field] Name of the data's field to display in the list
* @param [config.data] Object List
* @param [currentAt] Default selected object position
* @param [current] Default selected object
* @param [placeHolder] Text displays when no selection
*/
constructor: function(config) {
this.addEvents('change');
this.arrowtop = new Ui.Icon({ icon: 'arrowtop', width: 10, height: 10 });
this.arrowbottom = new Ui.Icon({ icon: 'arrowbottom', width: 10, height: 10 });
this.setMarker(new Ui.VBox({ verticalAlign: 'center',
content: [ this.arrowtop, this.arrowbottom ], marginRight: 5 }));
},
setPlaceHolder: function(placeHolder) {
this.placeHolder = placeHolder;
if(this.position === -1)
this.setText(this.placeHolder);
},
setField: function(field) {
this.field = field;
if(this.data !== undefined)
this.setData(this.data);
},
setData: function(data) {
this.data = data;
},
/**Read only*/
getData: function(){
return this.data;
},
getPosition: function() {
return this.position;
},
setCurrentAt: function(position) {
if(position === -1) {
this.position = -1;
this.current = undefined;
this.setText(this.placeHolder);
this.fireEvent('change', this, this.current, this.position);
}
else if((position >= 0) && (position < this.data.length)) {
this.current = this.data[position];
this.position = position;
this.setText(this.current[this.field]);
this.fireEvent('change', this, this.current, this.position);
}
},
getCurrent: function() {
return this.current;
},
getValue: function() {
return this.current;
},
setCurrent: function(current) {
if(current === undefined)
this.setCurrentAt(-1);
var position = -1;
for(var i = 0; i < this.data.length; i++) {
if(this.data[i] == current) {
position = i;
break;
}
}
if(position != -1)
this.setCurrentAt(position);
},
onItemPress: function(popup, item, position) {
this.setCurrentAt(position);
}
}, {
onPress: function() {
var popup = new Ui.ComboPopup({ field: this.field, data: this.data });
if(this.position !== -1)
popup.setCurrentAt(this.position);
this.connect(popup, 'item', this.onItemPress);
popup.show(this);
},
updateColors: function() {
Ui.Combo.base.updateColors.apply(this, arguments);
this.arrowtop.setFill(this.getForeground());
this.arrowbottom.setFill(this.getForeground());
}
});
Ui.MenuPopup.extend('Ui.ComboPopup', {
list: undefined,
data: undefined,
field: undefined,
constructor: function(config) {
this.addEvents('item');
this.setAutoHide(true);
this.list = new Ui.VBox();
this.setContent(this.list);
},
setField: function(field) {
this.field = field;
if(this.data !== undefined)
this.setData(this.data);
},
setData: function(data) {
this.data = data;
if(this.field === undefined)
return;
for(var i = 0; i < data.length; i++) {
var item = new Ui.ComboItem({ text: data[i][this.field] });
this.connect(item, 'press', this.onItemPress);
this.list.append(item);
}
},
setCurrentAt: function(pos) {
this.list.getChildren()[pos].setIsActive(true);
},
onItemPress: function(item) {
var position = -1;
for(var i = 0; i < this.list.getChildren().length; i++) {
if(this.list.getChildren()[i] == item) {
position = i;
break;
}
}
this.fireEvent('item', this, item, position);
this.hide();
}
});
Ui.Button.extend('Ui.ComboItem');
|
JavaScript
| 0 |
@@ -3636,17 +3636,60 @@
i.ComboItem'
+, %7B%7D, %7B%7D, %7B%0A%09style: %7B%0A%09%09borderWidth: 0%0A%09%7D%0A%7D
);%0A%09%0A
|
6965b0b02942b5faf373bfea78a3e2d7ad68b1c3
|
allow setFill(undefined) to use the style property
|
era/ui/shape.js
|
era/ui/shape.js
|
Ui.CanvasElement.extend('Ui.Shape',
/**@lends Ui.Shape*/
{
fill: undefined,
path: undefined,
scale: 1,
/**
* @constructs
* @class
* @extends Ui.Element
*/
constructor: function(config) {
},
setScale: function(scale) {
if(this.scale != scale) {
this.scale = scale;
this.invalidateDraw();
}
},
getFill: function() {
if(this.fill === undefined)
return Ui.Color.create(this.getStyleProperty('color'));
else
return this.fill;
},
setFill: function(fill) {
if(this.fill !== fill) {
if(typeof(fill) === 'string')
fill = Ui.Color.create(fill);
else
fill = Ui.Element.create(fill);
this.fill = fill;
this.invalidateDraw();
}
},
setPath: function(path) {
if(this.path != path) {
this.path = path;
this.invalidateDraw();
}
}
}, {
onStyleChange: function() {
this.invalidateDraw();
},
updateCanvas: function(ctx) {
if(this.path === undefined)
return;
if(this.scale != 1)
ctx.scale(this.scale, this.scale);
this.svgPath(this.path);
var fill = this.getFill();
if(Ui.Color.hasInstance(fill))
ctx.fillStyle = fill.getCssRgba();
else if(Ui.LinearGradient.hasInstance(fill))
ctx.fillStyle = fill.getCanvasGradient(ctx, this.getLayoutWidth(), this.getLayoutHeight());
ctx.fill();
}
}, {
style: {
color: new Ui.Color({ r: 0, g: 0, b: 0 })
}
});
|
JavaScript
| 0 |
@@ -584,24 +584,47 @@
ll);%0A%09%09%09else
+ if(fill !== undefined)
%0A%09%09%09%09fill =
|
e48ea6b75c2930ceb9955a5658e88f1d8ee34a8c
|
add maintenance detect in music_jp
|
lyric_engine_js/modules/music_jp.js
|
lyric_engine_js/modules/music_jp.js
|
const URL = require('url');
const util = require('util');
const iconv = require('iconv-lite');
const he = require('he');
const rp = require('request-promise');
const striptags = require('striptags');
const LyricBase = require('../include/lyric_base');
const keyword = 'music-book.jp';
class Lyric extends LyricBase {
async get_artist_id(url) {
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2141.0 Safari/537.36'
};
const html = await rp({
method: 'POST',
uri:url,
headers: headers
});
const pattern = "checkFavorite\\('([0-9]+)'\\)";
const id = this.get_first_group_by_pattern(html, pattern);
return id;
}
async get_song_json(url) {
const artist_id = await this.get_artist_id(url);
if (!artist_id) {
console.error('Failed to get artist id of url:', url);
return false;
}
console.log('artist_id is', artist_id);
const url_object = URL.parse(url, true);
const pos = url_object.pathname.lastIndexOf('/');
const pid = url_object.pathname.substr(pos + 1);
console.log('pid:', pid);
const post_url = 'http://music-book.jp/music/MusicDetail/GetLyric';
const body = {
'artistId': artist_id,
'artistName': decodeURIComponent(url_object.query.artistname),
'title': (url_object.query.title),
'muid': '',
'pid': pid,
'packageName': decodeURIComponent(url_object.query.packageName),
};
const json = await rp({
method: 'POST',
uri: post_url,
form: body,
json: true,
})
return json;
}
async find_lyric(url, json) {
let lyric = json.Lyrics;
lyric = lyric.replace(/<br \/>/g, '\n');
lyric = lyric.trim();
this.lyric = lyric;
return true;
}
async find_info(url, json) {
const url_object = URL.parse(url, true);
this.title = decodeURIComponent(url_object.query.title);
this.artist = decodeURIComponent(url_object.query.artistname);
this.lyricist = json.Writer;
this.composer = json.Composer;
}
async parse_page() {
const url = this.url;
const json = await this.get_song_json(url);
await this.find_lyric(url, json);
await this.find_info(url, json);
return true;
}
}
exports.keyword = keyword;
exports.Lyric = Lyric;
if (require.main === module) {
(async function() {
const url = 'http://music-book.jp/music/Kashi/aaa6rh9s?artistname=%25e5%2580%2589%25e6%259c%25a8%25e9%25ba%25bb%25e8%25a1%25a3&title=%25e6%25b8%25a1%25e6%259c%2588%25e6%25a9%258b%2520%25ef%25bd%259e%25e5%2590%259b%2520%25e6%2583%25b3%25e3%2581%25b5%25ef%25bd%259e&packageName=%25e6%25b8%25a1%25e6%259c%2588%25e6%25a9%258b%2520%25ef%25bd%259e%25e5%2590%259b%2520%25e6%2583%25b3%25e3%2581%25b5%25ef%25bd%259e';
const obj = new Lyric(url);
const lyric = await obj.get();
console.log(lyric);
})();
}
|
JavaScript
| 0 |
@@ -323,33 +323,28 @@
async get_
-artist_id
+html
(url) %7B%0A
@@ -624,24 +624,78 @@
%7D);%0A%0A
+ return html;%0A %7D%0A%0A get_artist_id(html) %7B%0A
cons
@@ -855,24 +855,30 @@
ong_json(url
+, html
) %7B%0A
@@ -894,22 +894,16 @@
ist_id =
- await
this.ge
@@ -914,18 +914,19 @@
tist_id(
-ur
+htm
l);%0A
@@ -2431,16 +2431,407 @@
s.url;%0A%0A
+ let html;%0A try %7B%0A html = await this.get_html(url);%0A %7D catch (err) %7B%0A if (err.response && err.response.body && err.response.body.indexOf('%E3%83%A1%E3%83%B3%E3%83%86%E3%83%8A%E3%83%B3%E3%82%B9') %3E= 0) %7B%0A this.lyric = '%E5%8F%AA%E4%BB%8A%E3%83%A1%E3%83%B3%E3%83%86%E3%83%8A%E3%83%B3%E3%82%B9%E4%B8%AD%E3%81%A7%E3%81%99';%0A return true;%0A %7D else %7B%0A console.error(err);%0A return false;%0A %7D%0A %7D %0A%0A
@@ -2871,16 +2871,22 @@
json(url
+, html
);%0A%0A
|
0bd2f25ea1d5661e8602bde8d0993ed4f74a9532
|
Remove confusing dead functions.
|
sheaf.js
|
sheaf.js
|
var ok = require('assert').ok
var path = require('path')
var fs = require('fs')
var mkdirp = require('mkdirp')
var Staccato = require('staccato')
var Signal = require('signal')
var Turnstile = require('turnstile')
Turnstile.Set = require('turnstile/set')
var cadence = require('cadence')
var sequester = require('sequester')
var Cache = require('magazine')
var Locker = require('./locker')
var Page = require('./page')
function compare (a, b) { return a < b ? -1 : a > b ? 1 : 0 }
function extract (a) { return a }
function Sheaf (options) {
this.nextAddress = 0
this.directory = options.directory
this.cache = options.cache || new Cache()
this.options = options
this._checksum = function () { return "0" }
this.tracer = options.tracer || function () { arguments[2]() }
this.extractor = options.extractor || extract
this.comparator = options.comparator || compare
this.player = options.player
this.lengths = {}
this.turnstile = new Turnstile
this._lock = new Turnstile.Set(this, '_locked', this.turnstile)
this._queues = {}
}
Sheaf.prototype.create = function () {
var root = this.createPage(0)
var leaf = this.createPage(1)
this.splice(root, 0, 0, { address: leaf.address, heft: 0 })
ok(root.address == 0, 'root not zero')
return { root: root, leaf: leaf }
}
Sheaf.prototype.unbalanced = function (page, force) {
if (force) {
this.lengths[page.address] = this.options.leafSize
} else if (this.lengths[page.address] == null) {
this.lengths[page.address] = page.items.length - page.ghosts
}
}
Sheaf.prototype.createPage = function (modulus, address) {
return new Page(this, address, modulus)
}
Sheaf.prototype.createMagazine = function () {
var magazine = this.cache.createMagazine()
var cartridge = magazine.hold(-2, {
page: {
address: -2,
items: [{ key: null, address: 0, heft: 0 }],
queue: sequester.createQueue()
}
})
var metaRoot = cartridge.value.page
metaRoot.cartridge = cartridge
metaRoot.lock = metaRoot.queue.createLock()
metaRoot.lock.share(function () {})
this.metaRoot = metaRoot
this.magazine = magazine
}
Sheaf.prototype.createLocker = function () {
return new Locker(this, this.magazine)
}
Sheaf.prototype.find = function (page, key, low) {
var mid, high = page.items.length - 1
while (low <= high) {
mid = low + ((high - low) >>> 1)
var compare = this.comparator(key, page.items[mid].key)
if (compare < 0) high = mid - 1
else if (compare > 0) low = mid + 1
else return mid
}
return ~low
}
Sheaf.prototype.hold = function (id) {
return this._sheaf.hold(id, null)
}
Sheaf.prototype._operate = cadence(function (async, entry) {
})
// TODO Okay, I'm getting tired of having to check canceled and unit test for
// it, so let's have exploding turnstiles (or just let them OOM?) Maybe on
// timeout we crash?
//
// We can ignore canceled here, I believe, and just work through anything left,
// but we should document this as a valid attitude to work in Turnstile.
//
// Writing things out again. Didn't occur to me
Sheaf.prototype._locked = cadence(function (async, envelope) {
var queue = this._queues[envelope.body], entry
console.log('here')
async(function () {
async.loop([], function () {
if (queue.length == 0) {
return [ async.break ]
}
var entry = queue.pop()
async(function () {
switch (entry.method) {
case 'write':
var directory = path.resolve(this.directory, String(envelope.body))
async(function () {
mkdirp(directory, async())
}, function () {
var stream = fs.createWriteStream(path.resolve(directory, 'append'), { flags: 'a' })
var writable = new Staccato.Writable(stream)
async(function () {
async.forEach([ entry.writes ], function (write) {
var header = Buffer.from(JSON.stringify({
position: write.position,
previous: write.previous,
method: write.method,
index: write.index,
length: write.serialized.length
}) + '\n')
var record = Buffer.concat([ header, write.serialized ])
var checksum = JSON.stringify(this._checksum.call(null, record, 0, record.length)) + '\n'
async(function () {
writable.write(checksum, async())
}, function () {
writable.write(record, async())
})
})
}, function () {
writable.end(async())
})
})
break
}
}, function () {
entry.completed.unlatch()
})
})
})
})
Sheaf.prototype.append = function (entry) {
var queue = this._queues[entry.id]
if (queue == null) {
var queue = this._queues[entry.id] = [{ method: 'write', writes: [], completed: new Signal }]
}
queue[0].writes.push(entry)
this._lock.add(entry.id)
return queue.signal
}
module.exports = Sheaf
|
JavaScript
| 0.000002 |
@@ -2674,153 +2674,8 @@
%0A%7D%0A%0A
-Sheaf.prototype.hold = function (id) %7B%0A return this._sheaf.hold(id, null)%0A%7D%0A%0ASheaf.prototype._operate = cadence(function (async, entry) %7B%0A%7D)%0A%0A
// T
|
37e21349b79535482792ac8d013f9a61e65e7d20
|
make cache private
|
shout.js
|
shout.js
|
/*
* Shout.js
*
* A quick and dirty pub/sub thingamajig
*
* Author: Stephen Murray
* Shout.js may be freely distributed under the MIT license.
*/
;(function(){
"use strict";
var shout,
_cache = {},
_delim = /\s+/,
slice = Array.prototype.slice;
function getArgs( args ) {
return slice.call(args, 0);
}
shout = this.shout = {
_cache: _cache,
on: function(){
var args = getArgs(arguments),
events = args[0].split(_delim),
handlers = slice.call(args, 1),
ev;
while ( ev = events.shift() ) {
_cache[ev] = _cache[ev] || [];
for ( var i = 0; i < handlers.length; i++ ) {
_cache[ev].push(handlers[i]);
}
}
return this;
},
off: function(){
var args = getArgs(arguments),
events = args[0].split(_delim),
ev,
retains = [],
handlers = slice.call(args, 1);
while ( ev = events.shift() ) {
_cache[ev] = _cache[ev] || [];
if ( handlers.length ) {
for ( var i = 0; i < _cache[ev].length; i++ ) {
for ( var j = 0; j < handlers.length; j++ ) {
if ( _cache[ev][i] !== handlers[j] ) {
retains.push(_cache[ev][i]);
}
}
}
_cache[ev] = retains;
} else {
delete _cache[ev];
}
}
return this;
},
emit: function(){
var args = getArgs(arguments),
events = args[0].split(_delim),
argsToPass = slice.call(args, 1),
ev,
handlers;
while ( ev = events.shift() ) {
handlers = _cache[ev] || [];
for ( var i = 0; i < handlers.length; i++ ) {
handlers[i].apply(null, argsToPass);
}
}
return this;
}
};
shout.trigger = shout.fire = shout.emit;
}).call(this);
|
JavaScript
| 0 |
@@ -365,29 +365,8 @@
%7B%0A%0A
- _cache: _cache,%0A%0A
|
b3b43d4025e22704d4a8afeaa2f10601babe0a73
|
Fix js
|
modules/editor/assets/js/buttons.js
|
modules/editor/assets/js/buttons.js
|
yii.buttons = (function ($) {
var css = {
panel: '.js-editor-buttons',
preview: '.js-editor-preview'
};
var $btnPanel = $(css.panel);
var pub = {
isActive: true,
init: function () {
$btnPanel.on('click', function (event) {
var $btn = $(event.target);
var $btnName = $btn.attr('data-editor-btn-panel');
var $form = $btn.closest('form');
var $textarea = $form.find('textarea');
if ($btnName == 'preview') {
preview($btn, $textarea);
}
if (!$btn.hasClass('disabled')) {
markUp($btnName, $textarea);
}
return false;
});
}
};
function preview(btn, textarea) {
var message = textarea.val();
var form = textarea.closest('form');
if (btn.hasClass('selected')) {
$('.btn-group > .btn.btn-sm').each(function(){
var btn = $(this);
btn.removeClass('disabled');
});
btn.removeClass('selected');
form.find(css.preview).hide();
textarea.show().focus();
} else {
$('.btn-group > .btn.btn-sm').each(function(){
var btn = $(this);
if (btn.attr('data-editor-btn-panel') == 'preview') {
return true;
}
btn.addClass('disabled');
});
btn.addClass('selected');
textarea.hide();
form.find('.error-summary').hide();
form.find(css.preview).show().html('Загрузка предпросмотра...');
$.ajax({
url: '/post/preview',
type: 'POST',
dataType: 'json',
data: {message: message},
cache: false,
success: function (data) {
form.find(css.preview).show().html(data);
}
});
}
}
function markUp(btn, textarea) {
textarea.focus();
var txt = str = textarea.extractSelectedText();
var len = txt.length;
var tip = '';
if (btn == 'bold') {
tip = '**Полужирный текст**';
if (len > 0) {
if (str == tip) {
str = '';
} else {
str = getBlockMarkUp(txt, '**', '**');
}
} else {
str = tip;
}
} else if (btn == 'italic') {
tip = '*Курсивный текст*';
if (len > 0) {
if (str == tip) {
str = '';
} else {
str = getBlockMarkUp(txt, '*', '*');
}
} else {
str = tip;
}
} else if (btn == 'strike') {
tip = '~~Зачеркнутый текст~~';
if (len > 0) {
if (str == tip) {
str = '';
} else {
str = getBlockMarkUp(txt, '~~', '~~');
}
} else {
str = tip;
}
} else if (btn == 'link') {
var link = prompt('Вставьте гиперссылку', 'http://');
if (len == 0) {
txt = prompt('Название гиперссылки', 'Гиперссылка');
}
str = (link != null && link != '' && link != 'http://') ? '[' + txt + '](' + link + ')' : txt;
} else if (btn == 'image') {
link = prompt('Вставка картинки', 'http://');
str = (link != null && link != '' && link != 'http://') ? '' : txt;
} else if (btn == 'indent') {
var ind = ' ';
if (str.indexOf('\n') < 0) {
str = ind + str
} else {
var list = [];
list = txt.split('\n');
$.each(list, function (k, v) {
list[k] = ind + v
});
str = list.join('\n')
}
} else if (btn == 'unindent') {
var ind = ' ';
if (str.indexOf('\n') < 0 && str.substr(0, 2) == ind) {
str = str.slice(2)
} else {
var list = [];
list = txt.split('\n');
$.each(list, function (k, v) {
list[k] = v;
if (v.substr(0, 2) == ind) {
list[k] = v.slice(2)
}
});
str = list.join('\n')
}
} else if (btn == 'list-bulleted') {
str = getBlockMarkUp(txt, "- ", "");
} else if (btn == 'list-numbered') {
start = prompt('Введите начальное число', 1);
if (start != null && start != '') {
if (!isNumber(start)) {
start = 1
}
if (txt.indexOf('\n') < 0) {
str = getMarkUp(txt, start + '. ', '');
} else {
var list = [],
i = start;
list = txt.split('\n');
$.each(list, function (k, v) {
list[k] = getMarkUp(v, i + '. ', '');
i++
});
str = list.join('\n')
}
}
} else if (btn == 'quote') { // Blockquote
str = getBlockMarkUp(txt, "> ", " ");
} else if (btn == 'code') { // Code Block
str = getMarkUp(txt, "~~~\n", "\n~~~ \n");
}
if (!isEmpty(str)) {
textarea.replaceSelectedText(str, "select")
}
}
function isEmpty(value, trim) {
return value === null || value === undefined || value == []
|| value === '' || trim && $.trim(value) === '';
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function getBlockMarkUp (txt, begin, end) {
var string = txt;
if (string.indexOf('\n') < 0) {
string = getMarkUp(txt, begin, end);
} else {
var list = [];
list = txt.split('\n');
$.each(list, function (k) {
list[k] = getMarkUp(this.replace(new RegExp("[\s]+$"), ""), begin, end + ' ')
});
string = list.join('\n');
}
return string;
}
function getMarkUp(txt, begin, end) {
var m = begin.length,
n = end.length;
var string = txt;
if (m > 0) {
string = (string.slice(0, m) == begin) ? string.slice(m) : begin + string;
}
if (n > 0) {
string = (string.slice(-n) == end) ? string.slice(0, -n) : string + end;
}
return string;
}
return pub;
})(jQuery);
|
JavaScript
| 0.000014 |
@@ -870,16 +870,17 @@
var
+$
form = t
@@ -896,32 +896,80 @@
losest('form');%0A
+ var $preview = $form.find(css.preview);%0A
if (btn.
@@ -1200,38 +1200,24 @@
-form.find(css.
+$
preview
-)
.hide();
@@ -1244,16 +1244,38 @@
a.show()
+;%0A textarea
.focus()
@@ -1637,32 +1637,33 @@
();%0A
+$
form.find('.erro
@@ -1698,37 +1698,47 @@
-form.find(css.
+$
preview
-)
.show()
+;%0A //$preview
.htm
@@ -2031,37 +2031,53 @@
-form.find(css.
+$
preview
-)
.show()
+;%0A $preview
.htm
|
e15aad885b48f60ddae5fda3e443d0c258c5129b
|
fix var-definitions style.
|
slice.js
|
slice.js
|
'use strict';
var reAnsi = require('ansi-regex')
, stringifiable = require('es5-ext/object/validate-stringifiable')
, length = require('./get-stripped-length');
module.exports = function (str, begin, end) {
str = stringifiable(str);
var len = length(str);
if (begin == null) {
begin = 0;
}
if (end == null) {
end = len;
}
if (begin < 0) {
begin = len + begin;
}
if (end < 0) {
end = len + end;
}
var seq = tokenize(str);
seq = sliceSeq(seq, begin, end);
return seq.map(function (chunk) {
if (chunk instanceof Token) {
return chunk.token;
}
return chunk;
}).join('');
};
function tokenize(str) {
var match = reAnsi().exec(str);
if (!match) {
return [ str ];
}
var index = match.index;
var head;
var tail;
if (index === 0) {
head = match[0];
tail = str.slice(head.length);
return [ new Token(head) ].concat(tokenize(tail));
}
var prehead = str.slice(0, index);
head = match[0];
tail = str.slice(index + head.length);
return [ prehead, new Token(head) ].concat(tokenize(tail));
}
function Token(token) {
this.token = token;
}
function sliceSeq(seq, begin, end) {
return seq.reduce(function (state, chunk) {
if (!(chunk instanceof Token)) {
var index = state.index;
var nextChunk = '';
if (isChunkInSlice(chunk, index, begin, end)) {
var relBegin = Math.max(begin - index, 0);
var relEnd = Math.min(end - index, chunk.length);
nextChunk = chunk.slice(relBegin, relEnd);
}
state.seq.push(nextChunk);
state.index = index + chunk.length;
} else {
state.seq.push(chunk);
}
return state;
}, {
index: 0,
seq: []
}).seq;
}
function isChunkInSlice(chunk, index, begin, end) {
var endIndex = chunk.length + index;
if (begin > endIndex) return false;
if (end < index) return false;
return true;
}
|
JavaScript
| 0 |
@@ -220,16 +220,32 @@
end) %7B%0A
+%09var seq, len;%0A%0A
%09str = s
@@ -263,22 +263,17 @@
e(str);%0A
-%0A%09var
+%09
len = le
@@ -442,20 +442,16 @@
d;%0A%09%7D%0A%0A%09
-var
seq = to
@@ -497,17 +497,16 @@
, end);%0A
-%0A
%09return
@@ -750,25 +750,28 @@
ndex
-;
%0A%09
-var head;%0A%09var
+ , head, prehead,
tai
@@ -905,20 +905,16 @@
);%0A%09%7D%0A%0A%09
-var
prehead
@@ -1254,16 +1254,15 @@
ndex
-;
%0A%09%09%09
-var
+ ,
nex
@@ -1375,25 +1375,24 @@
, 0)
-;
%0A%09%09%09%09
-var
+ ,
relEnd
= Ma
@@ -1387,16 +1387,18 @@
relEnd
+
= Math.m
|
30e1639856fe572a96b04c63a8a4a82ce84f891d
|
call first the router component, then user provider if needed
|
smash.js
|
smash.js
|
var glob = require("glob");
var path = require('path');
var responseFactory = require('./core/response.js');
//TODO
//core module can be explicitly replaced by custom module
//add method call verification everywhere
//for the moment, correct chained module is not needed
//TODO
//change everywhere for object
//currently returning that everywhere, and this is not good
//TODO
//add core module that can add headers from endpoint definition
//TODO
//create abstraction for module
function smash() {
var that = this;
const corePath = __dirname + "/core/*.js";
const middlewarePath = __dirname + "/middleware/*.js";
const defaultControllerPath = "/controller/*.js";
var logger = null;
var userProvider = null;
var router = null;
var authorization = null;
var config = null;
//TODO maybe env are not usefull
var envList = ["prod", "dev", "test"]; //useless?????
var env = null; //Not used
var debug = false;
var logEnable = false;
var rootPath = process.cwd();
var controllerPath = defaultControllerPath;
var requestMiddleware = null;
var responseMiddleware = null;
var loadCore = function () {
var files = glob.sync(corePath);
files.forEach(function (file) {
require(path.resolve(file));
});
if (logEnable) {
logger.log(files.length + " files loaded in the core directory.");
}
return that;
};
var loadConfig = function () {
//TODO the problem here is this is not really DRY
//find a solution to apply push config in an array of core module
if (config) {
config.load(rootPath);
if (logger && typeof logger.getConfKeyword === 'function') {
pushConfig(logger, logger.getConfKeyword());
}
if (userProvider && typeof userProvider.getConfKeyword === 'function') {
pushConfig(userProvider, userProvider.getConfKeyword());
}
if (router && typeof router.getConfKeyword === 'function') {
pushConfig(router, router.getConfKeyword());
}
if (authorization && typeof authorization.getConfKeyword === 'function') {
pushConfig(authorization, authorization.getConfKeyword());
}
}
//TODO
//note that request and response are not here,
//maybe they should be in another dir
//or maybe migrate this module in another dir called basic module or something else
return that;
};
var loadDefaultMiddleware = function () {
var files = glob.sync(middlewarePath);
if (logEnable) {
logger.log(files.length + " files loaded in the middleware directory.");
}
files.forEach(function (file) {
require(path.resolve(file));
});
return that;
};
var pushConfig = function (service, keyword) {
service.applyConfig(config.get(keyword));
return that;
};
loadControllers = function () {
var files = glob.sync(rootPath + controllerPath);
if (logEnable) {
logger.log(files.length + " files loaded in the controllers directory.");
}
files.forEach(function (file) {
require(path.resolve(file));
});
return that;
};
var executeController = function (request, response) {
if (logEnable) {
logger.log("Execute controller.");
}
try {
request.route.callback(request, response);
} catch (err) {
response.internalServerError("failed to process request");
if (logEnable) {
logger.log("Error when executing controller.");
}
}
if (responseMiddleware.handleResponse(response) === false) {
if (logEnable) {
logger.log("Middleware has not been able to process the response.");
}
//TODO
//this is useless lol
response.badRequest("bad request");
}
return that;
};
that.registerLogger = function (extLogger) {
logger = extLogger;
if (logger && debug) {
logEnable = true;
}
if (logEnable) {
logger.log("Register logger module.");
}
return that;
};
that.getLogger = function () {
return logger;
};
that.registerUserProvider = function (extUserProvider) {
userProvider = extUserProvider;
if (logEnable) {
logger.log("Register user provider module.");
}
return that;
};
that.getUserProvider = function () {
return userProvider;
};
that.registerRouter = function (extRouter) {
router = extRouter;
if (logEnable) {
logger.log("Register router module.");
}
return that;
};
that.getRouter = function () {
return router;
};
that.registerAuthorization = function (extAuthorization) {
authorization = extAuthorization;
if (logEnable) {
logger.log("Register authorization module.");
}
return that;
};
that.getAuthorization = function () {
return authorization;
};
that.registerConfig = function (extConfig) {
config = extConfig;
if (logEnable) {
logger.log("Register config module.");
}
return that;
};
that.getConfig = function () {
return config;
};
that.registerRequestMiddleware = function (extMiddleware) {
//TODO maybe in the future rename this like entry point
//because there are not really middleware
//Add chained middleware can be a good idea
requestMiddleware = extMiddleware;
if (logEnable) {
logger.log("Register request middleware module.");
}
return that;
};
that.getRequestMiddleware = function () {
return requestMiddleware;
};
that.registerResponseMiddleware = function (extMiddleware) {
//TODO same as request middleware
responseMiddleware = extMiddleware;
if (logEnable) {
logger.log("Register response middleware module.");
}
return that;
};
that.getResponseMiddleware = function () {
return responseMiddleware;
};
that.boot = function (extDebug) {
//
//TODO put it in a another var
//the pruopose is that this var is hust to ask debug activation
//but if no logger is activated, something will be wrong
//
if (extDebug) {
debug = true;
} else {
debug = false;
}
logEnable = false;
//TODO
//is this a good pattern, all module are loaded, then configuration are applied
//there is no configuration apply to middleware
loadCore();
loadConfig();
loadDefaultMiddleware();
loadControllers();
//TODO
//linking here or when handle request??
return that;
};
that.handleRequest = function (request, response) {
if (logEnable) {
logger.log("Handle new request.");
}
requestMiddleware.setNext(userProvider.handleRequest, responseMiddleware.handleResponse);
userProvider.setNext(router.handleRequest, responseMiddleware.handleResponse);
router.setNext(authorization.handleRequest, responseMiddleware.handleResponse);
authorization.setNext(executeController, responseMiddleware.handleResponse);
responseMiddleware.setNext(response);
var response = responseFactory.createResponse();
requestMiddleware.handleRequest(request, response);
return that;
};
that.getEnv = function () {
//for the mmoment env var is not used
return env;
};
that.debugIsActive = function () {
return logEnable;
};
that.setRootPath = function (extRootPath) {
//TODO maybe this is not usefull, for the moment no use case and this is not needed
rootPath = extRootPath;
if (logEnable) {
logger.log("Change root path.");
}
return that;
};
that.resetRootPath = function () {
//TODO this is needed for testing, but this is probably not a best practice
rootPath = process.cwd();
return that;
};
that.getRootPath = function () {
return rootPath;
};
that.setControllerPath = function (extControllerPath) {
//TODO throw an error if .js is not in the string
//OR simply add it at the end
controllerPath = extControllerPath;
if (logEnable) {
logger.log("Change controller path.");
}
return that;
};
that.getControllerPath = function () {
return controllerPath;
};
}
module.exports = new smash();
|
JavaScript
| 0 |
@@ -7300,16 +7300,97 @@
setNext(
+router.handleRequest, responseMiddleware.handleResponse);%0A router.setNext(
userProv
@@ -7478,89 +7478,8 @@
ext(
-router.handleRequest, responseMiddleware.handleResponse);%0A router.setNext(
auth
|
d8e22d2c8032a01607734b51b0b4970e9e8b2242
|
Correct bug with keys
|
snake.js
|
snake.js
|
var Snake = Class.extend({
age : 1,
food : 0,
body : [{x:0, y:9}],
direction : 'r', //'r': right, 'l': lefft, 'u': up, 'd': down
init : function() {
},
move : function() {
var head = {x : this.head().x, y : this.head().y},
newBody = [],
snakeAge = this.age;
if (this.direction==='r') {
head.x++;
} else if (this.direction==='l') {
head.x--;
} else if (this.direction==='d') {
head.y++;
} else if (this.direction==='u') {
head.y--;
}
newBody.push(head);
for(var i=1; i<this.age; i++) {
newBody.push(this.body[i-1]);
}
this.body = newBody;
},
checkColision : function(x,y) {
y = (x instanceof Object)?x.y:y;
x = (x instanceof Object)?x.x:x;
for(var i in this.body) {
if(this.body[i].x == x && this.body[i].y == y) {
return true;
}
}
return false;
},
eat : function() {
this.food++;
if (this.food%this.age === 0) {
this.age++;
this.food = 0;
}
},
head : function() {
return this.body[0];
}
});
var GameScene = Scene.extend({
snake : null,
maxXY : 0,
sizeOfTiles : 25,
food : null,
init : function(id, size, snake, updateTime) {
this._super( id, size, updateTime);
this.snake = snake;
this.maxXY = parseInt(this.size/this.sizeOfTiles)-1;
},
createTile : function(x,y, type) {
var tileSize = this.sizeOfTiles,
left = tileSize * parseInt(x),
top = tileSize * parseInt(y);
return '<div class="tile '+type+'" style="left:'+left+'px; top:'+top+'px;'
+' width:'+tileSize+'px; height:'+tileSize+'px;"></div>';
},
draw : function() {
var scene = '',
i,tile;
for(i in this.snake.body) {
tile = this.snake.body[i];
scene += this.createTile(tile.x, tile.y, 'snake');
}
scene += this.createTile(this.food.x, this.food.y, 'food');
this.container.innerHTML = scene;
}
});
var GameState = State.extend({
snake : null,
food : null,
init : function() {
this._super(200);
this.snake = new Snake();
this.scene = new GameScene('snakeGame', 500, this.snake, 200);
},
keyEvents : function(e, state) {
e = e || window.event;
if (e.keyCode == '38') { // up arrow
state.snake.direction = 'u';
}
else if (e.keyCode == '40') { // down arrow
state.snake.direction = 'd';
}
else if (e.keyCode == '37') { // left arrow
state.snake.direction = 'l';
}
else if (e.keyCode == '39') { // right arrow
state.snake.direction = 'r';
}
else if (e.keyCode == 0 || e.keyCode == 32) {
state.stop();
}
},
update : function() {
this.snake.move();
if (this.snake.checkColision(this.food)) {
this.snake.eat();
this.food = null;
}
if (this.food==null) {
this.scene.food = this.addFood();
}
if (this.snake.head().x===this.scene.maxXY+1 && this.snake.direction=='r') this.snake.head().x=0;
if (this.snake.head().x===-1 && this.snake.direction=='l') this.snake.head().x=this.scene.maxXY;
if (this.snake.head().y===this.scene.maxXY+1 && this.snake.direction=='d') this.snake.head().y=0;
if (this.snake.head().y===-1 && this.snake.direction=='u') this.snake.head().y=this.scene.maxXY;
},
addFood : function() {
var x = 0,
y = 0,
colision = true;
while(colision) {
x = Math.floor(Math.random() * (this.scene.maxXY));
y = Math.floor(Math.random() * (this.scene.maxXY));
colision = this.snake.checkColision(x,y);
}
this.food = { 'x' : x, 'y' : y };
return this.food;
}
});
|
JavaScript
| 0.000004 |
@@ -2260,24 +2260,90 @@
// up arrow%0A
+ if (state.snake.age==1 %7C%7C state.snake.direction != 'd') %7B%0A
state.
@@ -2365,16 +2365,24 @@
= 'u';%0A
+ %7D%0A
%7D%0A
@@ -2423,24 +2423,90 @@
down arrow%0A
+ if (state.snake.age==1 %7C%7C state.snake.direction != 'u') %7B%0A
state.
@@ -2528,16 +2528,24 @@
= 'd';%0A
+ %7D%0A
%7D%0A
@@ -2582,32 +2582,98 @@
%7B // left arrow%0A
+ if (state.snake.age==1 %7C%7C state.snake.direction != 'r') %7B%0A
state.snak
@@ -2691,16 +2691,24 @@
= 'l';%0A
+ %7D%0A
%7D%0A
@@ -2750,24 +2750,90 @@
right arrow%0A
+ if (state.snake.age==1 %7C%7C state.snake.direction != 'l') %7B%0A
state.
@@ -2855,16 +2855,24 @@
= 'r';%0A
+ %7D%0A
%7D%0A
|
58da0ba11e605191d1231c0774a90e4c519460f2
|
Allow spark.js to work either as a node module or as a browser function.
|
spark.js
|
spark.js
|
/*
* ASCII sparklines.
*/
var ticks = ['▁', '▂', '▃', '▅', '▆', '▇'];
function spark(ints) {
var max = Math.max.apply(null, ints),
min = Math.min.apply(null, ints);
var steps = ints.map(function (tick) {
var index = Math.round((tick - min) / max * (ticks.length -1));
return ticks[index];
});
return steps.join("");
}
module.exports = spark;
|
JavaScript
| 0 |
@@ -22,16 +22,38 @@
s.%0A */%0A%0A
+(function(root) %7B%0A
var tick
@@ -89,16 +89,29 @@
'%E2%96%87'%5D;%0A%0A
+%09var spark =
function
@@ -111,21 +111,16 @@
unction
-spark
(ints) %7B
@@ -120,24 +120,25 @@
ints) %7B%0A
+%09
var max = Ma
@@ -163,24 +163,19 @@
ints),%0A
-
+%09%09%09
min = Ma
@@ -201,20 +201,18 @@
ints);%0A%0A
-
+%09%09
var step
@@ -246,20 +246,18 @@
) %7B%0A
-
+%09%09
var inde
@@ -316,20 +316,18 @@
));%0A
-
+%09%09
return t
@@ -343,21 +343,17 @@
x%5D;%0A
-
+%09%09
%7D);%0A%0A
-
+%09%09
retu
@@ -375,32 +375,216 @@
%22);%0A
-%0A%7D%0A%0Amodule.exports = spark;
+%09%7D%0A%0A%09if(typeof exports !== 'undefined') %7B%0A%09%09if (typeof module !== 'undefined' && module.exports) %7B%0A%09%09%09module.exports = spark;%0A%09%09%7D%0A%09%09exports.spark = spark;%0A%09%7D else %7B%0A%09%09root.spark = spark;%0A%09%7D%0A%0A%7D)(this %7C%7C window);
%0A
|
5e08b0d2f4e08bafd1d2f5aac37ef83a7da7d621
|
Fix getQueryParams tests
|
test/helpers/getPetitionsQueryParams.js
|
test/helpers/getPetitionsQueryParams.js
|
import chai from 'chai';
import getPetitionsQueryParams from 'helpers/getPetitionsQueryParams';
const { assert } = chai;
describe('getPetitionsQueryString', () => {
it('returns correct `page` from params', () => {
const result = getPetitionsQueryParams({
page: 2
});
const actual = result.page;
const expected = 2;
assert.equal(actual, expected);
});
it('returns correct `page` from query string', () => {
const result = getPetitionsQueryParams({}, {
page: 2
});
const actual = result.page;
const expected = 2;
assert.equal(actual, expected);
});
it('accepts `page` from params over query string', () => {
const result = getPetitionsQueryParams({
page: 1
}, {
page: 2
});
const actual = result.page;
const expected = 1;
assert.equal(actual, expected);
});
it('parses integers for `page` params', () => {
const result = getPetitionsQueryParams({}, {
page: '2'
});
const actual = result.page;
const expected = 2;
assert.equal(actual, expected);
});
it('returns correct `city` from params', () => {
const result = getPetitionsQueryParams({
city: 'nwch:5'
});
const actual = result.city;
const expected = 'nwch:5';
assert.equal(actual, expected);
});
it('returns correct `cityName` from params', () => {
const result = getPetitionsQueryParams({
cityName: 'aargau'
});
const actual = result.cityName;
const expected = 'aargau';
assert.equal(actual, expected);
});
it('returns correct `limit` from query string', () => {
const result = getPetitionsQueryParams({}, {
limit: 50
});
const actual = result.limit;
const expected = 50;
assert.equal(actual, expected);
});
it('parses integers for `limit` query string', () => {
const result = getPetitionsQueryParams({}, {
limit: '50'
});
const actual = result.limit;
const expected = 50;
assert.equal(actual, expected);
});
it('does not return `city` from query string', () => {
const result = getPetitionsQueryParams({}, {
city: 'nwch:5'
});
const actual = result.city;
const expected = '';
assert.equal(actual, expected);
});
it('does not return `cityName` from query string', () => {
const result = getPetitionsQueryParams({}, {
cityName: 'aargau'
});
const actual = result.cityName;
const expected = '';
assert.equal(actual, expected);
});
it('does not return `limit` from params', () => {
const result = getPetitionsQueryParams({
limit: 50
}, {
limit: 100
});
const actual = result.limit;
const expected = 100;
assert.equal(actual, expected);
});
it('returns correct `page` when no arguements', () => {
const result = getPetitionsQueryParams();
const actual = result.hasOwnProperty('page');
assert.isTrue(actual);
});
it('returns correct `city` when no arguements', () => {
const result = getPetitionsQueryParams();
const actual = result.hasOwnProperty('city');
assert.isTrue(actual);
});
it('returns correct `cityName` when no arguements', () => {
const result = getPetitionsQueryParams();
const actual = result.hasOwnProperty('cityName');
assert.isTrue(actual);
});
it('returns correct `limit` when no arguements', () => {
const result = getPetitionsQueryParams();
const actual = result.hasOwnProperty('limit');
assert.isTrue(actual);
});
it('returns fallback `page`', () => {
const result = getPetitionsQueryParams();
const actual = result.page;
const expected = 1;
assert.equal(actual, expected);
});
it('returns fallback `limit`', () => {
const result = getPetitionsQueryParams();
const actual = result.limit;
const expected = 12;
assert.equal(actual, expected);
});
});
|
JavaScript
| 0.000001 |
@@ -147,14 +147,14 @@
uery
-String
+Params
', (
@@ -380,39 +380,31 @@
%7D);%0A%0A it('
-returns correct
+ignores
%60page%60 from
@@ -402,38 +402,38 @@
age%60 from query
-string
+params
', () =%3E %7B%0A c
@@ -534,259 +534,8 @@
ge;%0A
- const expected = 2;%0A%0A assert.equal(actual, expected);%0A %7D);%0A%0A it('accepts %60page%60 from params over query string', () =%3E %7B%0A const result = getPetitionsQueryParams(%7B%0A page: 1%0A %7D, %7B%0A page: 2%0A %7D);%0A const actual = result.page;%0A
@@ -684,36 +684,32 @@
onsQueryParams(%7B
-%7D, %7B
%0A page: '2'
@@ -709,20 +709,24 @@
ge: '2'%0A
-
+%7D, %7B
%7D);%0A
|
ab38ad529ed78c88b5a7ace4767c5714529df019
|
use imports
|
test/lib/data_profiles_splitter.test.js
|
test/lib/data_profiles_splitter.test.js
|
describe('DataProfilesSplitter', () => {
const dps = new DataProfilesSplitter();
describe('#profilesFromDataSet', () => {
it('returns all profiles from profiles, profiles_1, profiles_2, profiles_3, profiles_4', () => {
const profiles = dps.profilesFromDataSet({
profiles: [{ profile: 'p0' }],
profiles_1: [{ profile: 'p1' }],
profiles_2: [{ profile: 'p2' }],
profiles_3: [{ profile: 'p3' }],
profiles_4: [{ profile: 'p4' }]
})
expect(profiles.length).to.eq(5);
for (let i = 0; i < 5; i++) expect(profiles[i].profile).to.eq(`p${i}`);
})
it('returns all profiles from profiles, profiles_1, profiles_2, profiles_3, profiles_4 except profiles_5', () => {
const profiles = dps.profilesFromDataSet({
profiles: [{ profile: 'p0' }],
profiles_1: [{ profile: 'p1' }],
profiles_2: [{ profile: 'p2' }],
profiles_3: [{ profile: 'p3' }],
profiles_4: [{ profile: 'p4' }],
profiles_5: [{ profile: 'p5' }],
})
expect(profiles.length).to.eq(5);
for (let i = 0; i < 5; i++) expect(profiles[i].profile).to.eq(`p${i}`);
})
it('returns all profiles from profiles, profiles_1, profiles_2, profiles_3', () => {
const profiles = dps.profilesFromDataSet({
profiles: [{ profile: 'p0' }, { profile: 'p1' }],
profiles_1: [{ profile: 'p2' }],
profiles_2: [{ profile: 'p3' }],
profiles_3: [{ profile: 'p4' }]
})
expect(profiles.length).to.eq(5);
for (let i = 0; i < 5; i++) expect(profiles[i].profile).to.eq(`p${i}`);
})
it('returns all profiles from only profiles', () => {
const profiles = dps.profilesFromDataSet({
profiles: [{ profile: 'p0' }, { profile: 'p1' }, { profile: 'p2' }]
})
expect(profiles.length).to.eq(3);
for (let i = 0; i < 3; i++) expect(profiles[i].profile).to.eq(`p${i}`);
})
})
describe('#profilesToDataSet', () => {
it('returns dataSet thas has 1 profiles field from 40 profiles', () => {
const profiles = [];
for (let i = 0; i < 40; i++) profiles.push({ profile: `p${i}` });
const dataSet = dps.profilesToDataSet(profiles);
expect(dataSet.profiles[0].profile).to.eq('p0');
expect(dataSet.profiles[39].profile).to.eq('p39');
expect(dataSet.profiles.length).to.eq(40);
expect(dataSet.profiles_1).to.be.empty;
expect(dataSet.profiles_2).to.be.empty;
expect(dataSet.profiles_3).to.be.empty;
expect(dataSet.profiles_4).to.be.empty;
})
it('returns dataSet thas has 2 profiles fields from 41 profiles', () => {
const profiles = [];
for (let i = 0; i < 41; i++) profiles.push({ profile: `p${i}` });
const dataSet = dps.profilesToDataSet(profiles);
expect(dataSet.profiles[0].profile).to.eq('p0');
expect(dataSet.profiles[39].profile).to.eq('p39');
expect(dataSet.profiles.length).to.eq(40);
expect(dataSet.profiles_1[0].profile).to.eq('p40');
expect(dataSet.profiles_1.length).to.eq(1);
expect(dataSet.profiles_2).to.be.empty;
expect(dataSet.profiles_3).to.be.empty;
expect(dataSet.profiles_4).to.be.empty;
})
it('returns dataSet thas has 5 profiles fields from 200 profiles', () => {
const profiles = [];
for (let i = 0; i < 200; i++) profiles.push({ profile: `p${i}` });
const dataSet = dps.profilesToDataSet(profiles);
expect(dataSet.profiles[0].profile).to.eq('p0');
expect(dataSet.profiles[39].profile).to.eq('p39');
expect(dataSet.profiles.length).to.eq(40);
expect(dataSet.profiles_1[0].profile).to.eq('p40');
expect(dataSet.profiles_1.length).to.eq(40);
expect(dataSet.profiles_2.length).to.eq(40);
expect(dataSet.profiles_3.length).to.eq(40);
expect(dataSet.profiles_4[0].profile).to.eq('p160');
expect(dataSet.profiles_4[39].profile).to.eq('p199');
expect(dataSet.profiles_4.length).to.eq(40);
expect(dataSet.profiles_5).to.be.undefined;
})
it('returns dataSet thas has 5 profiles fields from 201 profiles', () => {
const profiles = [];
for (let i = 0; i < 201; i++) profiles.push({ profile: `p${i}` });
const dataSet = dps.profilesToDataSet(profiles);
expect(dataSet.profiles.length).to.eq(40);
expect(dataSet.profiles_1.length).to.eq(40);
expect(dataSet.profiles_2.length).to.eq(40);
expect(dataSet.profiles_3.length).to.eq(40);
expect(dataSet.profiles_4.length).to.eq(40);
expect(dataSet.profiles_5).to.be.undefined;
})
})
})
|
JavaScript
| 0.000001 |
@@ -1,16 +1,126 @@
+import %7B expect %7D from 'chai'%0Aimport %7B DataProfilesSplitter %7D from '../../src/lib/data_profiles_splitter.js'%0A%0A
describe('DataPr
|
4a8b294c924aae193ed3570c9e76d4d013833a8b
|
Update colors test with new colors
|
test/spec/colors/colors-service.spec.js
|
test/spec/colors/colors-service.spec.js
|
describe('Factory: mos.colors.ColorService', function () {
'use strict';
// load the module
beforeEach(module('mos'));
var $injector = angular.injector(['mos']);
var Colors;
var CartoConfig;
var MosColors;
var MosCssValues;
// Initialize the service
beforeEach(inject(function (_ColorService_) {
MosColors = $injector.get('MOSColors');
MosCssValues = $injector.get('MOSCSSValues');
CartoConfig = $injector.get('CartoConfig');
Colors = _ColorService_;
}));
it('should have base CartoCSS', function () {
expect(Colors.baseCartoCSS).toBeDefined();
});
it('should get legend', function () {
var floorLegend = Colors.getLegend('floor_area');
expect(floorLegend).toBeDefined();
});
it('should build CartoCSS for sector', function () {
var sectorCSS = Colors.getFieldCartoCSS('sector');
var cssVal = '#mos_beb_2013[sector="School (K-12)"] {marker-fill: #A6CEE3;} #mos_beb_2013[sector="Office"] {marker-fill: #1F78B4;} #mos_beb_2013[sector="Medical Office"] {marker-fill: #52A634;} #mos_beb_2013[sector="Warehouse"] {marker-fill: #B2DF8A;} #mos_beb_2013[sector="College/ University"] {marker-fill: #33A02C;} #mos_beb_2013[sector="Other"] {marker-fill: #FB9A99;} #mos_beb_2013[sector="Retail"] {marker-fill: #E31A1C;} #mos_beb_2013[sector="Municipal"] {marker-fill: #FDBF6F;} #mos_beb_2013[sector="Multifamily"] {marker-fill: #FF7F00;} #mos_beb_2013[sector="Hotel"] {marker-fill: #CAB2D6;} #mos_beb_2013[sector="Industrial"] {marker-fill: #6A3D9A;} #mos_beb_2013[sector="Worship"] {marker-fill: #9C90C4;} #mos_beb_2013[sector="Supermarket"] {marker-fill: #E8AE6C;} #mos_beb_2013[sector="Parking"] {marker-fill: #C9DBE6;} #mos_beb_2013[sector="Laboratory"] {marker-fill: #3AA3FF;} #mos_beb_2013[sector="Hospital"] {marker-fill: #C6B4FF;} #mos_beb_2013[sector="Data Center"] {marker-fill: #B8FFA8;} \n#mos_beb_2013 {marker-fill: #DDDDDD;}';
expect(sectorCSS).toBeDefined();
expect(sectorCSS).toBe(cssVal);
});
it('should build CartoCSS for total_ghg', function () {
var ghgCSS = Colors.getFieldCartoCSS('total_ghg');
var cssVal = '#mos_beb_2013 [total_ghg <= 258330] {marker-width: 25.0;}\n#mos_beb_2013 [total_ghg <= 5311.3] {marker-width: 23.3;}\n#mos_beb_2013 [total_ghg <= 2593.9] {marker-width: 21.7;}\n#mos_beb_2013 [total_ghg <= 1671] {marker-width: 20.0;}\n#mos_beb_2013 [total_ghg <= 1129.4] {marker-width: 18.3;}\n#mos_beb_2013 [total_ghg <= 825.7] {marker-width: 16.7;}\n#mos_beb_2013 [total_ghg <= 598.2] {marker-width: 15.0;}\n#mos_beb_2013 [total_ghg <= 429.6] {marker-width: 13.3;}\n#mos_beb_2013 [total_ghg <= 316.5] {marker-width: 11.7;}\n#mos_beb_2013 [total_ghg <= 126.5] {marker-width: 10.0;}\n#mos_beb_2013 [total_ghg = null] {marker-width: 0;}\n#mos_beb_2013 [total_ghg = 0] {marker-width: 0;}\n';
expect(ghgCSS).toBeDefined();
expect(ghgCSS).toBe(cssVal);
});
});
|
JavaScript
| 0 |
@@ -1744,14 +1744,14 @@
l: #
-C9DBE6
+62afe8
;%7D #
@@ -1920,14 +1920,14 @@
l: #
-B8FFA8
+a3d895
;%7D %5C
|
4365fde2c6cde8b741064d1f125bcf5877ea5bab
|
fix tests for query string util
|
test/unit/utils/QueryStringUtilsSpec.js
|
test/unit/utils/QueryStringUtilsSpec.js
|
let sinon from 'sinon/pkg/sinon.js');
var QueryStringUtils from '../../../lib/js/app/utils/QueryStringUtils');
describe('utils/QueryStringUtils', () => {
describe('getQueryAttributes', () => {
it('should properly parse funnel step filters', () => {
sinon.stub(QueryStringUtils, 'getSearchString').returns('query[steps][0][filters][0][property_value][0]=testing');
assert.sameMembers(QueryStringUtils.getQueryAttributes().query.steps[0].filters[0].property_value, ['testing']);
QueryStringUtils.getSearchString.restore();
});
});
});
|
JavaScript
| 0.000011 |
@@ -1,46 +1,10 @@
-%0Alet sinon from 'sinon/pkg/sinon.js');%0Avar
+import
Que
@@ -66,17 +66,16 @@
ngUtils'
-)
;%0A%0Adescr
@@ -112,18 +112,16 @@
() =%3E %7B%0A
-
%0A descr
@@ -154,20 +154,16 @@
() =%3E %7B%0A
-
%0A it(
@@ -225,18 +225,30 @@
-sin
+c
on
-.
st
-ub
+ spy = jest.spyOn
(Que
@@ -285,15 +285,23 @@
g').
-returns
+mockReturnValue
('qu
@@ -366,26 +366,14 @@
-assert.sameMembers
+expect
(Que
@@ -447,18 +447,26 @@
ty_value
-,
+).toEqual(
%5B'testin
@@ -481,42 +481,17 @@
-QueryStringUtils.getSearchString.r
+spy.mockR
esto
|
13eb5cba7be331ee2e7d7622373bb81f943d139a
|
add test for sending messages
|
tests/mocha/client/channels-test.es6.js
|
tests/mocha/client/channels-test.es6.js
|
"use strict";
if (typeof MochaWeb !== 'undefined') {
MochaWeb.testOnly(() => {
describe('channels', () => {
it('can create channels', () => {
return MTT.clickOn('+ New Channel')
.then(() => MTT.fillIn('It types something here', 'foo'))
.then(() => MTT.clickOn('Create'))
.then(() => {
var newChannel = $(".side-bar-container a:contains('foo')");
chai.expect(newChannel.length).to.be.eq(1);
});
});
it.skip('shows Nothing to See Here by default', () => {
var defaultText = $("h3:contains('Nothing to See Here')");
chai.expect(defaultText.length).to.eql(1);
})
});
});
}
|
JavaScript
| 0 |
@@ -71,24 +71,204 @@
nly(() =%3E %7B%0A
+ beforeEach(done =%3E %7B%0A Messages.insert(%7B%0A userName: 'blahbot',%0A channelName: 'general',%0A body: 'Welcome to #general!'%0A %7D);%0A done();%0A %7D);%0A%0A
describe
@@ -384,30 +384,24 @@
.then(
-() =%3E
MTT.fillIn('
@@ -450,22 +450,16 @@
.then(
-() =%3E
MTT.clic
@@ -663,13 +663,396 @@
it
-.skip
+('can add new messages', () =%3E %7B%0A return MTT.fillIn('Say Something!', 'pringles')%0A .then(MTT.clickOn('Send'))%0A .then(() =%3E %7B%0A var newMessage = Messages.findOne(%7B%0A channelName: 'general',%0A body: 'Welcome to #general!'%0A %7D);%0A%0A chai.expect(newMessage).to.not.eql(undefined);%0A %7D);%0A %7D);%0A%0A it
('sh
|
35b5c6b7bfca2567a3068af005a7ae1ba3b24039
|
add margins to label and chapter-section
|
tutor/src/components/book-part-title.js
|
tutor/src/components/book-part-title.js
|
import { React, PropTypes, cn, styled, css } from 'vendor';
import ChapterSection from './chapter-section';
const hideChapterSectionCSS = css`
.os-number {
display: none;
}
`;
const StyledBookPartTitle = styled.div`
display: inline-block;
${({ hideChapterSection }) => hideChapterSection && hideChapterSectionCSS}
.os-number {
.os-part-text {
font-weight: normal;
}
font-weight: ${({ boldChapterSection }) => boldChapterSection ? 'bold' : 'normal'};
}
.chapter-section {
font-weight: ${({ boldChapterSection }) => boldChapterSection ? 'bold' : 'normal'};
margin-left: 0.5rem;
}
`;
const hasChapterSection = /os-number/;
const BookPartTitle = ({ part, label, className, boldChapterSection, displayChapterSection }) => {
return (
<StyledBookPartTitle
boldChapterSection={boldChapterSection}
hideChapterSection={!displayChapterSection}
className={cn('book-part-title', className)}
>
{label && !part.title.includes(label) && (
<span className="label">{label}</span>
)}
{displayChapterSection && !part.title.match(hasChapterSection) && (
<ChapterSection chapterSection={part.chapter_section} />
)}
<span dangerouslySetInnerHTML={{ __html: part.title }} />
</StyledBookPartTitle>
);
};
BookPartTitle.propTypes = {
part: PropTypes.shape({
title: PropTypes.string.isRequired,
chapter_section: PropTypes.object,
}).isRequired,
label: PropTypes.node,
className: PropTypes.string,
boldChapterSection: PropTypes.bool,
displayChapterSection: PropTypes.bool,
};
export default BookPartTitle;
|
JavaScript
| 0 |
@@ -606,11 +606,53 @@
gin-
-lef
+right: 0.5rem;%0A %7D%0A .label %7B%0A margin-righ
t: 0
|
f27872b85a54e8e8477048567bb037482f8ce00b
|
replace a close icon for history
|
preview/js/saveSelectedAreas.js
|
preview/js/saveSelectedAreas.js
|
'use strict';
var areas = [];
var areaBounds = [];
var screenBounds = [];
var areaUrls = [];
var addresses = [];
var savedAreasWindowInner = document.getElementById('saved-areas-window-inner');
var savedAreasWindow = document.getElementById('saved-areas-window');
var ua = navigator.userAgent;
savedAreasWindowInner.onclick = function (e) {
if (e.srcElement.nodeName === 'IMG') {
var targetId = Number(e.srcElement.id.split('-')[2]);
var boundsBase = areaBounds[targetId];
var screenBoundsBase = screenBounds[targetId];
var sw = new mapboxgl.LngLat(boundsBase[0], boundsBase[1]);
var ne = new mapboxgl.LngLat(boundsBase[2], boundsBase[3]);
var bounds = new mapboxgl.LngLatBounds(sw, ne);
var screenSw = new mapboxgl.LngLat(screenBoundsBase[0], screenBoundsBase[1]);
var screenNe = new mapboxgl.LngLat(screenBoundsBase[2], screenBoundsBase[3]);
var sBounds = new mapboxgl.LngLatBounds(screenSw, screenNe);
updateTableImage(bounds);
if (gotStreets === false) {
gotStreets = true;
} else {
map.removeLayer(streetsLayerProps.id);
map.removeSource(streetsLayerProps.id);
}
getStreetsPNGInBounds(bounds, true);
$('#export-btn').tooltip('destroy');
setTableView(sBounds);
currentExportBounds = bounds;
currentExportScreenBounds = sBounds;
}
if (e.srcElement.nodeName === 'I') {
var img = e.srcElement.previousSibling;
var targetId = Number(img.id.split('-')[2]);
areas.splice(targetId, 1);
areaUrls.splice(targetId, 1);
areaBounds.splice(targetId, 1);
screenBounds.splice(targetId, 1);
addresses.splice(targetId, 1);
renderSavedAreaToWindow(areas);
}
}
if (ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0 || ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0) {
$('.delete-thumbnail-icon').css('display', 'inline');
}
map.on('load', function () {
savedAreasWindow.classList.add('visible');
});
map.on('move', function () {
savedAreasWindow.classList.remove('visible');
});
map.on('moveend', function () {
savedAreasWindow.classList.add('visible');
});
function createThumbnail(url) {
var thumbnail = document.createElement('div');
thumbnail.classList.add('savedarea-thumbnail');
var img = document.createElement("img");
img.src = url;
img.setAttribute('data-toggle', 'tooltip');
img.setAttribute('data-placement', 'bottom');
var deleteIcon = document.createElement('i');
deleteIcon.classList.add('fa');
deleteIcon.classList.add('fa-minus-circle');
deleteIcon.classList.add('delete-thumbnail-icon');
deleteIcon.ariaHidden = true;
thumbnail.appendChild(img);
thumbnail.appendChild(deleteIcon);
return thumbnail;
}
function getAreasInLocalStorage() {
areaUrls = JSON.parse(localStorage.getItem('mable-preview-areas')).areaUrls || [];
areaBounds = JSON.parse(localStorage.getItem('mable-preview-areas')).areaBounds || [];
screenBounds = JSON.parse(localStorage.getItem('mable-preview-areas')).screenBounds || [];
addresses = JSON.parse(localStorage.getItem('mable-preview-areas')).addresses || [];
areaUrls.forEach(function (url, i) {
areas.push(createThumbnail(url));
});
renderSavedAreaToWindow(areas);
}
function addSavedAreaToWindow(url, bounds) {
var elem = createThumbnail(url);
areas.push(elem);
areaUrls.push(url);
areaBounds.push([bounds._sw.lng, bounds._sw.lat, bounds._ne.lng, bounds._ne.lat]);
screenBounds.push([currentExportScreenBounds._sw.lng, currentExportScreenBounds._sw.lat, currentExportScreenBounds._ne.lng, currentExportScreenBounds._ne.lat]);
if (areas.length > 6) {
areas.shift();
areaUrls.shift();
areaBounds.shift();
screenBounds.shift();
}
//renderSavedAreaToWindow(areas);
var center = map.getCenter();
reverseGeocoding(center.lng, center.lat, elem);
}
function renderSavedAreaToWindow(domArray) {
savedAreasWindowInner.textContent = null;
domArray.forEach(function (thumbnail, i) {
thumbnail.childNodes.forEach(function (node) {
if (node.nodeName === 'IMG') {
node.id = 'saved-area-' + i;
console.log($('#' + node.id));
$('#' + node.id).tooltip({ title: addresses[i], container: 'body' });
}
});
savedAreasWindowInner.appendChild(thumbnail);
});
domArray.forEach(function (thumbnail, i) {
$('#' + 'saved-area-' + i).tooltip({ title: addresses[i], container: 'body' });
});
localStorage.setItem('mable-preview-areas', JSON.stringify({ 'areaUrls': areaUrls, 'areaBounds': areaBounds, 'screenBounds': screenBounds, 'addresses': addresses }));
}
function reverseGeocoding(lng, lat, elem) {
var requestUrl = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + lng + '%2C' + lat + '.json?access_token=' + mapboxgl.accessToken;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
switch ( xhr.readyState ) {
case 0:
console.log('uninitialized!');
break;
case 1:
console.log('loading...');
break;
case 2:
console.log('loaded.');
break;
case 3:
console.log('interactive... '+xhr.responseText.length+' bytes.');
break;
case 4:
if( xhr.status == 200 || xhr.status == 304 ) {
var data = JSON.parse(xhr.responseText);
console.log('COMPLETE!');
//addresses.push(data.features[0].text);
addresses.push(data.features[0].place_name);
if (areas.length > 6) {
addresses.shift();
}
renderSavedAreaToWindow(areas);
} else {
console.log('Failed. HttpStatus: ' + xhr.statusText);
}
break;
}
};
xhr.open('GET', requestUrl, false);
xhr.send();
}
getAreasInLocalStorage();
|
JavaScript
| 0 |
@@ -2549,19 +2549,12 @@
'fa-
-minus-cir
cl
+os
e');
|
2942e03e716f46013e4d8963b773752cb515fb8f
|
Use "cover" for rows per page selection menu
|
ui/src/components/table/table-bottom.js
|
ui/src/components/table/table-bottom.js
|
import QSelect from '../select/QSelect.js'
import QBtn from '../btn/QBtn.js'
import QIcon from '../icon/QIcon.js'
export default {
computed: {
navIcon () {
const ico = [ this.$q.iconSet.table.prevPage, this.$q.iconSet.table.nextPage ]
return this.$q.lang.rtl === true ? ico.reverse() : ico
}
},
methods: {
getBottom (h) {
if (this.hideBottom === true) {
return
}
if (this.nothingToDisplay === true) {
const message = this.filter
? this.noResultsLabel || this.$q.lang.table.noResults
: (this.loading === true ? this.loadingLabel || this.$q.lang.table.loading : this.noDataLabel || this.$q.lang.table.noData)
const noData = this.$scopedSlots['no-data']
const children = noData !== void 0
? [ noData({ message, icon: this.$q.iconSet.table.warning, filter: this.filter }) ]
: [
h(QIcon, {
staticClass: 'q-table__bottom-nodata-icon',
props: { name: this.$q.iconSet.table.warning }
}),
message
]
return h('div', {
staticClass: 'q-table__bottom row items-center q-table__bottom--nodata'
}, children)
}
const bottom = this.$scopedSlots.bottom
return h('div', {
staticClass: 'q-table__bottom row items-center',
class: bottom !== void 0 ? null : 'justify-end'
}, bottom !== void 0 ? [ bottom(this.marginalsProps) ] : this.getPaginationRow(h))
},
getPaginationRow (h) {
let control
const
{ rowsPerPage } = this.computedPagination,
paginationLabel = this.paginationLabel || this.$q.lang.table.pagination,
paginationSlot = this.$scopedSlots.pagination,
hasOpts = this.rowsPerPageOptions.length > 1
const child = [
h('div', { staticClass: 'q-table__control' }, [
h('div', [
this.hasSelectionMode === true && this.rowsSelectedNumber > 0
? (this.selectedRowsLabel || this.$q.lang.table.selectedRecords)(this.rowsSelectedNumber)
: ''
])
]),
h('div', { staticClass: 'q-table__separator col' })
]
if (hasOpts === true) {
child.push(
h('div', { staticClass: 'q-table__control' }, [
h('span', { staticClass: 'q-table__bottom-item' }, [
this.rowsPerPageLabel || this.$q.lang.table.recordsPerPage
]),
h(QSelect, {
staticClass: 'inline q-table__bottom-item',
props: {
color: this.color,
value: rowsPerPage,
options: this.computedRowsPerPageOptions,
displayValue: rowsPerPage === 0
? this.$q.lang.table.allRows
: rowsPerPage,
dark: this.isDark,
borderless: true,
dense: true,
optionsDense: true
},
on: {
input: pag => {
this.setPagination({
page: 1,
rowsPerPage: pag.value
})
}
}
})
])
)
}
if (paginationSlot !== void 0) {
control = paginationSlot(this.marginalsProps)
}
else {
control = [
h('span', rowsPerPage !== 0 ? { staticClass: 'q-table__bottom-item' } : {}, [
rowsPerPage
? paginationLabel(this.firstRowIndex + 1, Math.min(this.lastRowIndex, this.computedRowsNumber), this.computedRowsNumber)
: paginationLabel(1, this.computedRowsNumber, this.computedRowsNumber)
])
]
if (rowsPerPage !== 0) {
control.push(
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.navIcon[0],
dense: true,
flat: true,
disable: this.isFirstPage
},
on: { click: this.prevPage }
}),
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.navIcon[1],
dense: true,
flat: true,
disable: this.isLastPage
},
on: { click: this.nextPage }
})
)
}
}
child.push(
h('div', { staticClass: 'q-table__control' }, control)
)
return child
}
}
}
|
JavaScript
| 0 |
@@ -2938,24 +2938,60 @@
ptionsDense:
+ true,%0A optionsCover:
true%0A
|
9f796efbda10158456108fa3fbfc583cadd2bac7
|
remove logs
|
lib/subscribe.js
|
lib/subscribe.js
|
'use strict'
const INIT = 'new'
const UPDATE = 'update'
const REMOVE = 'remove'
const merge = require('lodash.merge')
module.exports = function (target, subscription, update, tree) {
if (!tree) { tree = {} }
target.on('subscription', function (data, event) {
handleUpdate(target, subscription, update, tree, event, tree)
})
target._subscriptions = true
handleUpdate(target, subscription, update, tree, void 0, tree)
return tree
}
function handleUpdate (target, subscription, update, tree, event, roottree) {
for (let key in subscription) {
handleItem(key, target, subscription, subscription[key], update, tree, event, roottree)
}
}
function handleItem (key, target, subscription, subs, update, tree, event, roottree) {
if (key !== 'val') {
if (key === '~') {
root(subs, target, subscription, update, tree, event, roottree)
} else if (key === '*') {
collection(subs, target, subscription, update, tree, event, roottree)
} else if (subs === true) {
leaf(key, target, subscription, update, tree, event)
} else {
console.log('STRUCT!', key)
struct(subs, key, target, subscription, update, tree, event, roottree)
}
// can use the same for remove (cleanup)
}
}
function leaf (key, target, subscription, update, tree, event) {
var keyTarget = target[key]
var treeKey = tree[key]
if (keyTarget && keyTarget.__input !== null) {
let stamp = generateStamp(keyTarget, treeKey)
console.log('leaf', stamp)
if (!tree[key]) {
tree[key] = stamp
update.call(keyTarget, INIT, event, subscription)
} else if (treeKey !== stamp) {
tree[key] = stamp
update.call(keyTarget, UPDATE, event, subscription)
}
} else if (treeKey) {
update.call(keyTarget, REMOVE, event, subscription)
delete tree[key]
}
}
function struct (subs, key, target, subscription, update, tree, event, roottree) {
var keyTarget = target[key]
var treeKey = tree[key]
if (keyTarget && keyTarget.__input !== null) {
let stamp = generateStamp(keyTarget, treeKey, key)
console.log('struct', stamp)
if (!tree[key]) {
tree[key] = { $: stamp }
tree[key].$ = stamp
if (subs.val) {
update.call(keyTarget, INIT, event, subs)
}
handleUpdate(target[key], subs, update, tree[key], event, roottree)
} else if (tree[key].$ !== stamp) {
tree[key].$ = stamp
if (subs.val) {
update.call(keyTarget, UPDATE, event, subs)
}
handleUpdate(target[key], subs, update, tree[key], event, roottree)
}
} else if (treeKey) {
update.call(keyTarget, REMOVE, event, subs)
delete tree[key]
}
}
function collection (subs, target, subscription, update, tree, event, roottree) {
if (target && target.__input !== null) {
let keys = target.keys()
if (keys) {
for (let i = 0, len = keys.length; i < len; i++) {
handleItem(keys[i], target, subs, subs, update, tree, event, roottree)
}
}
} else if (tree) {
update.call(target, REMOVE, event, subs)
}
}
function root (subs, target, subscription, update, tree, event, roottree) {
// lots of reuse with struct of course
if (!tree.$r) {
for (let key in subs) {
if (subs[key] === true) {
subs[key] = { val: true }
}
}
let i = 0
let path = target.syncPath
let len = path.length
let segment = roottree[path[i]]
// let segmentTarget = target[]
while (segment && i < len) {
if (segment.$r) {
merge(segment.$r, subs)
} else {
segment.$r = merge({}, subs)
}
// need tp update stamps for each segment
segment = segment[path[++i]]
}
}
// have to check if it needs to update!
}
function generateStamp (target, tree, key) {
if (tree && tree.$r) {
console.log('stamp it', target, key)
}
return target._lstamp
}
/*
handleUpdate (target, subscription, update, tree, event, roottree) {
for (let key in subscription) {
handleItem(key, target, subscription, subscription[key], update, tree, event, roottree)
}
}
*/
|
JavaScript
| 0.000001 |
@@ -1069,42 +1069,8 @@
e %7B%0A
- console.log('STRUCT!', key)%0A
@@ -1424,39 +1424,8 @@
ey)%0A
- console.log('leaf', stamp)%0A
@@ -2001,42 +2001,8 @@
ey)%0A
- console.log('struct', stamp)%0A%0A
@@ -3715,16 +3715,21 @@
og('
-s
+generateS
tamp
- it
', t
|
afd57d9346079ee027e01d80b4d77a1dd2dba9fc
|
fix handling of changing values
|
lib/sustained.js
|
lib/sustained.js
|
var watch = require('mutant/watch')
var computed = require('mutant/computed')
var Value = require('mutant/value')
module.exports = Sustained
// only broadcast value changes once a truthy value has stayed constant for more than timeThreshold
function Sustained (obs, timeThreshold, checkUpdateImmediately) {
var outputValue = Value(obs())
return computed(outputValue, v => v, {
onListen: () => watch(obs, onChange)
})
function onChange (value) {
if (checkUpdateImmediately && checkUpdateImmediately(value)) { // update immediately for falsy values
clearTimeout()
update()
} else if (value !== outputValue()) {
clearTimeout()
setTimeout(update, timeThreshold)
}
}
function update () {
outputValue.set(obs())
}
}
|
JavaScript
| 0.000001 |
@@ -335,16 +335,39 @@
e(obs())
+%0A var lastValue = null
%0A%0A retu
@@ -649,21 +649,17 @@
!==
-outpu
+las
tValue
-()
) %7B%0A
@@ -719,16 +719,40 @@
eshold)%0A
+ lastValue = value%0A
%7D%0A
@@ -773,24 +773,83 @@
update () %7B%0A
+ var value = obs()%0A if (value !== outputValue()) %7B%0A
outputVa
@@ -856,21 +856,27 @@
lue.set(
-obs())
+value)%0A %7D
%0A %7D%0A%7D%0A
|
3d93e39edbb400a176a4e4b3f83d29e37eb888f5
|
Use swagger-ui's dist path export
|
lib/swaggerUI.js
|
lib/swaggerUI.js
|
"use strict";
var P = require('bluebird');
var fs = P.promisifyAll(require('fs'));
var path = require('path');
var docRoot = __dirname + '/../node_modules/swagger-ui/dist/';
function staticServe (restbase, req) {
// Expand any relative paths for security
var filePath = req.query.path.replace(/\.\.\//g, '');
return fs.readFileAsync(docRoot + filePath, 'utf8')
.then(function(body) {
if (filePath === '/index.html') {
// Rewrite the HTML to use a query string
body = body.replace(/((?:src|href)=['"])/g, '$1?doc=&path=')
// Some self-promotion
.replace(/<a id="logo".*?<\/a>/,
'<a id="logo" href="http://restbase.org">RESTBase</a>')
// Replace the default url with ours
.replace(/url = "http/, 'url = "?spec"; //');
}
var contentType = 'text/html';
if (/\.js$/.test(filePath)) {
contentType = 'text/javascript';
} else if (/\.png/.test(filePath)) {
contentType = 'image/png';
} else if (/\.css/.test(filePath)) {
contentType = 'text/css';
body = body.replace(/\.\.\/(images|fonts)\//g, '?doc&path=$1/');
}
return P.resolve({
status: 200,
headers: {
'content-type': contentType,
},
body: body
});
});
}
module.exports = staticServe;
|
JavaScript
| 0 |
@@ -109,53 +109,103 @@
');%0A
-%0Avar docRoot = __dirname + '/../node_modules/
+// swagger-ui helpfully exports the absolute path of its dist directory%0Avar docRoot = require('
swag
@@ -214,17 +214,24 @@
r-ui
-/
+').
dist
+ + '
/';%0A
+%0A
func
|
b838f02fee261ae21bdacceb1d99c5d81089ff65
|
Clean up code
|
lib/tokenize.es6
|
lib/tokenize.es6
|
const SINGLE_QUOTE = '\''.charCodeAt(0);
const DOUBLE_QUOTE = '"'.charCodeAt(0);
const BACKSLASH = '\\'.charCodeAt(0);
const SLASH = '/'.charCodeAt(0);
const NEWLINE = '\n'.charCodeAt(0);
const SPACE = ' '.charCodeAt(0);
const FEED = '\f'.charCodeAt(0);
const TAB = '\t'.charCodeAt(0);
const CR = '\r'.charCodeAt(0);
const OPEN_PARENTHESES = '('.charCodeAt(0);
const CLOSE_PARENTHESES = ')'.charCodeAt(0);
const OPEN_CURLY = '{'.charCodeAt(0);
const CLOSE_CURLY = '}'.charCodeAt(0);
const SEMICOLON = ';'.charCodeAt(0);
const ASTERICK = '*'.charCodeAt(0);
const COLON = ':'.charCodeAt(0);
const AT = '@'.charCodeAt(0);
const RE_AT_END = /[ \n\t\r\{\(\)'"\\;/]/g;
const RE_WORD_END = /[ \n\t\r\(\)\{\}:;@!'"\\]|\/(?=\*)/g;
const RE_BAD_BRACKET = /.[\\\/\("'\n]/;
export default function tokenize(input) {
let tokens = [];
let css = input.css.valueOf();
let code, next, quote, lines, last, content, escape,
nextLine, nextOffset, escaped, escapePos, prev, n;
let length = css.length;
let offset = -1;
let line = 1;
let pos = 0;
function unclosed(what) {
throw input.error('Unclosed ' + what, line, pos - offset);
}
while ( pos < length ) {
code = css.charCodeAt(pos);
if ( code === NEWLINE ) {
offset = pos;
line += 1;
}
switch ( code ) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if ( code === NEWLINE ) {
offset = next;
line += 1;
}
} while ( code === SPACE ||
code === NEWLINE ||
code === TAB ||
code === CR ||
code === FEED );
tokens.push(['space', css.slice(pos, next)]);
pos = next - 1;
break;
case OPEN_CURLY:
tokens.push(['{', '{', line, pos - offset]);
break;
case CLOSE_CURLY:
tokens.push(['}', '}', line, pos - offset]);
break;
case COLON:
tokens.push([':', ':', line, pos - offset]);
break;
case SEMICOLON:
tokens.push([';', ';', line, pos - offset]);
break;
case OPEN_PARENTHESES:
prev = tokens.length ? tokens[tokens.length - 1][1] : '';
n = css.charCodeAt(pos + 1);
if ( prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE &&
n !== SPACE && n !== NEWLINE && n !== TAB &&
n !== FEED && n !== CR ) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if ( next === -1 ) unclosed('bracket');
escapePos = next;
while ( css.charCodeAt(escapePos - 1) === BACKSLASH ) {
escapePos -= 1;
escaped = !escaped;
}
} while ( escaped );
tokens.push(['brackets', css.slice(pos, next + 1),
line, pos - offset,
line, next - offset
]);
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if ( next === -1 || RE_BAD_BRACKET.test(content) ) {
tokens.push(['(', '(', line, pos - offset]);
} else {
tokens.push(['brackets', content,
line, pos - offset,
line, next - offset
]);
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
tokens.push([')', ')', line, pos - offset]);
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? '\'' : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if ( next === -1 ) unclosed('quote');
escapePos = next;
while ( css.charCodeAt(escapePos - 1) === BACKSLASH ) {
escapePos -= 1;
escaped = !escaped;
}
} while ( escaped );
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if ( last > 0 ) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['string', css.slice(pos, next + 1),
line, pos - offset,
nextLine, next - nextOffset
]);
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if ( RE_AT_END.lastIndex === 0 ) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
tokens.push(['at-word', css.slice(pos, next + 1),
line, pos - offset,
line, next - offset
]);
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while ( css.charCodeAt(next + 1) === BACKSLASH ) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if ( escape && (code !== SLASH &&
code !== SPACE &&
code !== NEWLINE &&
code !== TAB &&
code !== CR &&
code !== FEED ) ) {
next += 1;
}
tokens.push(['word', css.slice(pos, next + 1),
line, pos - offset,
line, next - offset
]);
pos = next;
break;
default:
if ( code === SLASH && css.charCodeAt(pos + 1) === ASTERICK ) {
next = css.indexOf('*/', pos + 2) + 1;
if ( next === 0 ) unclosed('comment');
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if ( last > 0 ) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['comment', content,
line, pos - offset,
nextLine, next - nextOffset
]);
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if ( RE_WORD_END.lastIndex === 0 ) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
tokens.push(['word', css.slice(pos, next + 1),
line, pos - offset,
line, next - offset
]);
pos = next;
}
break;
}
pos++;
}
return tokens;
}
|
JavaScript
| 0.000004 |
@@ -793,27 +793,24 @@
AT_END
-
= /%5B %5Cn%5Ct%5Cr%5C
@@ -846,19 +846,16 @@
_END
-
= /%5B %5Cn%5C
@@ -908,19 +908,16 @@
BRACKET
-
= /.%5B%5C%5C%5C
|
7bcc16de84c034331607edb1cff796b796c9aaa7
|
update files
|
lib/transform.js
|
lib/transform.js
|
/**
* Created by nuintun on 2015/4/27.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var Vinyl = require('vinyl');
var util = require('./util');
var through = require('@nuintun/through');
var gutil = require('@nuintun/gulp-util');
var relative = path.relative;
// blank buffer
var BLANK = Buffer.from ? Buffer.from('') : new Buffer('');
/**
* transform
*
* @param options
* @returns {Stream}
*/
module.exports = function(options) {
var initialized = false;
var defaults = util.initOptions(options);
// stream
return through({ objectMode: true }, function(vinyl, encoding, next) {
// hack old vinyl
vinyl._isVinyl = true;
// normalize vinyl base
vinyl.base = relative(vinyl.cwd, vinyl.base);
// return empty vinyl
if (vinyl.isNull()) {
return next(null, vinyl);
}
// throw error if stream vinyl
if (vinyl.isStream()) {
return next(gutil.throwError('streaming not supported.'));
}
if (!initialized) {
// debug
debug('cwd: %s', gutil.colors.magenta(gutil.normalize(util.cwd)));
initialized = true;
}
// catch error
try {
// stream
var stream = this;
// clone options
options = gutil.extend({}, defaults);
// lock wwwroot
gutil.readonlyProperty(options, 'wwwroot');
// lock plugins
gutil.readonlyProperty(options, 'plugins');
// transport
gutil.transport(vinyl, options, function(vinyl, options) {
var pool = {};
var pkg = vinyl.package;
var start = vinyl.clone();
var end = vinyl.clone();
var pathFromCwd = gutil.pathFromCwd(vinyl.path);
// set start and end file status
start.startConcat = true;
start.contents = BLANK;
end.endConcat = true;
end.contents = BLANK;
// clean vinyl
delete start.package;
delete end.package;
// compute include
options.include = gutil.isFunction(options.include)
? options.include(pkg.id || null, vinyl.path)
: options.include;
// debug
util.debug('concat: %s start', gutil.colors.magenta(pathFromCwd));
// push start blank vinyl
stream.push(start);
// include dependencies files
includeDeps.call(stream, vinyl, pool, options, function() {
// push end blank vinyl
stream.push(end);
// free memory
pool = null;
// debug
util.debug('concat: %s ...ok', gutil.colors.magenta(pathFromCwd));
next();
});
});
} catch (error) {
// show error message
util.print(colors.red.bold(error.stack) + '\x07');
next();
}
});
};
/**
* create a new vinyl
*
* @param path
* @param cwd
* @param base
* @returns {Vinyl|null}
*/
function vinylFile(path, cwd, base) {
if (!gutil.isString(path) || !gutil.isString(cwd) || !gutil.isString(base)) return null;
// file exists
if (fs.existsSync(path)) {
return new Vinyl({
path: path,
cwd: cwd,
base: base,
stat: fs.statSync(path),
contents: fs.readFileSync(path)
});
}
// file not exists
util.print('file: %s not exists', gutil.colors.yellow(gutil.pathFromCwd(path)));
return null;
}
/**
* walk file
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function walk(vinyl, pool, options, done) {
var stream = this;
var pkg = vinyl.package;
var status = pool[vinyl.path];
/**
* transport dependence file
*
* @param path
* @param next
* @returns {void}
*/
function transform(path, next) {
if (pool.hasOwnProperty(path)) {
next();
} else {
// create a vinyl file
var child = vinylFile(path, vinyl.cwd, vinyl.base);
// read file success
if (child !== null) {
// debug
util.debug('include: %s', gutil.colors.magenta(gutil.pathFromCwd(child.path)));
// transport file
gutil.transport(child, options, function(child, options) {
// cache next
status.next = next;
// add cache status
pool[child.path] = {
next: null,
parent: status,
included: false
};
// walk
walk.call(stream, child, pool, options, done);
});
} else {
next();
}
}
}
/**
* include current file and flush status
*
* @returns {void}
*/
function flush() {
// push file to stream
stream.push(vinyl);
// all file include
if (status.parent === null) {
done();
} else if (status.parent.next !== null) {
// run parent next dependencies
status.parent.next();
}
// change cache status
status.next = null;
status.included = true;
// clean parent
if (status.parent !== null) {
delete status.parent;
}
}
// bootstrap
if (status.included || !pkg) {
flush();
} else {
gutil.async.series(pkg.include, transform, flush);
}
}
/**
* include dependencies file
*
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function includeDeps(vinyl, pool, options, done) {
// return if include not equal 'all' and 'relative'
if (!options.include) {
// push file to stream
this.push(vinyl);
// free memory
pool = null;
// callback
return done();
}
// set pool cache
pool[vinyl.path] = {
next: null,
parent: null,
included: false
};
// bootstrap
walk.call(this, vinyl, pool, options, function() {
// free memory
pool = null;
// callback
done();
});
}
|
JavaScript
| 0.000001 |
@@ -1070,16 +1070,17 @@
rmalize(
+g
util.cwd
|
9278197e38dde08d73eab57dbccaa5d2a3d3a291
|
Remove console.log
|
packages/rekit-core/core/files.js
|
packages/rekit-core/core/files.js
|
const _ = require('lodash');
const shell = require('shelljs');
const path = require('path');
const fs = require('fs');
const paths = require('./paths');
const deps = require('./deps');
const chokidar = require('chokidar');
const EventEmitter = require('events');
// Maintain file structure in memory and keep sync with disk if any file changed.
const cache = {};
const parentHash = {};
const allElementById = {};
const byId = id => allElementById[id];
const watchers = {};
const files = new EventEmitter();
const emitChange = _.debounce(() => {
files.emit('change');
}, 100);
function readDir(dir) {
dir = dir || paths.map('src');
if (!watchers[dir]) startWatch(dir);
console.log('readDir', dir);
if (!cache[dir]) {
cache[dir] = getDirElement(dir);
}
const elementById = {};
const dirEle = cache[dir];
const children = [...dirEle.children];
while (children.length) {
const cid = children.pop();
const ele = byId(cid);
elementById[cid] = ele;
if (ele.children) children.push.apply(children, ele.children);
}
// Always return a cloned object to avoid acidentally cache modify
return JSON.parse(JSON.stringify({ elements: dirEle.children, elementById }));
}
function startWatch(dir) {
const w = chokidar.watch(dir, { persistent: true, awaitWriteFinish: false });
w.on('ready', () => {
w.on('add', onAdd);
w.on('change', onChange);
w.on('unlink', onUnlink);
w.on('addDir', onAddDir);
w.on('unlinkDir', onUnlinkDir);
});
watchers[dir] = w;
}
const setLastChangeTime = () => {
files.lastChangeTime = Date.now();
};
function onAdd(file) {
console.log('on add', file);
const prjRoot = paths.getProjectRoot();
const rFile = file.replace(prjRoot, '');
allElementById[rFile] = getFileElement(file);
const dir = path.dirname(rFile);
byId(dir).children.push(rFile);
sortElements(byId(dir).children);
setLastChangeTime();
emitChange();
}
function onUnlink(file) {
console.log('on unlink', file);
const prjRoot = paths.getProjectRoot();
const rFile = file.replace(prjRoot, '');
delete allElementById[rFile];
const dir = path.dirname(rFile);
_.pull(byId(dir).children, rFile);
setLastChangeTime();
emitChange();
}
function onChange(file) {
console.log('on change', file);
const prjRoot = paths.getProjectRoot();
const rFile = file.replace(prjRoot, '');
allElementById[rFile] = getFileElement(file);
setLastChangeTime();
emitChange();
}
function onAddDir(file) {
console.log('on add dir', arguments);
const prjRoot = paths.getProjectRoot();
const rFile = file.replace(prjRoot, '');
allElementById[rFile] = getDirElement(file);
const dir = path.dirname(rFile);
byId(dir).children.push(rFile);
sortElements(byId(dir).children);
setLastChangeTime();
emitChange();
}
function onUnlinkDir(file) {
console.log('on unlink dir', arguments);
onUnlink(file);
setLastChangeTime();
emitChange();
}
function getDirElement(dir) {
const prjRoot = paths.getProjectRoot();
let rDir = dir.replace(prjRoot, '');
if (!rDir) rDir = '.'; // root dir
const dirEle = {
name: path.basename(dir),
type: 'folder',
id: rDir,
children: [],
};
allElementById[rDir] = dirEle;
shell.ls(dir).forEach(file => {
file = paths.join(dir, file);
const rFile = file.replace(prjRoot, '');
dirEle.children.push(rFile);
parentHash[rFile] = rDir;
if (shell.test('-d', file)) {
getDirElement(file);
} else {
getFileElement(file);
}
});
sortElements(dirEle.children, allElementById);
return dirEle;
}
function getFileElement(file) {
const prjRoot = paths.getProjectRoot();
const rFile = file.replace(prjRoot, '');
const ext = path.extname(file).replace('.', '');
const size = fs.statSync(file).size;
const fileEle = {
name: path.basename(file),
type: 'file',
ext,
size,
id: rFile,
};
allElementById[rFile] = fileEle;
const fileDeps = size < 50000 ? deps.getDeps(rFile) : null;
if (fileDeps) {
fileEle.views = [
{ key: 'diagram', name: 'Diagram' },
{
key: 'code',
name: 'Code',
target: rFile,
isDefault: true,
},
];
fileEle.deps = fileDeps;
}
return fileEle;
}
function sortElements(elements) {
elements.sort((a, b) => {
a = byId(a);
b = byId(b);
if (!a || !b) {
console.log('Error in sortElement'); // should not happen?
return 0;
}
if (a.children && !b.children) return -1;
else if (!a.children && b.children) return 1;
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
return elements;
}
files.readDir = readDir;
// files.setFileChanged = setFileChanged;
module.exports = files;
|
JavaScript
| 0.000004 |
@@ -677,39 +677,8 @@
r);%0A
- console.log('readDir', dir);%0A
if
@@ -1923,42 +1923,8 @@
) %7B%0A
- console.log('on unlink', file);%0A
co
@@ -1953,32 +1953,32 @@
tProjectRoot();%0A
+
const rFile =
@@ -2181,42 +2181,8 @@
) %7B%0A
- console.log('on change', file);%0A
co
@@ -2382,48 +2382,8 @@
) %7B%0A
- console.log('on add dir', arguments);%0A
co
@@ -2650,32 +2650,32 @@
emitChange();%0A%7D%0A
+
function onUnlin
@@ -2691,51 +2691,8 @@
) %7B%0A
- console.log('on unlink dir', arguments);%0A
on
|
9bdb7eed5695864247cc926775c527520e68cb9d
|
Send proper error object
|
packages/relay/src/Environment.js
|
packages/relay/src/Environment.js
|
// @flow
import { DeviceInfo } from '@kiwicom/mobile-localization';
import {
Environment,
Network,
RecordSource,
Store,
Observable,
} from 'relay-runtime';
import fetchWithRetries from '@kiwicom/fetch';
// This works, and requires no native setup. Note that @sentry/node does not work since it relies on crypto module, which is not available in RN
// TODO: try to use rn-nodeify and react-native-crypt and use @sentry/node next time target-version changes
import * as Sentry from '@sentry/browser';
import { SENTRY_DSN } from 'react-native-dotenv';
import ConnectionManager from './ConnectionManager';
import CacheManager from './CacheManager';
type FetcherResponse = {|
+data: Object,
+errors?: $ReadOnlyArray<Object>,
|};
let useSentry;
const { NODE_ENV } = process.env;
try {
// The app will crash if SENTRY_DSN is wrong. Let's rather deactivate it if it for some reason is not set correctly
Sentry.init({ dsn: SENTRY_DSN, enabled: NODE_ENV !== 'development' });
useSentry = true;
} catch {
useSentry = false;
}
const logError = error => {
if (useSentry) {
Sentry.captureException(error);
}
};
const GRAPHQL_URL = 'https://graphql.kiwi.com/';
const store = new Store(new RecordSource());
async function fetchFromTheNetwork(
networkHeaders,
operation,
variables,
observer,
) {
try {
const fetchResponse = await fetchWithRetries(GRAPHQL_URL, {
method: 'POST',
headers: networkHeaders,
body: JSON.stringify({
query: operation.text, // TODO: fetch persisted queries instead (based on operation.id)
variables,
}),
fetchTimeout: 15000,
retryDelays: [1000, 3000],
});
const jsonResponse = await fetchResponse.json();
if (jsonResponse.errors) {
jsonResponse.errors.forEach(error => {
console.warn(error);
logError(error);
});
}
if (operation.operationKind !== 'mutation') {
CacheManager.set(operation.name, variables, jsonResponse);
}
observer.next(jsonResponse);
observer.complete();
} catch (error) {
// Handle error from fetch, unless we will see loader forever
observer.error(error);
observer.complete();
console.warn(error);
logError(error);
}
}
const handleNoNetworkNoCachedResponse = observer => {
// If not we are stuck on loader forever.
observer.error({ message: 'No network' });
observer.complete();
};
const asyncStoreRead = async (observer, operation, variables) => {
try {
const cachedData = await CacheManager.get(operation.name, variables);
if (cachedData) {
// It loads smoother if we do this in a set timeout
// If we don't the UI freezes for a while
setTimeout(() => {
observer.next(cachedData);
if (ConnectionManager.isConnected() === false) {
observer.complete();
}
});
} else if (ConnectionManager.isConnected() === false) {
handleNoNetworkNoCachedResponse(observer);
}
} catch (error) {
// AsyncStorage read wasn't successful - nevermind
console.warn('error', error);
}
};
export default function createEnvironment(accessToken: string = '') {
const networkHeaders: Object = {
Accept: 'application/json',
'Content-Type': 'application/json',
'Accept-Language': DeviceInfo.getLocaleUnderscored(),
};
if (accessToken) {
networkHeaders.authorization = accessToken;
}
const fetchQuery = (operation, variables): Promise<FetcherResponse> => {
return Observable.create(observer => {
if (operation.operationKind !== 'mutation') {
asyncStoreRead(observer, operation, variables);
}
if (ConnectionManager.isConnected()) {
fetchFromTheNetwork(networkHeaders, operation, variables, observer);
}
});
};
return new Environment({
network: Network.create(fetchQuery),
store,
});
}
|
JavaScript
| 0 |
@@ -1111,21 +1111,40 @@
ception(
-error
+new Error(error.message)
);%0A %7D%0A%7D
|
ec8eae523d0eb811d30eae7dc903937b2c978b93
|
use require.resolve for mocha bin in runtests
|
scripts/lib/runtests.js
|
scripts/lib/runtests.js
|
var mochaPhantom = require('./mocha-phantomjs');
var spawn = require('child_process').spawn;
var getStaticServer = require('./static-server');
var path = require('path');
var utils = require('./utils');
var lookup = utils.lookup;
var promiseSequence = utils.promiseSequence;
function mochaRun() {
return new Promise((resolve, reject) => {
try {
const proc = spawn(lookup('.bin/nyc', true), [
'--require', '@babel/register',
'--exclude',
'tests/**',
'--silent',
'--no-clean',
lookup('.bin/mocha', true),
'-R', 'spec',
'-r', 'tests/setup',
'-r', '@babel/register',
'tests'
], {
cwd: path.join(__dirname, '../..'),
env: process.env
});
proc.stdout.pipe(process.stdout);
proc.stderr.pipe(process.stderr);
proc.on('error', (err) => reject(err));
proc.on('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error('test failed. nyc/mocha exit code: ' + code));
}
});
} catch (err) {
reject(err);
}
});
}
function runtests() {
return new Promise((resolve, reject) => {
var server;
return mochaRun().then(() => {
return getStaticServer().then((args) => {
server = args[0];
const port = args[1];
const promises = ['index', 'slim'].map(
f => (() => mochaPhantom(`http://localhost:${port}/tests/browser/${f}.html`)));
return promiseSequence(promises).then(() => {
server.close();
resolve();
});
});
}).catch((err) => {
if (server) {
server.close();
}
reject(err);
});
});
}
module.exports = runtests;
|
JavaScript
| 0 |
@@ -530,25 +530,39 @@
-lookup('.
+require.resolve('mocha/
bin/moch
@@ -563,22 +563,16 @@
n/mocha'
-, true
),%0A
|
2c9ee8dd3d33eacadfb201f4ec503107a53a3e3d
|
fix ledger hardware wallet to support 32bits chainId
|
src/wallets/hardware/ledger/index.js
|
src/wallets/hardware/ledger/index.js
|
import Ledger from '@ledgerhq/hw-app-eth';
import { byContractAddress } from '@ledgerhq/hw-app-eth/erc20';
import ethTx from 'ethereumjs-tx';
import u2fTransport from '@ledgerhq/hw-transport-u2f';
import webUsbTransport from '@ledgerhq/hw-transport-webusb';
import { LEDGER as ledgerType } from '../../bip44/walletTypes';
import bip44Paths from '../../bip44';
import HDWalletInterface from '@/wallets/HDWalletInterface';
import * as HDKey from 'hdkey';
import platform from 'platform';
import {
getSignTransactionObject,
getBufferFromHex,
sanitizeHex,
calculateChainIdFromV
} from '../../utils';
import { toBuffer } from 'ethereumjs-util';
import errorHandler from './errorHandler';
const NEED_PASSWORD = false;
const OPEN_TIMEOUT = 10000;
const LISTENER_TIMEOUT = 15000;
class ledgerWallet {
constructor() {
this.identifier = ledgerType;
this.isHardware = true;
this.needPassword = NEED_PASSWORD;
this.supportedPaths = bip44Paths[ledgerType];
}
async init(basePath) {
this.basePath = basePath ? basePath : this.supportedPaths[0].path;
this.isHardened = this.basePath.split('/').length - 1 === 2;
this.transport = await getLedgerTransport();
this.ledger = new Ledger(this.transport);
this.appConfig = await getLedgerAppConfig(this.ledger);
if (!this.isHardened) {
const rootPub = await getRootPubKey(this.ledger, this.basePath);
this.hdKey = new HDKey();
this.hdKey.publicKey = Buffer.from(rootPub.publicKey, 'hex');
this.hdKey.chainCode = Buffer.from(rootPub.chainCode, 'hex');
}
}
async getAccount(idx) {
let derivedKey, accountPath;
if (this.isHardened) {
const rootPub = await getRootPubKey(
this.ledger,
this.basePath + '/' + idx + "'"
);
const hdKey = new HDKey();
hdKey.publicKey = Buffer.from(rootPub.publicKey, 'hex');
hdKey.chainCode = Buffer.from(rootPub.chainCode, 'hex');
derivedKey = hdKey.derive('m/0/0');
accountPath = this.basePath + '/' + idx + "'" + '/0/0';
} else {
derivedKey = this.hdKey.derive('m/' + idx);
accountPath = this.basePath + '/' + idx;
}
const txSigner = async tx => {
tx = new ethTx(tx);
const networkId = tx._chainId;
tx.raw[6] = Buffer.from([networkId]);
tx.raw[7] = Buffer.from([]);
tx.raw[8] = Buffer.from([]);
const tokenInfo = byContractAddress('0x' + tx.to.toString('hex'));
if (tokenInfo) await this.ledger.provideERC20TokenInformation(tokenInfo);
const result = await this.ledger.signTransaction(
accountPath,
tx.serialize().toString('hex')
);
tx.v = getBufferFromHex(result.v);
tx.r = getBufferFromHex(result.r);
tx.s = getBufferFromHex(result.s);
const signedChainId = calculateChainIdFromV(tx.v);
if (signedChainId !== networkId)
throw new Error(
'Invalid networkId signature returned. Expected: ' +
networkId +
', Got: ' +
signedChainId,
'InvalidNetworkId'
);
return getSignTransactionObject(tx);
};
const msgSigner = async msg => {
const result = await this.ledger.signPersonalMessage(
accountPath,
toBuffer(msg).toString('hex')
);
const v = parseInt(result.v, 10) - 27;
const vHex = sanitizeHex(v.toString(16));
return Buffer.concat([
getBufferFromHex(result.r),
getBufferFromHex(result.s),
getBufferFromHex(vHex)
]);
};
const displayAddress = async () => {
await this.ledger.getAddress(accountPath, true, false);
};
return new HDWalletInterface(
accountPath,
derivedKey.publicKey,
this.isHardware,
this.identifier,
errorHandler,
txSigner,
msgSigner,
displayAddress
);
}
getCurrentPath() {
return this.basePath;
}
getSupportedPaths() {
return this.supportedPaths;
}
}
const createWallet = async basePath => {
const _ledgerWallet = new ledgerWallet();
await _ledgerWallet.init(basePath);
return _ledgerWallet;
};
createWallet.errorHandler = errorHandler;
const isWebUsbSupported = async () => {
const isSupported = await webUsbTransport.isSupported();
return isSupported && platform.os.family !== 'Windows'; // take it out later once the windows issue is fixed
};
const getLedgerTransport = async () => {
let transport;
const support = await isWebUsbSupported();
if (support) {
transport = await webUsbTransport.create();
} else {
transport = await u2fTransport.create(OPEN_TIMEOUT, LISTENER_TIMEOUT);
}
return transport;
};
const getLedgerAppConfig = async _ledger => {
const appConfig = await _ledger.getAppConfiguration();
return appConfig;
};
const getRootPubKey = async (_ledger, _path) => {
const pubObj = await _ledger.getAddress(_path, false, true);
return {
publicKey: pubObj.publicKey,
chainCode: pubObj.chainCode
};
};
export default createWallet;
|
JavaScript
| 0 |
@@ -2257,29 +2257,16 @@
aw%5B6%5D =
-Buffer.from(%5B
networkI
@@ -2266,18 +2266,16 @@
etworkId
-%5D)
;%0A
@@ -2612,24 +2612,295 @@
')%0A );%0A
+%0A // EIP155 support. check/recalc signature v value.%0A let v = result.v;%0A const rv = parseInt(v, 16);%0A let cv = networkId * 2 + 35;%0A if (rv !== cv && (rv & cv) !== rv) %7B%0A cv += 1; // add signature v bit.%0A %7D%0A v = cv.toString(16);%0A%0A
tx.v =
@@ -2917,23 +2917,16 @@
FromHex(
-result.
v);%0A
|
bf94576f1626e835b7cb62d13b3b5264c9c0c9f3
|
Improve tnl messaging
|
commands/tnl.js
|
commands/tnl.js
|
'use strict';
const sprintf = require('sprintf').sprintf;
const LevelUtil = require('../src/levels').LevelUtil;
const util = require('util');
exports.command = (rooms, items, players, npcs, Commands) => {
return (args, player) => {
const playerExp = player.getAttribute('experience');
const tolevel = LevelUtil.expToLevel(player.getAttribute('level'));
const percentage = parseInt((playerExp / tolevel) * 100, 10);
const color = 'blue';
let msg = '...';
util.log(player.getName() + ' experience: ' + playerExp + ' To Level: ', tolevel, ' ');
util.log('%' + percentage + ' tnl.');
const toLevelStatus = {
0: 'You have far to go before advancing again.',
25: 'You have a journey ahead before advancing.',
50: 'You feel that you have more to learn before advancing.',
75: 'You have learned much since you last advanced.',
90: 'You are on the cusp of a breakthrough...'
};
for (let tier in toLevelStatus) {
if (percentage >= parseInt(tier, 10)) {
msg = '<' + color + '>' + toLevelStatus[tier] +
'</' + color + '>';
}
}
player.say(msg);
};
};
|
JavaScript
| 0.000001 |
@@ -658,40 +658,25 @@
ave
-far to go before advancing again
+recently advanced
.',%0A
@@ -685,10 +685,10 @@
-25
+10
: 'Y
@@ -697,16 +697,24 @@
have a
+lengthy
journey
@@ -749,10 +749,10 @@
+3
5
-0
: 'Y
@@ -817,10 +817,10 @@
-75
+66
: 'Y
|
0f929809d08db22f3187735f14606d9cb8b45e8e
|
Revert "fix: wah, typo - correct order for subtraction"
|
app/assets/javascripts/auto/jobs.js
|
app/assets/javascripts/auto/jobs.js
|
/* -*- coding: utf-8 -*- */
/* global cforum, Highcharts, t */
cforum.admin.jobs = {
jobsCount: null,
index: function() {
Highcharts.setOptions({
lang: t('highcharts')
});
var keys = cforum.admin.jobs.jobsCount.sort(function(a,b) {
var a_date = new Date(a.day);
var b_date = new Date(b.day);
return b_date.getTime() - a_date.getTime();
});
$("#chart").highcharts({
chart: { type: 'spline' },
title: null,
xAxis: {
categories: $.map(keys,
function(val, i) {
return Highcharts.dateFormat("%A, %d. %B %Y",
new Date(val.day));
})
},
yAxis: { title: { text: t('highcharts.cnt_jobs') } },
series: [{
name: t('highcharts.jobs'),
data: $.map(keys, function(val, i) { return val.cnt; })
}]
});
}
};
/* eof */
|
JavaScript
| 0 |
@@ -334,17 +334,17 @@
return
-b
+a
_date.ge
@@ -353,17 +353,17 @@
ime() -
-a
+b
_date.ge
|
0707d7242c657841e21d05bfc49509d8d36fad61
|
remove gchq
|
rest/api.js
|
rest/api.js
|
// libs
var express = require('express');
//API implementations
var login = require('./Login');
var deceased = require('./Deceased');
var recipients = require('./Recipient');
var events = require('./Events');
var messages = require('./Messages');
var encryption = require('../gchq_encryption/encrypt')
// express router
var router = express.Router();
module.exports = function() {
router.post('/login', function (req, res) {
login.login((e,r) => {
res.json( {error: e, set: r});
}, req.body.email);
});
router.get('/', function (req, res) {
res.send('Hello World!');
});
router.get('/deceased', function (req, res) {
deceased.getDeceaseds((e, r) => {
res.json({ error: e, set: r });
});
});
router.get('/deceased/:id', function (req, res) {
deceased.getDeceased((e, r) => {
res.json({ error: e, set: r });
}, req.params.id);
});
router.post('/deceased', function (req, res) {
deceased.postDeceased((e,r) => {
res.json( {error: e, set: r});
}, req.body.firstName, req.body.lastName, req.body.email, req.body.phone);
});
router.patch('/deceased/:id', function (req, res) {
deceased.patchDeceased((e,r) => {
res.json( {error: e, set: r});
}, req.params.id, req);
});
router.patch('/deceased/:id/hasDied', function (req, res) {
deceased.patchSetDeceased((e,r) => {
res.json( {error: e, set: r});
}, req.params.id, req.body.deceasedDate);
});
router.patch('/deceased/:id/checkin', function (req, res) {
deceased.patchSetCheckIn((e, r) => {
res.json( {error: e, set: r});
}, req.params.id);
});
router.patch('/deceased/:id/frequency', function (req, res) {
deceased.patchSetInterval((e, r) => {
res.json ( { error:e, set:r});
}, req.params.id, req.body.frequency);
});
router.delete('/deceased/:id', function (req, res) {
deceased.deleteDeceased((e, r) => {
res.json ( {error: e, set: r});
}, req.params.id);
});
router.get('/deceased/:id/recipients', function (req, res) {
recipients.getRecipientsForDeceased((e, r) => {
res.json ( {error: e, set:r});
}, req.params.id)
})
router.get('/recipients/:id', function (req, res) {
recipients.getRecipient((e, r) => {
res.json ( {error: e, set: r});
}, req.params.id);
});
router.post('/recipients', function (req, res) {
recipients.postRecipient((e,r) => {
res.json ( {error: e, set: r});
}, req.body.firstName, req.body.lastName, req.body.recipientNickName, req.body.senderNickName, req.body.phone, req.body.email, req.body.twitter, req.body.deceasedId, req.body.dateOfBirth, req.body.meetupEnabled, req.body.sex);
});
router.patch('/recipients/:id', function (req, res) {
recipients.patchRecipient((e,r) => {
res.json ( {error: e, set: r});
}, req.params.id, req.body.firstName, req.body.lastName, req.body.recipientNickName, req.body.senderNickName, req.body.phone, req.body.email, req.body.twitter);
});
router.patch('/recipients/:id/meetup', function (req, res) {
recipients.patchRecipientMeetup((e,r) => {
res.json ( {error: e, set: r});
}, req.params.id, req.body.meetupEnabled);
});
router.delete('/recipients/:id', function (req, res) {
recipients.deleteRecipient((e,r) => {
res.json ( {error: e, set: r});
}, req.params.id);
});
router.get('/events/:id', function(req, res) {
events.getEvent((e, r) => {
res.json( { error: e, set: r});
}, req.params.id);
});
router.post('/events', function (req, res) {
events.postEvent((e,r) => {
res.json ( {error: e, set: r});
}, req.body.date, req.body.type, req.body.recipientId, req.body.deceasedId, req.body.repeat, req.body.messageText, req.body.sms, req.body.email, req.body.twitter, req.body.minsAfterDeath);
});
router.patch('/events/:id', function (req, res) {
events.patchEvent((e,r) => {
res.json ( {error: e, set: r});
}, req.params.id, req.body.date, req.body.type, req.body.recipientId, req.body.deceasedId, req.body.repeat, req.body.messageText, req.body.sms, req.body.email, req.body.twitter);
});
router.delete('/events/:id', function (req, res) {
events.deleteEvent((e,r) => {
res.json ( {error: e, set: r});
}, req.params.id);
});
router.get('/recipients/:id/events', function (req, res) {
events.getEventsForRecipient((e,r) => {
res.json( { error: e, set: r});
}, req.params.id);
})
router.get('/recipients/:id/messages', function (req, res) {
messages.getMessagesForRecipient((e, r) => {
res.json( { error: e, set: r});
}, req.params.id);
})
router.post('/messages', function (req, res) {
messages.postMessage((e, r) => {
res.json( { error: e, set: r});
}, req.body.message);
});
router.delete('/messages/:id', function (req, res) {
messages.deleteMessage((e, r) => {
res.json( { error: e, set: r});
}, req.params.id);
});
router.post('/sensitive_data/send', function(req, res) {
encryption.encryptAndStore(req.body.message, req.body.id);
});
router.post('/sensitive_data/receive', function(req, res) {
encryption.decryptAndSend(req.body.message, req.body.seed);
});
return router;
}
|
JavaScript
| 0.001167 |
@@ -242,16 +242,18 @@
ges');%0A%0A
+//
var encr
@@ -5408,24 +5408,26 @@
%7D);%0A%0A%0A%0A
+/*
router.post(
@@ -5682,24 +5682,26 @@
ed);%0A %7D);
+*/
%0A return
|
7873947798061d81b37b0d83f5c38e6e516b2c26
|
Add newline at end before writing package json files
|
scripts/next-release.js
|
scripts/next-release.js
|
const execSync = require('child_process').execSync;
const fs = require('fs');
const os = require('os');
const readline = require('readline');
const path = require('path');
const config = {
packageJson: {
file: path.join(__dirname, '../frontend/package.json')
},
packageJsonLock: {
file: path.join(__dirname, '../frontend/package-lock.json')
},
gradleProperties: {
file: path.join(__dirname, '../backend/gradle.properties')
}
};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
/**
* Gets the current version from the package.json file.
*
* @returns {string} the version in x.y.z or x.y.z-SNAPSHOT format
*/
function getCurrentVersion() {
const packageJsonContent = fs.readFileSync(config.packageJson.file, 'utf8');
const packageJson = JSON.parse(packageJsonContent);
return packageJson.version;
}
/**
* Increments the revision of the given release version. Ex. 1.0.0 becomes 1.0.1
*
* @param {string} version the current version
* @returns {string} the next version revision
*/
function incrementVersion(version) {
const [major, minor, revision] = version.split('.');
const newRevision = parseInt(revision, 10) + 1;
return `${major}.${minor}.${newRevision}`;
}
/**
* Updates the version property of package.json and package-lock.json files.
*
* @param {string} version the release version
*/
function updatePackageJson(version) {
console.log('updating package.json...');
const packageJsonContent = fs.readFileSync(config.packageJson.file, 'utf8');
const packageJson = JSON.parse(packageJsonContent);
packageJson.version = version;
fs.writeFileSync(config.packageJson.file, JSON.stringify(packageJson, null, 2));
console.log('updating package-lock.json...');
const packageJsonLockContent = fs.readFileSync(config.packageJsonLock.file, 'utf8');
const packageJsonLock = JSON.parse(packageJsonLockContent);
packageJsonLock.version = version;
fs.writeFileSync(config.packageJsonLock.file, JSON.stringify(packageJsonLock, null, 2));
}
/**
* Updates the buildVersion property of the gradle.properties file.
*
* @param {string} version the release version
*/
function updateGradleProperties(version) {
console.log('updating gradle.properties...');
const gradlePropertiesContent = fs.readFileSync(config.gradleProperties.file, 'utf8');
const gradleProperties = gradlePropertiesContent.split(os.EOL);
let newGradleProperties = '';
for (const property of gradleProperties) {
if (property) {
const [key, value] = property.split('=');
if (key === 'buildVersion') {
newGradleProperties += `${key}=${version}`;
} else {
newGradleProperties += `${key}=${value}`;
}
newGradleProperties += os.EOL;
}
}
fs.writeFileSync(config.gradleProperties.file, newGradleProperties);
}
/**
* Performs the following git operations:
*
* ```
* git reset
* git add package.json package-lock.json gradle.properties
* git commit -m "message"
* ```
* @param {string} version the release version
*/
function gitCommit(version) {
let commitMsg = '';
if (isSnapshotVersion(version)) {
commitMsg = 'Next snapshot version';
} else {
commitMsg = `Release ${version}`;
}
console.log(`committing changes with message: '${commitMsg}'`);
execSync('git reset'); // unstage any extraneous changes. commit only package json and gradle props files
execSync(`git add ${config.packageJson.file} ${config.packageJsonLock.file} ${config.gradleProperties.file}`);
execSync(`git commit -m "${commitMsg}"`);
}
/**
* Updates the necessary files to include - package.json, package-lock.json and gradle.properties as part of the next
* release process.
*
* @param {string} version the release version
*/
function updateFiles(version) {
updatePackageJson(version);
updateGradleProperties(version);
gitCommit(version);
}
/**
* Prompts for the next release version, which is optional.
*
* @param {string} defaultNextVersion the next version to be used if one is not specified
*/
function promptForNextVersion(defaultNextVersion) {
rl.prompt();
rl.on('line', (line) => {
const nextVersion = line.trim();
if (nextVersion) {
console.log(`Next version will be: '${nextVersion}'`);
updateFiles(nextVersion);
} else {
console.log(`Next version will be: '${defaultNextVersion}'`);
updateFiles(defaultNextVersion);
}
process.exit(0);
}).on('close', () => {
process.exit(0);
});
}
/**
* Determines if the given version is a SNAPSHOT or full release version
*
* @param {string} buildVersion
* @returns {boolean} true if SNAPSHOT version, otherwise false
*/
function isSnapshotVersion(buildVersion) {
return buildVersion.includes('SNAPSHOT');
}
/**
* Prepares for the next release either by incrementing the next version as x.y.z-SNAPSHOT or removing SNAPSHOT.
*/
function prepareNextRelease() {
const currentVersion = getCurrentVersion();
if (isSnapshotVersion(currentVersion)) {
makeRelease(currentVersion);
} else {
nextSnapshot(currentVersion);
}
}
/**
* Prepares for the next release with the next SNAPSHOT version.
*
* @param {string} snapshotVersion the SNAPSHOT version
*/
function makeRelease(snapshotVersion) {
const releaseVersion = snapshotVersion.substring(0, snapshotVersion.indexOf('-SNAPSHOT'));
console.log('Preparing for release...');
console.log(`Current snapshot: '${snapshotVersion}'`);
console.log(`Releasing version: '${releaseVersion}'`);
updateFiles(releaseVersion);
process.exit(0);
}
/**
* Prepares for the next release with the next SNAPSHOT version.
*
* @param {string} currentVersion the current release version
*/
function nextSnapshot(currentVersion) {
const defaultNextVersion = incrementVersion(currentVersion);
const snapshotVersion = `${defaultNextVersion}-SNAPSHOT`;
console.log('Preparing for next version...');
console.log(`Current version: '${currentVersion}'`);
console.log(`Optionally enter next version. Will use: '${defaultNextVersion}' (${snapshotVersion}) if not specified`);
promptForNextVersion(snapshotVersion);
}
prepareNextRelease();
|
JavaScript
| 0 |
@@ -1710,16 +1710,31 @@
null, 2)
+.concat(os.EOL)
);%0A%0A co
@@ -2051,16 +2051,31 @@
null, 2)
+.concat(os.EOL)
);%0A%7D%0A%0A/*
|
faba9410436f531170789416191a77b5f3dea0bb
|
Update meta count in store
|
components/NewChat.js
|
components/NewChat.js
|
import React, { Component } from 'react'
import { withApollo, gql } from 'react-apollo'
import _ from 'lodash'
import withData from '../lib/withData'
import { GC_USER_ID, GC_USERNAME } from '../constants'
import { ALL_CHATROOMS_QUERY } from './ChatList'
class NewChat extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
}
}
onCreateChat = async (e) => {
e.preventDefault()
const currentUserId = this.props.currentUserId
if(!currentUserId) {
alert('You must log in first.')
return
}
try {
const userCount = (await this.props.client.query({ query: USER_COUNT_QUERY })).data._allUsersMeta.count
const randomSkip = _.random(0, userCount - 2)
if(userCount - 2 < 0) {
alert("Oops, can't find any users.")
return
}
const twoRandomUserIds = (await this.props.client.query({
query: GET_USERS_QUERY,
variables: {
first: 2,
skip: randomSkip,
}
})).data.allUsers.map(u => u.id)
const anotherUserId = twoRandomUserIds[0] !== currentUserId ? twoRandomUserIds[0] : twoRandomUserIds[1]
const { data: { createChatroom: { id } } } = await this.props.client.mutate({
mutation: CREATE_CHAT_MUTATION,
variables: {
title: this.state.title,
userIds: [currentUserId, anotherUserId],
},
optimisticResponse: {
__typename: 'Mutation',
createChatroom: {
__typename: 'Chatroom',
id: '',
createdAt: +new Date,
title: this.state.title,
users: [
{
__typename: 'User',
id: '',
username: localStorage.getItem(GC_USERNAME),
}
],
}
},
update: (store, { data: { createChatroom }}) => {
// Update the store (so that the graphql components across the app will get updated)
// 1. read from store
const data = store.readQuery({
query: ALL_CHATROOMS_QUERY,
})
// 2. append at first position
data.allChatrooms.splice(0,0,createChatroom)
// 3. write back
store.writeQuery({
query: ALL_CHATROOMS_QUERY,
data
})
},
})
this.setState({
title: '',
})
this.props.onCreateNewChatroom(id)
} catch(err) {
alert("Oops: " + err.graphQLErrors[0].message);
}
}
render() {
const confirmDisabled = !this.state.title
return (
<div>
<form onSubmit={this.onCreateChat}>
<input
value={this.state.title}
onChange={e => this.setState({ title: e.target.value})}
placeholder="insert a topic here"
type="text"
className="add-chat-input"
/>
<button
className="primary-button"
type="submit"
disabled={confirmDisabled}
>
Create chat
</button>
<style jsx>{`
.add-chat-input {
height: 26px;
margin-right: 8px;
}
.primary-button {
border: none;
}
`}</style>
</form>
</div>)
}
}
const CREATE_CHAT_MUTATION = gql`
mutation CreateChatroomMutation($title: String!, $userIds: [ID!]!) {
createChatroom(title: $title, usersIds: $userIds) {
id,
createdAt,
title,
users {
id,
username,
}
}
}
`
const USER_COUNT_QUERY = gql`
query UserCountQuery {
_allUsersMeta {
count
}
}
`
const GET_USERS_QUERY = gql`
query GetUsersQuery($first: Int!, $skip: Int!) {
allUsers(first: $first, skip: $skip) {
id,
}
}
`
NewChat.propTypes = {
currentUserId: React.PropTypes.string.isRequired,
}
export default withData(withApollo(NewChat))
|
JavaScript
| 0 |
@@ -2213,16 +2213,60 @@
hatroom)
+%0A data._allChatroomsMeta.count += 1
%0A%0A
|
e27311e044207f4537f1f9d9c1dcbf3ee84455b2
|
Fix error. Where if you do shift select and click another element (so all others are unselected) the class is-selected does not get removed from others
|
addon/pods/components/frost-list-item/component.js
|
addon/pods/components/frost-list-item/component.js
|
import Ember from 'ember'
import _ from 'lodash/lodash'
import FrostList from '../frost-list/component'
export default Ember.Component.extend({
classNameBindings: ['isSelected', 'frost-list-item'],
initContext: Ember.on('init', function () {
this.set('_frostList', this.nearestOfType(FrostList))
}),
isSelected: Ember.computed.reads('model.isSelected'),
onclick: Ember.on('click', function (event) {
if (!(Ember.ViewUtils.isSimpleClick(event) || event.shiftKey || event.metaKey || event.ctrlKey)) {
return true
}
event.preventDefault()
event.stopPropagation()
if (_.isFunction(this.get('_frostList.onSelect'))) {
let isTargetSelectionIndicator = Ember.$(event.target).hasClass('frost-list-selection-indicator')
if (event.shiftKey && (!this.get('_frostList.persistedClickState.isSelected')) && !this.get('isSelected')) {
this.get('_frostList.onShiftSelect').call(this.get('_frostList'), {
secondClickedRecord: this.get('model'),
isTargetSelectionIndicator: isTargetSelectionIndicator
})
if (window.getSelection) {
window.getSelection().removeAllRanges()
} else if (document.selection) { // IE
document.selection.empty()
}
} else {
this.get('_frostList.onSelect')({
record: this.get('model'),
isSelected: !this.get('model.isSelected'),
isTargetSelectionIndicator: isTargetSelectionIndicator,
isShiftSelect: false,
isCtrlSelect: (event.metaKey || event.ctrlKey) && (!this.get('_frostList.persistedClickState.isSelected')) && !this.get('isSelected')
})
}
this.set('_frostList.persistedClickState', {clickedRecord: this.get('model'), isSelected: this.get('isSelected')})
this.get('isSelected') ? this.$().parent().removeClass('is-selected') : this.$().parent().addClass('is-selected')
}
})
})
|
JavaScript
| 0.000001 |
@@ -362,16 +362,209 @@
cted'),%0A
+ isSelectedChanged: Ember.observer('model.isSelected', function () %7B%0A this.get('isSelected') ? this.$().parent().addClass('is-selected') : this.$().parent().removeClass('is-selected')%0A %7D),
%0A oncli
@@ -1979,128 +1979,8 @@
)%7D)%0A
- this.get('isSelected') ? this.$().parent().removeClass('is-selected') : this.$().parent().addClass('is-selected')%0A
|
bcdb74ba15c207c91828963aaa28b0d773838a31
|
update jsdoc in table
|
common/Table.js
|
common/Table.js
|
/**
* Created by tsmish on 13/08/16.
*/
import { Card } from './Card'
import { Player } from './Player'
export class Table {
constructor() {
/**
* An array of players sitting on the table
*
* @type [player]
*/
this.players = [];
/**
* An array of currently active cards (in the middle of table)
*
* @type [string]
*/
this.activeCards = [];
/**
* An array of discarded doors
*
* @type [string]
*/
this.discardedDoors = [];
/**
* An array of discarded treasure cards
*
* @type [string]
*/
this.discardedTreasure = [];
/**
* Determines if there is an active game playing
*
* @type {bool}
*/
this.playing = false;
/**
* Determines whose is the current turn
* idx in {players}
*
* @type {string}
*/
this.turn = 0;
/**
* Currently going fight
*
* @type {Fight|null}
*/
this.fight = null;
/**
* begin -> open -> hand -> closed -> drop
*
* @type {string}
*/
this.phase = 'begin';
}
/**
* Move the card to the discard deck
*
* @param card
*/
discard(card) {
if (Card.byId(card).kind == 'door') {
this.discardedDoors.push(card);
} else if (Card.byId(card).kind == 'treasure') {
this.discardedTreasure.push(card);
}
}
/**
* Return the player whose turn it is right now
*
* @returns {Player}
*/
currentPlayer() {
return this.players[this.turn];
}
/**
* Modifies the turn member so it points to the next player
*/
nextTurn() {
this.turn = (this.turn + 1) % this.players.length;
}
}
|
JavaScript
| 0 |
@@ -237,16 +237,18 @@
ype
-%5Bp
+%7B%5BP
layer%5D
+%7D
%0A
@@ -288,172 +288,8 @@
%5D;%0A%0A
- /**%0A * An array of currently active cards (in the middle of table)%0A *%0A * @type %5Bstring%5D%0A */%0A this.activeCards = %5B%5D;%0A%0A
@@ -359,32 +359,33 @@
* @type
+%7B
%5Bstring%5D
%0A */
@@ -364,32 +364,33 @@
@type %7B%5Bstring%5D
+%7D
%0A */%0A
@@ -509,24 +509,25 @@
* @type
+%7B
%5Bstring%5D
%0A
@@ -518,16 +518,17 @@
%5Bstring%5D
+%7D
%0A
@@ -1225,16 +1225,25 @@
* @param
+ %7Bstring%7D
card%0A
|
90a5b964806092a68237ab237fac533fbd56bfef
|
Add descriptions to transformation/transformers/es6/arrow-functions
|
src/babel/transformation/transformers/es6/arrow-functions.js
|
src/babel/transformation/transformers/es6/arrow-functions.js
|
/**
* [Please add a description.]
*/
export var visitor = {
/**
* [Please add a description.]
*/
ArrowFunctionExpression(node) {
this.ensureBlock();
node.expression = false;
node.type = "FunctionExpression";
node.shadow = true;
}
};
|
JavaScript
| 0 |
@@ -4,35 +4,216 @@
%0A *
-%5BPlease add a description.%5D
+Turn arrow functions into normal functions.%0A *%0A * @example%0A *%0A * **In**%0A *%0A * %60%60%60javascript%0A * arr.map(x =%3E x * x);%0A * %60%60%60%0A *%0A * **Out**%0A *%0A * %60%60%60javascript%0A * arr.map(function (x) %7B%0A * return x * x;%0A * %7D);
%0A */
@@ -253,35 +253,69 @@
*
-%5BPlease add a descrip
+Look for arrow functions and turn them into normal func
tion
+s
.
-%5D
%0A
|
5fc59e2f390e6dbe4f34fa483108a25d5a5478a3
|
Change back button in profile of other users to use window.history.back() instead of dispatching
|
components/Profile.js
|
components/Profile.js
|
import React from 'react'
import Header from './Header'
import Nav from './Nav'
import logout from '../api/logout'
function Profile ({state, dispatch}) {
function goBack (e) {
e.preventDefault()
dispatch({type: 'CHANGE_PAGE', payload: '/flops'})
}
if(state.currentUser.userId === state.currentViewUserId) {
return (
<div>
<Header />
<div className="buttonGroup dashboardButtons">
<div className='btn clickable' onClick={() => dispatch({type: 'CHANGE_PAGE', payload: `/profile/${state.currentUser.username}/edit`})}>Edit Profile</div>
<div className='btn clickable' onClick={() => logout(dispatch)}>Logout</div>
</div>
<h3>Your Profile</h3>
<div className='profile'>
<h1 >{state.currentUser.name}</h1>
<img className='profilePic' src={state.currentUser.profilePic} />
<div className='profileInfo'>
<p>{state.currentUser.bio}</p>
</div>
</div>
{SortFlops(state, dispatch, state.currentUser.userId)}
<div className='clear' />
<Nav state={state} dispatch={dispatch} />
</div>
)
} else {
return (
<div>
<Header />
<div className="dashboardButtons buttonGroup">
<div className="btn clickable" onClick={goBack}>back</div>
</div>
<h3>User Profile</h3>
{User(state, dispatch)}
{SortFlops(state, dispatch, state.currentViewUserId)}
<Nav dispatch={dispatch} state={state}/>
</div>
)
}
}
function User (state, dispatch) {
return state.allUsers
.filter(user => {
return user.userId == state.currentViewUserId
})
.map(user => {
return (
<div key={user.userId}>
<h1>{user.username}</h1>
<img className="profilePic" src={user.profilePic}/>
</div>
)
})
}
function SortFlops (state, dispatch, userId) {
const {flops, lifestyles} = state
return lifestyles
.map(lifestyle => {
return flops
.filter(flop => flop.lifestyleId === lifestyle.lifestyleId)
.sort((a, b) => (b.upvotes - b.downvotes) - (a.upvotes - a.downvotes))
.map((flop, index) => {
flop.rank = index + 1
if (flop.userId === userId) {
return (
<div className='flopContainer' key={flop.flopId}>
<div className='flopRank'>
<h2>{flop.rank}</h2>
</div>
{getTitle(flop, lifestyle)}
</div>
)
}
})
})
}
function getTitle (flop, lifestyle) {
return <h2 className='lifestyleTitle'>{lifestyle.title}</h2>
}
module.exports = Profile
|
JavaScript
| 0 |
@@ -198,16 +198,45 @@
lt()%0A
+ window.history.back()%0A //
dispatc
@@ -1565,17 +1565,16 @@
)%0A %7D%0A
-%0A
%7D%0A%0Afunct
|
5401902b422b6f9f41617d694c4805eda28e115f
|
update play.js example
|
example/play.js
|
example/play.js
|
/**
* Example script that retrieves the specified Track through Spotify, then decodes
* the MP3 data through node-lame, and fianally plays the decoded PCM data through
* the speakers using node-speaker.
*/
var Spotify = require('../');
var login = require('../login');
var lame = require('lame');
var Speaker = require('speaker');
var superagent = require('superagent');
var trackUri = process.argv[2] || 'spotify:track:6tdp8sdXrXlPV6AZZN2PE8';
Spotify.login(login.username, login.password, function (err, spotify) {
if (err) throw err;
// first get a "track" instance from the Track URI
spotify.metadata(trackUri, function (err, track) {
if (err) throw err;
spotify.trackUri(track, function (err, res) {
if (err) throw err;
console.log('Playing: %s - %s', track.artist[0].name, track.name);
console.log('MP3 URL: %j', res.uri);
// no need to be connected to Spotify any longer...
spotify.disconnect();
var decoder = new lame.Decoder();
decoder.on('format', function (format) {
decoder.pipe(new Speaker(format));
});
superagent.get(res.uri).pipe(decoder);
});
});
});
|
JavaScript
| 0 |
@@ -374,18 +374,14 @@
');%0A
+%0A
var
-trackU
+u
ri =
@@ -608,22 +608,17 @@
etadata(
-trackU
+u
ri, func
@@ -657,24 +657,25 @@
throw err;%0A
+%0A
spotify.
@@ -952,88 +952,31 @@
-var decoder = new lame.Decoder();%0A decoder.on('format', function (format) %7B
+superagent.get(res.uri)
%0A
@@ -980,23 +980,16 @@
-decoder
.pipe(ne
@@ -994,78 +994,51 @@
new
-Speaker(format
+lame.Decoder(
))
-;
%0A
-%7D);%0A superagent.get(res.uri).pipe(decoder
+ .pipe(new Speaker()
);%0A
|
44aba48abf13cc05b306416cbca40f005e89fc26
|
Use more specific selector to handle anomalies reports sections
|
common/reffy.js
|
common/reffy.js
|
window.onload = function () {
const $ = (el, selector) =>
Array.prototype.slice.call(el.querySelectorAll(selector), 0);
const toggleSubSections = spec =>
$(spec, 'h2 ~ section').forEach(
section => section.hasAttribute('hidden') ?
section.removeAttribute('hidden') :
section.setAttribute('hidden', '')
);
// Collapse spec sections by default
let total = 0;
let totalOk = 0;
let totalError = 0;
let totalWarning = 0;
$(document, '[data-spec]').forEach(spec => {
total += 1;
const title = spec.querySelector('h2');
// Compute the set of anomaly icons to display
let flags = [];
if (spec.hasAttribute('data-ok')) {
flags.push('<i class="fa fa-check fa-lg ok" ' +
'title="Spec looks good"></i>');
totalOk += 1;
}
else if (spec.hasAttribute('data-error')) {
flags.push('<i class="fa fa-exclamation-triangle fa-lg error" ' +
'title="Spec could not be parsed"></i>');
totalError += 1;
}
else {
if (spec.hasAttribute('data-noNormativeRefs')) {
flags.push('<span class="fa-stack" ' +
'title="No normative references found in the spec">' +
'<i class="fa fa-list fa-stack-1x"></i>' +
'<i class="fa fa-ban fa-stack-2x warn"></i>' +
'</span>');
}
if (spec.hasAttribute('data-hasInvalidIdl') ||
spec.hasAttribute('data-hasObsoleteIdl')) {
flags.push('<i class="fa fa-bug fa-lg error" ' +
'title="Invalid or obsolete IDL content found"></i>');
}
if (spec.hasAttribute('data-unknownIdlNames') ||
spec.hasAttribute('data-redefinedIdlNames')) {
flags.push('<i class="fa fa-code fa-lg warn" ' +
'title="Spec uses unknown IDL terms or re-defines terms defined elsewhere"></i>');
}
if (spec.hasAttribute('data-noRefToWebIDL') ||
spec.hasAttribute('data-missingWebIdlRef') ||
spec.hasAttribute('data-missingLinkRef') ||
spec.hasAttribute('data-noEdDraft')) {
flags.push('<i class="fa fa-chain-broken fa-lg error" ' +
'title="Some references are missing"></i>');
}
if (spec.hasAttribute('data-inconsistentRef')) {
flags.push('<i class="fa fa-link fa-lg warn" ' +
'title="References exist but used inconsistently"></i>');
}
totalWarning += 1;
}
// Update the spec title
title.innerHTML = '<a aria-expanded="false" aria-haspopup="true" href="#" class="pure-g">' +
'<div class="pure-u-sm-4-5 pure-u-lg-2-3 pure-u-xl-3-5">' +
'<i class="fa fa-caret-right"></i> ' +
'<span>' + title.innerHTML + '</span>' +
'</div> ' +
'<div class="pure-u-sm-1-5 pure-u-lg-1-3 pure-u-xl-2-5">' +
flags.join(' ') +
'</div></a>';
// Collapse the section by default
toggleSubSections(spec);
// Expand/Collapse the section on click
const link = spec.querySelector('h2 a');
link.onclick = () => {
toggleSubSections(spec);
const caret = title.querySelector('i');
if (link.getAttribute('aria-expanded') === 'false') {
link.setAttribute('aria-expanded', 'true');
caret.setAttribute('class', 'fa fa-caret-down');
window.history.pushState({}, '', '#' + spec.getAttribute('id'));
}
else {
link.setAttribute('aria-expanded', 'false');
caret.setAttribute('class', 'fa fa-caret-right');
}
return false;
};
});
// Render summary bar
// (making sure narrow columns remain wide enough on narrow screens)
const barOk = document.getElementById('barOk');
const barWarning = document.getElementById('barWarning');
const barError = document.getElementById('barError');
barOk.innerHTML = totalOk;
barOk.title = `Correct specs: ${totalOk}`;
if (totalOk === 0) {
barOk.style.display = 'none';
}
else {
barOk.style.flex = (totalOk < 10) ?
`${totalOk} 0 1em` :
`${totalOk} ${totalOk} auto`;
}
barWarning.innerHTML = totalWarning;
barWarning.title = `Specs with warnings: ${totalWarning}`;
if (totalWarning === 0) {
barWarning.style.display = 'none';
}
else {
barWarning.style.flex = (totalWarning < 10) ?
`${totalWarning} 0 1em` :
`${totalWarning} ${totalWarning} auto`;
}
barError.innerHTML = totalError;
barError.title = `Specs for which analysis failed: ${totalError}`;
if (totalError === 0) {
barError.style.display = 'none';
}
else {
barError.style.flex = (totalError < 10) ?
`${totalError} 0 1em` :
`${totalError} ${totalError} auto`;
}
document.getElementById('summary').style.display = 'flex';
// Display the number of specifications in the report
document.getElementById('stats').innerHTML = 'This report contains ' +
'<strong>' + total + '</strong> specifications.';
// Bind to spec filter
document.getElementById('submit').onclick = () => {
const filter = document.getElementById('filter').value;
let count = 0;
$(document, '[data-spec]').forEach(spec => {
const hide = (filter !== 'all') &&
!filter.split('|').find(anomaly => spec.hasAttribute('data-' + anomaly));
if (hide) {
spec.setAttribute('hidden', '');
}
else {
count += 1;
spec.removeAttribute('hidden');
}
});
if (filter === 'all') {
document.getElementById('stats').innerHTML = 'This report contains ' +
'<strong>' + total + '</strong> specifications.';
}
else {
document.getElementById('stats').innerHTML = 'This report contains ' +
'<strong>' + total + '</strong> specifications. ' +
'<strong>' + count + '</strong> specification' +
((count > 1) ? 's match' : ' matches') +
' the selected filter.';
}
return false;
};
// Force browser to re-scroll to requested position
if (document.location.hash) {
const spec = document.getElementById(document.location.hash.substring(1));
spec.querySelector('h2 a').click();
setTimeout(() => spec.scrollIntoView(), 0);
}
};
|
JavaScript
| 0 |
@@ -466,32 +466,39 @@
%0A $(document, '
+section
%5Bdata-spec%5D').fo
@@ -5017,16 +5017,23 @@
ument, '
+section
%5Bdata-sp
|
3b9047be0f3587a4163bb2c6fbf8467961d4371e
|
Fix fira code download
|
addons/xterm-addon-ligatures/bin/download-fonts.js
|
addons/xterm-addon-ligatures/bin/download-fonts.js
|
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const axios = require('axios').default;
const mkdirp = require('mkdirp');
const yauzl = require('yauzl');
const urls = {
fira: 'https://github.com/tonsky/FiraCode/raw/master/distr/otf/FiraCode-Regular.otf',
iosevka: 'https://github.com/be5invis/Iosevka/releases/download/v1.14.3/01-iosevka-1.14.3.zip'
};
const writeFile = util.promisify(fs.writeFile);
const fontsFolder = path.join(__dirname, '../fonts');
async function download() {
await mkdirp(fontsFolder);
await downloadFiraCode();
await downloadIosevka();
console.log('Loaded all fonts for testing')
}
async function downloadFiraCode() {
const file = path.join(fontsFolder, 'firaCode.otf');
if (await util.promisify(fs.exists)(file)) {
console.log('Fira Code already loaded');
} else {
console.log('Downloading Fira Code...');
await writeFile(
file,
(await axios.get(urls.fira, { responseType: 'arraybuffer' })).data
);
}
}
async function downloadIosevka() {
const file = path.join(fontsFolder, 'iosevka.ttf');
if (await util.promisify(fs.exists)(file)) {
console.log('Iosevka already loaded');
} else {
console.log('Downloading Iosevka...');
const iosevkaContents = (await axios.get(urls.iosevka, { responseType: 'arraybuffer' })).data;
const iosevkaZipfile = await util.promisify(yauzl.fromBuffer)(iosevkaContents);
await new Promise((resolve, reject) => {
iosevkaZipfile.on('entry', entry => {
if (entry.fileName === 'ttf/iosevka-regular.ttf') {
iosevkaZipfile.openReadStream(entry, (err, stream) => {
if (err) {
return reject(err);
}
const writeStream = fs.createWriteStream(file);
stream.pipe(writeStream);
writeStream.on('close', () => resolve());
});
}
});
});
}
}
download();
process.on('unhandledRejection', e => {
console.error(e);
process.exit(1);
});
|
JavaScript
| 0 |
@@ -344,14 +344,48 @@
raw/
-master
+d42e7276fa925e5f82748f3ec9ea429736611b48
/dis
|
fc1d88d5c3b34dace64441ea9c091fdb99ed261b
|
Add buffer byte length
|
src/Buffer.js
|
src/Buffer.js
|
/**
* Используется для хранения и подготовки данных для передачи в атрибуты шейдера
*
* @param {TypedArray | ArrayBuffer} data Данные для передачи в видеокарту
* @param {?BufferBindOptions} options Параметры передачи буфера в видеокарту,
* могут быть переопределены из {@link BufferChannel}
*/
class Buffer {
constructor(data, options) {
this._data = data;
/**
* Тип буфера. Буфер может использоваться для передачи массива данных,
* так и для передачи индексов элементов из данных.
* @type {Buffer.ArrayBuffer | Buffer.ElementArrayBuffer}
*/
this.type = Buffer.ArrayBuffer;
/**
* Указывает, как часто данные буфера будут изменяться.
* @type {Buffer.StaticDraw | Buffer.DynamicDraw}
*/
this.drawType = Buffer.StaticDraw;
/**
* Параметры для связывания буфера
* @type {BufferBindOptions}
* @ignore
*/
this.options = Object.assign({}, Buffer.defaultOptions, options);
/**
* Исходный WebGL буфер
* @type {?WebGLBuffer}
* @ignore
*/
this._glBuffer = null;
}
/**
* Связывает данные с контекстом WebGL.
*
* В случае Buffer.ArrayBuffer связывает с атрибутами шейдера.
* А в случае Buffer.ElementArrayBuffer связывает массив индексов.
*
* Если используется первый раз, добавляет данные в контекст WebGL.
*
* @param {WebGLRenderingContext} gl
* @param {?Number} location Положение аттрибута для связывания данных с переменными в шейдере
* @param {?BufferBindOptions} options Параметры передаваемые в функцию vertexAttribPointer, если их нет,
* то используются параметры конкретного буфера. Параметры должны быть переданы все.
*/
bind(gl, location, options) {
if (!this._glBuffer) {
this._prepare(gl);
}
if (this.type === Buffer.ArrayBuffer) {
gl.bindBuffer(gl.ARRAY_BUFFER, this._glBuffer);
options = options || this.options;
gl.vertexAttribPointer(location, options.itemSize, this._toGlParam(gl, options.dataType),
options.normalized, options.stride, options.offset);
} else if (this.type === Buffer.ElementArrayBuffer) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
}
return this;
}
/**
* Удаляет данные из контекста WebGL.
* @param {WebGLRenderingContext} gl
*/
remove(gl) {
this._unprepare(gl);
return this;
}
/**
* Заменяет часть буфера новыми данными и отправляет их в видеокарту
* @param {WebGLRenderingContext} gl
* @param {Number} index Индекс, с которого начать замену
* @param {TypedArray} data Новые данные
*/
subData(gl, index, data) {
gl.bindBuffer(this._toGlParam(gl, this.type), this._glBuffer);
gl.bufferSubData(this._toGlParam(gl, this.type), index * this.itemSize, data);
return this;
}
/**
* Кладёт данные в видеокарту
* @param {WebGLRenderingContext} gl
* @ignore
*/
_prepare(gl) {
this._glBuffer = gl.createBuffer();
gl.bindBuffer(this._toGlParam(gl, this.type), this._glBuffer);
gl.bufferData(this._toGlParam(gl, this.type), this._data, this._toGlParam(gl, this.drawType));
this._data = null;
}
/**
* Удаляет данные из видеокарты
* @param {WebGLRenderingContext} gl
* @ignore
*/
_unprepare(gl) {
if (this._glBuffer) {
gl.deleteBuffer(this._glBuffer);
this._glBuffer = null;
}
}
/**
* Преобразовывает параметры буфера в параметры WebGL
* @param {WebGLRenderingContext} gl
* @param {Buffer.ArrayBuffer | Buffer.ElementArrayBuffer} param
* @ignore
*/
_toGlParam(gl, param) {
if (param === Buffer.ArrayBuffer) { return gl.ARRAY_BUFFER; }
if (param === Buffer.ElementArrayBuffer) { return gl.ELEMENT_ARRAY_BUFFER; }
if (param === Buffer.StaticDraw) { return gl.STATIC_DRAW; }
if (param === Buffer.DynamicDraw) { return gl.DYNAMIC_DRAW; }
if (param === Buffer.Byte) { return gl.BYTE; }
if (param === Buffer.Short) { return gl.SHORT; }
if (param === Buffer.Int) { return gl.INT; }
if (param === Buffer.Float) { return gl.FLOAT; }
if (param === Buffer.UnsignedByte) { return gl.UNSIGNED_BYTE; }
if (param === Buffer.UnsignedShort) { return gl.UNSIGNED_SHORT; }
if (param === Buffer.UnsignedInt) { return gl.UNSIGNED_INT; }
}
}
Buffer.ArrayBuffer = 1;
Buffer.ElementArrayBuffer = 2;
Buffer.StaticDraw = 10;
Buffer.DynamicDraw = 11;
Buffer.Float = 20;
Buffer.UnsignedByte = 21;
Buffer.UnsignedShort = 22;
Buffer.UnsignedInt = 23;
Buffer.Byte = 24;
Buffer.Short = 25;
Buffer.Int = 26;
Buffer.defaultOptions = {
itemSize: 3,
dataType: Buffer.Float,
stride: 0,
offset: 0,
normalized: false
};
export default Buffer;
/**
* Параметры передаваемые в функцию vertexAttribPointer.
*
* @typedef {Object} BufferBindOptions
* @property {Number} itemSize Размерность элементов в буфере
* @property {Buffer.Float | Buffer.UnsignedByte} dataType Тип данных в буфере
* @property {Boolean} normalized Используется для целочисленных типов. Если выставлен в true, то
* значения имеющие тип BYTE от -128 до 128 будут переведены от -1.0 до 1.0.
* @property {Number} stride
* @property {Number} offset
*/
|
JavaScript
| 0.000048 |
@@ -369,16 +369,153 @@
data;%0A%0A
+ /**%0A * %D0%A0%D0%B0%D0%B7%D0%BC%D0%B5%D1%80 %D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85 %D0%B2 %D0%B1%D1%83%D1%84%D0%B5%D1%80%D0%B5 %D0%B2 %D0%B1%D0%B0%D0%B9%D1%82%D0%B0%D1%85%0A * @type %7BNumber%7D%0A */%0A this.byteLength = data.byteLength;%0A%0A
|
4fda7b75fa11cc1a7654beea998be4af08225990
|
Make code more readable
|
examples/api.js
|
examples/api.js
|
#!/usr/bin/env node
/* eslint-disable fp/no-unused-expression, fp/no-nil, fp/no-mutation, no-console */
const Chance = require('chance');
const R = require('ramda');
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router();
const middlewares = jsonServer.defaults();
const chance = new Chance();
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares);
// Add custom routes before JSON Server router
server.get('/multibar-line', (req, res) => {
const range = length => Array.apply(undefined, {length: length});
const INTERVAL = 5;
const NOW = new Date();
const createTimeSerie = R.curry((valueFunc, dt) => [dt, valueFunc()]);
const createTimeRandomValueSerie = createTimeSerie(() => chance.floating({min: 0, max: 10**5}));
const addSecond = R.curry((num, dt) => new Date(new Date(dt).setSeconds(new Date(dt).getSeconds()+num)));
const plusSecondInterval = addSecond(INTERVAL);
const prevDate = prevArr => prevArr.slice(-1)[0][0];
const valuesReducer =
R.reduce((prev) => [...prev, createTimeRandomValueSerie(plusSecondInterval(prevDate(prev)))]);
const data = [
{
key: 'Cost',
bar: true,
values: valuesReducer([createTimeRandomValueSerie(addSecond(-11 * INTERVAL, NOW))], range(10))
},
{
key: 'Forecast',
bar: true,
values: valuesReducer([createTimeRandomValueSerie(NOW)], range(4))
},
{
key: 'Budget',
values: valuesReducer()
}
];
res.jsonp(data);
});
// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
if (req.method === 'POST') {
req.body.createdAt = Date.now();
}
// Continue to JSON Server router
next();
});
// Use default router
server.use(router);
server.listen(3000, () => {
console.log('JSON Server is running');
});
|
JavaScript
| 0.003321 |
@@ -773,16 +773,21 @@
meSerie(
+%0A
() =%3E ch
@@ -821,16 +821,19 @@
10**5%7D)
+%0A
);%0A%0A co
@@ -845,16 +845,17 @@
ddSecond
+s
= R.cur
@@ -857,16 +857,21 @@
R.curry(
+%0A
(num, dt
@@ -939,16 +939,19 @@
()+num))
+%0A
);%0A con
@@ -953,26 +953,68 @@
const
-plusSecond
+addInterval = addSeconds(INTERVAL);%0A const negative
Interval
@@ -1025,25 +1025,32 @@
ddSecond
-(
+s(-11 *
INTERVAL
);%0A con
@@ -1033,32 +1033,37 @@
s(-11 * INTERVAL
+, NOW
);%0A const prevD
@@ -1192,17 +1192,10 @@
rie(
-plusSecon
+ad
dInt
@@ -1340,38 +1340,24 @@
rie(
-addSecond(-11 * INTERVAL, NOW)
+negativeInterval
)%5D,
|
2dfc6d71438f900871c6224a2a04b78341794923
|
Add stateless functional component and web component stories
|
gemini/index.js
|
gemini/index.js
|
gemini.suite('CSS component', (suite) => {
suite.setUrl('/')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
|
JavaScript
| 0.000001 |
@@ -53,16 +53,493 @@
etUrl('/
+?selectedKind=CSS%2520component&selectedStory=default')%0A .setCaptureElements('#storybook-preview-iframe')%0A .capture('plain');%0A%7D);%0A%0Agemini.suite('Stateless functional component', (suite) =%3E %7B%0A suite.setUrl('/?selectedKind=Stateless%2520functional%2520component&selectedStory=default')%0A .setCaptureElements('#storybook-preview-iframe')%0A .capture('plain');%0A%7D);%0A%0Agemini.suite('Web Component', (suite) =%3E %7B%0A suite.setUrl('/?selectedKind=Web%2520component&selectedStory=default
')%0A .
|
1f56a8384e27049d1d005bf0d616cc5c68e2e06f
|
Remove console.log for debugging
|
app/assets/javascripts/sharelink.js
|
app/assets/javascripts/sharelink.js
|
var ShareQuotes = {
init: function() {
$('.quotes').on('click', '.share-quote', this.showUrl);
$('.container').on('click', this.removeShare);
$('.show-quote').on('click', '.share-quote', this.showUrlSinglePage);
},
showUrl: function(e) {
e.preventDefault();
var index = $(e.target).closest('.quote').index();
var quoteId = $(e.target).closest('.quote').attr('id');
var hostName = 'http://' + window.location.hostname;
var localhost = '';
// so the URL succeeds for testing and development
if ( hostName.match(/localhost/) ) {
localhost = ':3000';
}
var url = hostName + localhost + '/quotes/' + quoteId;
var html = "<div class='share-link'><input type='text' value='" + url + "'/></div>";
$('.quotes').children(':eq(' + index + ')').after(html);
},
showUrlSinglePage: function(e) {
e.preventDefault();
var index = $(e.target).closest('.quote').index();
var quoteId = $(e.target).closest('.quote').attr('id');
var hostName = 'http://' + window.location.hostname;
var localhost = '';
if ( hostName.match(/localhost/) ) {
localhost = ':3000';
}
var url = hostName + localhost + '/quotes/' + quoteId;
var html = "<div class='share-link'><input type='text' value='" + url + "'/></div>";
console.log(url);
console.log($('.show-quote').children);
console.log(index);
$('.show-quote').children(':eq(' + index + ')').after(html);
},
removeShare: function(e) {
if ($(e.target).attr('class') != 'share-quote' &&
!($(e.target).is('input'))) {
$('.share-link').remove();
}
}
};
$(document).ready(function() {
ShareQuotes.init();
});
|
JavaScript
| 0.000003 |
@@ -1307,98 +1307,8 @@
%0A
- console.log(url);%0A console.log($('.show-quote').children);%0A console.log(index);%0A
|
8e3a24d1d8607e41f9d60a44c5d88712effe46b8
|
Fix typo in score
|
static/src/modules/main/MainListCtrl.js
|
static/src/modules/main/MainListCtrl.js
|
/*@ngInject*/
module.exports = function ($scope, $rootScope, $stateParams, Metric, Config, Project, DateTimes) {
var chart = require('./chart');
var cubism;
var initOpt;
$rootScope.currentMain = true;
$scope.dateTimes = DateTimes;
$scope.projectId = $stateParams.project;
$scope.limitList = [{
label: 'Limit1',
val: 1
}, {
label: 'Limit 30',
val: 30
}, {
label: 'Limit 50',
val: 50
}, {
label: 'Limit 100',
val: 100
}, {
label: 'Limit 500',
val: 500
}, {
label: 'Limit 1000',
val: 1000
}];
$scope.sortList = [{
label: 'Trending Up',
val: 0
}, {
label: 'Trending Down',
val: 1
}];
$scope.typeList = [{
label: 'value',
val: 'v'
}, {
label: 'score',
val: 'm'
}];
$scope.autoComplete = {
searchText: ''
};
initOpt = {
project: $stateParams.project,
pattern: $stateParams.pattern,
datetime: DateTimes[0].seconds,
limit: $scope.limitList[2].val,
sort: $scope.sortList[0].val,
type: $scope.typeList[0].val,
status: false
};
$scope.filter = angular.copy(initOpt);
$scope.toggleCubism = function () {
$scope.filter.status = !$scope.filter.status;
if (!$scope.filter.status) {
buildCubism();
} else {
cubism.stop();
}
};
$scope.restart = function () {
$scope.filter = angular.copy(initOpt);
buildCubism();
};
$scope.searchPattern = function() {
$scope.filter.project = '';
$scope.autoComplete.searchText = '';
buildCubism();
};
$scope.searchProject = function(project) {
$scope.filter.project = project.id;
$scope.filter.pattern = '';
buildCubism();
};
$scope.$on('$destroy', function () {
$rootScope.currentMain = false;
});
function loadData() {
Project.getAllProjects().$promise
.then(function (res) {
var projectId = parseInt($stateParams.project);
$scope.projects = res;
if (projectId) {
$scope.projects.forEach(function(el) {
if (el.id === projectId) {
$scope.autoComplete.searchText = el.name;
$scope.project = el;
setTitle();
}
});
}
});
Config.getInterval().$promise
.then(function (res) {
$scope.filter.interval = res.interval;
setIntervalAndRunNow(buildCubism, 10 * 60 * 1000);
watchAll();
});
}
/**
* watch filter.
*/
function watchAll() {
$scope.$watchGroup(['filter.datetime', 'filter.limit', 'filter.sort', 'filter.type'], function () {
buildCubism();
});
}
function buildCubism() {
var params = {
limit: $scope.filter.limit,
sort: $scope.filter.sort,
};
if ($scope.filter.project) {
params.project = $scope.filter.project;
} else {
params.pattern = $scope.filter.pattern;
}
chart.remove();
setTitle();
cubism = chart.init({
selector: '#cubism-wrap',
serverDelay: $scope.filter.datetime * 1000,
step: $scope.filter.interval * 1000,
stop: false,
type: $scope.filter.type
});
Metric.getMetricIndexes(params).$promise
.then(function (res) {
plot(res);
});
}
function setTitle() {
if ($scope.filter.project && $scope.project) {
$scope.title = 'Project: ' + $scope.project.name;
$scope.showLink = true;
return;
}
$scope.showLink = false;
if ($scope.filter.pattern) {
$scope.title = 'Pattern: ' + $scope.filter.pattern;
return;
}
$scope.title = 'Pattern: *';
}
/**
* Plot.
*/
function plot(data) {
var name, i, metrics = [];
for (i = 0; i < data.length; i++) {
name = data[i].name;
// TODO
// metrics.push(feed(name, self.refreshTitle));
metrics.push(feed(name, function () {}));
}
return chart.plot(metrics);
}
/**
* Feed metric.
* @param {String} name
* @param {Function} cb // function(data)
* @return {Metric}
*/
function feed(name) {
return chart.metric(function (start, stop, step, callback) {
var values = [],
i = 0;
// cast to timestamp from date
start = parseInt((+start - $scope.filter.datetime) / 1000);
stop = parseInt((+stop - $scope.filter.datetime) / 1000);
step = parseInt(+step / 1000);
// parameters to pull data
var params = {
name: name,
type: $scope.filter.type,
start: start,
stop: stop
};
// request data and call `callback` with values
// data schema: {name: {String}, times: {Array}, vals: {Array}}
Metric.getMetricValues(params, function (data) {
// the timestamps from statsd DONT have exactly steps `10`
var len = data.length;
while (start < stop && i < len) {
while (start < data[i].stamp) {
start += step;
if ($scope.filter.type === 'v') {
values.push(start > data[i].stamp ? data[i].value : 0);
} else {
values.push(start > data[i].stamp ? data[i].score : 0);
}
}
if ($scope.filter.type === 'v') {
values.push(data[i++].value);
} else {
values.push(data[i++].core);
}
start += step;
}
callback(null, values);
});
}, name);
}
function setIntervalAndRunNow(fn, ms) {
fn();
return setInterval(fn, ms);
}
loadData();
};
|
JavaScript
| 0.999982 |
@@ -5281,16 +5281,17 @@
ta%5Bi++%5D.
+s
core);%0A
|
5b75796bc51c58abda410941511aa9fc4bb40751
|
fix move.style bug
|
src/Cursor.js
|
src/Cursor.js
|
//
// Copyright (c) 2016 Satoshi Nakajima (https://github.com/snakajima)
// License: The MIT License
//
import React, { Component } from 'react';
import App from './App';
import Page from './Page';
import Selection from './Selection';
import DragContext from './DragContext';
import createStore from './SimpleRedux';
class Cursor extends Component {
constructor() {
super();
window.cursor.setApplication(this);
this.onDrop = this.onDrop.bind(this);
this.onDragOver = this.onDragOver.bind(this);
}
static reducer(_state, action) {
if (typeof _state === "undefined") {
return {};
}
var state = Object.assign({}, window.store.getState());
switch(action.type) {
case 'update':
break;
case 'setSelectionStyle':
if (state.selection) {
state.selection = {ids:state.selection.ids, style:action.style};
}
break;
default:
console.log('Cursor:unknown action', action.type);
break;
}
return state;
}
onDrop(e) {
//console.log('Cursor:onDrop');
const context = DragContext.getContext();
const scale = this.scale;
if (this.state.pageIndex >= 0) {
window.store.dispatch({
type:'movePageElement', pageIndex:context.pageIndex,
handle:context.handle,
id:context.id, scale:scale, index:context.index, params:context.params,
dx:e.clientX-context.x, dy:e.clientY-context.y});
} else {
window.store.dispatch({
type:'moveSceneElement', id:context.id, index:context.index,
handle:context.handle, params:context.params,
scale:scale,
dx:e.clientX-context.x, dy:e.clientY-context.y});
}
}
onDragOver(e) {
//console.log('Cursor:onDragOver');
if (DragContext.getContext().pageIndex === this.state.pageIndex) {
e.preventDefault();
}
}
render() {
const selection = this.state.selection || {ids:new Set()}
if (selection.ids.size === 0) {
return <div></div>;
}
const { leftWidth, rightWidth } = App.windowSize();
const elements = (this.state.pageIndex >= 0) ?
Page.applyTransform(this.state.elements, this.state.pages[this.state.pageIndex])
: this.state.elements;
//console.log('Cursor:elements', JSON.stringify(elements));
const margin = this.state.margin || 0;
const w = rightWidth - margin * 2;
const scale = w / this.state.dimension.width;
this.scale = scale; // HACK: pass this value to onDrop (is this a bad practice?)
const height = this.state.dimension.height * scale + margin * 2;
const context = DragContext.getContext();
//console.log('Cursor:more', margin, w, scale, JSON.stringify(selection));
var style = {};
if (context.cursor) {
style.width = rightWidth;
style.height = height;
}
var selectedElements = [];
var cursors = elements.reduce((selections, element, index)=>{
if (selection.ids.has(element.id)) {
selectedElements.push(element);
selections.push(<Selection key={index+1000} index={index}
pageIndex={this.state.pageIndex}
element={element} main={true}
selectionStyle={this.state.selection.style}
scale={scale} />);
}
return selections;
}, []);
const firstElement = selectedElements[0];
return (
<div style={{position:'absolute', top:28, left:leftWidth + 2}}>
<div className='frameCursor' style={style} onDrop={this.onDrop} onDragOver={this.onDragOver}>
<div style={{position:'absolute', left:margin, top:margin}}>
{cursors}
</div>
</div>
<div className='frameProperties'
style={{position:'absolute', top:height+2, width:rightWidth}}>
<div className='frameProperty'>Opacity:{firstElement.opacity || 1}</div>
<div className='frameProperty'>Rotation:{(this.state.selection.style || firstElement).rotate || 0}</div>
</div>
</div>
)
}
}
window.cursor = createStore(Cursor.reducer);
export default Cursor;
|
JavaScript
| 0.000001 |
@@ -4413,16 +4413,30 @@
style %7C%7C
+ %7B%7D).rotate %7C%7C
firstEl
@@ -4440,17 +4440,16 @@
tElement
-)
.rotate
|
ae86807e2294648b1641ee67455072a5f04e3163
|
Update DocTyp.js
|
src/DocTyp.js
|
src/DocTyp.js
|
/*
Convert the contents of an HTML DOM element into a
styled text document for an easier reading
experience or to bring out certain features in the
document. You can create your own README document.
if (redistribute == true) {
return credit;
}
--------------------------------------------------
@DocTyp
@author: Alexander Hovy
@param:
exports - Contains all the public variables and functions of the module.
element - The HTML DOM element that will be Docified.
theme - You can optionally set the style to Dark or Light.
doc - The elements text that will be Docified.
@credit:
Prism, Highlight
*/
var DocTyp = (function(exports) {
/*============================================================
===========================Variable===========================
============================================================*/
var prefix = 'doctyp-',
scheme;
var header = {
'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
};
var style = {
'bold': {pattern: /\*/gm, regex: /\*{1,}(.*?)\*{1,}/gm},
'italic': {pattern: /\//gm, regex: /\/{1,}(.*?)\/{1,}/gm},
'underline': {pattern: /\_/gm, regex: /\_{1,}(.*?)\_{1,}/gm},
'strike': {pattern: /\~/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
'highlight': {pattern: /\=/gm, regex: /\={1,}(.*?)\={1,}/gm}
};
var rule = {
'rule-solid': {pattern: /\-/gm, regex: /\-{4,}/gm},
'rule-dash': {pattern: /\./gm, regex: /\.{4,}/gm}
};
var block = {
'code': {pattern: /\|/gm, regex: /\|{1,}(.*?)\|{1,}/gm},
'pre-external': {pattern: /(\`|\[(.*?)\])/gm, regex: /(\[(.*?)\|(.*?)\])\`{1,}([\s\S]*?)\`{1,}/gm},
'pre': {pattern: /\`/gm, regex: /\`{1,}([\s\S]*?)\`{1,}/gm},
'quote': {pattern: /[\{\}]/gm, regex: /\{{1,}([\s\S]*?)\}{1,}/gm}
};
var list = {
'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
};
var link = {
'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
};
/*============================================================
============================Private===========================
============================================================*/
function LoadScript(url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://doctyp.github.io/src/' + url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function LoadStyle(url) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'https://doctyp.github.io/src/' + url;
link.media = 'none';
link.onload = function() {
if (media != 'all') {
link.media = 'all';
}
};
document.getElementsByTagName('head')[0].appendChild(link);
}
//Processing
function Header(doc) {
for (key in header) {
doc = doc.replace(header[key].regex, function(match) {
var temp = Prepare(match).replace(header[key].pattern, '');
return '<span class="' + prefix + key + '">' + temp + '</span>';
});
}
return doc;
}
function Style(doc) {
for (key in style) {
doc = doc.replace(style[key].regex, function(match) {
var temp = Prepare(match).replace(style[key].pattern, '');
return '<span class="' + prefix + key + '">' + temp + '</span>';
});
}
return doc;
}
function Rule(doc) {
for (key in rule) {
doc = doc.replace(rule[key].regex, function(match) {
return '<hr class="' + prefix + key + '"/>';
});
}
return doc;
}
function Block(doc) {
for (key in block) {
doc = doc.replace(block[key].regex, function(match) {
var temp;
if (key != 'pre-external') {
temp = Prepare(match).replace(block[key].pattern, '');
}
if (key == 'code') {
return '<code class="' + prefix + key + '">' + Trim(temp) + '</code>';
} else if (key == 'pre-external') {
var extra = Prepare(match).replace(/(\[|\]|\`([\s\S]*?)\`)/gm, ''),
language = extra.split('|')[0].toLowerCase(),
url = 'Syntax/' + extra.split('|')[1].toLowerCase();
temp = Prepare(match).replace(block[key].pattern, '');
LoadScript(url + '/script.js');
LoadStyle(url + '/' + scheme + '.css');
return '<pre class="' + prefix + key + ' language-' + language + ' ' + language + '"><code class="language-' + language + ' ' + language + '">' + Trim(temp) + '</code></pre>';
} else if (key == 'pre') {
return '<pre class="' + prefix + key + ' nohighlight language-none"><code class="nohighlight language-none">' + Trim(temp) + '</code></pre>';
} else {
return '<span class="' + prefix + key + '">' + Trim(temp) + '</span>';
}
});
}
return doc;
}
function List(doc) {
return doc;
}
function Link(doc) {
return doc;
}
//Cleaning
function Prepare(doc) {
return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
}
function Trim(doc) {
return doc.replace(/(^\s+|\s+$)/gm, '');
}
function Clean(doc) {
return doc.replace(/\n/gm, '<br/>');
}
/*============================================================
============================Public============================
============================================================*/
exports.Docify = function(element, theme) {
//Check if element is an element
if (element.nodeType && element.nodeType == 1) {
//Check if user is using their own style
if (theme !== undefined) {
scheme = theme.toLowerCase();
LoadStyle('Style/' + theme.toLowerCase() + '.css');
} else {
scheme = 'light';
}
//Cater for older browsers
var doc = element.innerText ? element.innerText : element.textContent;
//Processing
doc = Header(doc);
doc = Style(doc);
doc = Rule(doc);
doc = Block(doc);
doc = List(doc);
doc = Clean(doc);
//Replace text with new text
element.innerHTML = doc;
} else {
throw('The element is not defined or is not a DOM element.');
}
};
/*============================================================
============================Export============================
============================================================*/
return exports;
})({});
|
JavaScript
| 0 |
@@ -3247,16 +3247,21 @@
if (
+link.
media !=
|
510a37c0c6b8e603819a6df19108336ab1b184bd
|
Fix Update organization should return 404
|
api/organizations/routes/updateOrganizationById.js
|
api/organizations/routes/updateOrganizationById.js
|
'use strict';
const Boom = require('boom');
const Organization = require('../model/Organization');
const UpdateOrganizationSchema = require('../validation/updateOrganizationSchema');
const internals = {};
internals.validateObjectId = require('../helpers/validateObjectId');
internals.setFieldsToUpdate = function (fieldName, payload, result) {
if (payload[fieldName]) {
result[fieldName] = payload[fieldName];
}
};
internals.updateOrganizationById = function (id, payload) {
const fieldsToUpdate = {};
internals.setFieldsToUpdate('name', payload, fieldsToUpdate);
internals.setFieldsToUpdate('description', payload, fieldsToUpdate);
internals.setFieldsToUpdate('code', payload, fieldsToUpdate);
internals.setFieldsToUpdate('url', payload, fieldsToUpdate);
internals.setFieldsToUpdate('type', payload, fieldsToUpdate);
if (fieldsToUpdate.type) {
fieldsToUpdate.type = fieldsToUpdate.type.toLowerCase();
}
console.log('fieldsToUpdate', fieldsToUpdate);
return Organization.findByIdAndUpdate(id, {
$set: fieldsToUpdate
}, { new: true })
.then((org) => {
return org;
})
.catch((err) => {
return Boom.badImplementation(err);
});
};
internals.requestHandler = function (request, reply) {
const id = request.params.id;
if (!internals.validateObjectId(id)){
return reply(Boom.badRequest('Must provide a valid organization id'));
}
return reply(internals.updateOrganizationById(id, request.payload));
};
module.exports = {
path: '/api/organizations/{id}',
method: 'PUT',
handler: internals.requestHandler,
config: {
validate: {
payload: UpdateOrganizationSchema
}
}
};
|
JavaScript
| 0.000066 |
@@ -1130,32 +1130,112 @@
hen((org) =%3E %7B%0A%0A
+ if (org === null) %7B%0A return Boom.notFound();%0A %7D%0A
return
|
87befa3afc4bb8314849da973dd1fa2735fdfc65
|
fix a bug
|
start.js
|
start.js
|
'use strict';
// 入口文件
var startFn = require('./index');
// 默认配置
var setting = require('./config').mock;
var start = module.exports = function(d,p,cb){
var dir = d || process.cwd(),
port = p || setting.port;
startFn(dir,port,cb)
}
if(require.main){
startFn(null,8011)
}
|
JavaScript
| 0.000016 |
@@ -100,16 +100,122 @@
.mock;%0A%0A
+var args = process.argv.slice(2),%0A%09port = (args%5B1%5D && /%5E%5Cd+$/.test(args%5B0%5D)) ? parseInt(args%5B0%5D) : 8011;%0A%0A
var star
@@ -253,16 +253,16 @@
,p,cb)%7B%0A
-
%09var dir
@@ -352,16 +352,40 @@
ire.main
+.filename === __filename
)%7B%0A%09star
@@ -397,12 +397,11 @@
ull,
-8011
+port
)%0A%7D
-%0A
|
0d63d37875f184dfce6bb94e2e099ca38cf9479c
|
Remove outdated comment from test-util
|
test/test-util.js
|
test/test-util.js
|
var assert = require('assert');
var path = require('path');
var linter = require('..');
var fs = require('fs');
var postcss = require('postcss');
function getPostcssResult(css, primary, secondary) {
// Call then() at the end to make the LazyResult evaluate
var result = postcss()
.use(linter(primary, secondary))
.process(css);
return result;
}
function fixture(name) {
return fs.readFileSync(path.join(__dirname, 'fixtures', name + '.css'), 'utf8').trim();
}
function assertSuccess(css, primary, secondary) {
var result = getPostcssResult(css, primary, secondary);
assert.equal(result.warnings().length, 0);
}
function assertSingleFailure(css, primary, secondary) {
var result = getPostcssResult(css, primary, secondary);
assert.equal(result.warnings().length, 1);
}
function assertFailure(css, primary, secondary) {
var result = getPostcssResult(css, primary, secondary);
assert.ok(result.warnings().length > 0);
}
function selectorTester(def) {
return function(selector) {
return def + '\n' + selector + ' {}';
};
}
module.exports = {
fixture: fixture,
assertSuccess: assertSuccess,
assertFailure: assertFailure,
assertSingleFailure: assertSingleFailure,
selectorTester: selectorTester,
test: getPostcssResult,
};
|
JavaScript
| 0 |
@@ -197,68 +197,8 @@
) %7B%0A
- // Call then() at the end to make the LazyResult evaluate%0A
va
|
f554c69ce0f97bde23b4a6b1cec98e4b30c75a8a
|
Rename close button in ScreenDetails.
|
app/assets/javascripts/components/ScreenDetails.js
|
app/assets/javascripts/components/ScreenDetails.js
|
import React, {Component} from 'react';
import {Input, Panel, ListGroup, ListGroupItem, ButtonToolbar, Button} from 'react-bootstrap';
import ElementCollectionLabels from './ElementCollectionLabels';
import UIStore from './stores/UIStore';
import UIActions from './actions/UIActions';
import Aviator from 'aviator';
import ScreenWellplates from './ScreenWellplates';
import ElementStore from './stores/ElementStore';
import ElementActions from './actions/ElementActions';
export default class ScreenDetails extends Component {
constructor(props) {
super(props);
const {screen} = props;
this.state = { screen };
}
componentWillReceiveProps(nextProps) {
const {screen} = nextProps;
this.setState({ screen });
}
handleSubmit() {
const {screen} = this.state;
if(screen.isNew) {
ElementActions.createScreen(screen);
} else {
ElementActions.updateScreen(screen);
}
}
handleInputChange(type, event) {
let {screen} = this.state;
const value = event.target.value;
switch (type) {
case 'name':
screen.name = value;
break;
case 'requirements':
screen.requirements = value;
break;
case 'collaborator':
screen.collaborator = value;
break;
case 'conditions':
screen.conditions = value;
break;
case 'result':
screen.result = value;
break;
case 'description':
screen.description = value;
break;
}
this.setState({
screen: screen
});
}
closeDetails() {
UIActions.deselectAllElements();
let uiState = UIStore.getState();
Aviator.navigate(`/collection/${uiState.currentCollection.id}`);
}
dropWellplate(wellplate) {
const {screen} = this.state;
screen.wellplates.push(wellplate);
this.setState({ screen });
}
deleteWellplate(wellplate){
const {screen} = this.state;
const wellplateIndex = screen.wellplates.indexOf(wellplate);
screen.wellplates.splice(wellplateIndex, 1);
this.setState({ screen });
}
render() {
const {screen} = this.state;
const {id, wellplates, name, collaborator, result, conditions, requirements, description} = screen;
const submitLabel = screen.isNew ? "Create" : "Save";
return (
<div key={screen.id}>
<Panel header="Screen Details" bsStyle={screen.isEdited ? 'info' : 'primary'}>
<Button bsStyle="danger" bsSize="xsmall" className="button-right" onClick={this.closeDetails.bind(this)}>
<i className="fa fa-times"></i>
</Button>
<h3>{name}</h3>
<ElementCollectionLabels element={screen}/>
<ListGroup fill>
<ListGroupItem>
<table width="100%">
<tr>
<td width="50%" className="padding-right">
<Input
type="text"
label="Name"
value={name}
onChange={event => this.handleInputChange('name', event)}
disabled={screen.isMethodDisabled('name')}
/>
</td>
<td width="50%">
<Input
type="text"
label="Collaborator"
value={collaborator}
onChange={event => this.handleInputChange('collaborator', event)}
disabled={screen.isMethodDisabled('collaborator')}
/>
</td>
</tr>
<tr>
<td className="padding-right">
<Input
type="text"
label="Requirements"
value={requirements}
onChange={event => this.handleInputChange('requirements', event)}
disabled={screen.isMethodDisabled('requirements')}
/>
</td>
<td >
<Input
type="text"
label="Conditions"
value={conditions}
onChange={event => this.handleInputChange('conditions', event)}
disabled={screen.isMethodDisabled('conditions')}
/>
</td>
</tr>
<tr>
<td colSpan="2">
<Input
type="text"
label="Result"
value={result}
onChange={event => this.handleInputChange('result', event)}
disabled={screen.isMethodDisabled('result')}
/>
</td>
</tr>
<tr>
<td colSpan="2">
<Input
type="textarea"
label="Description"
value={description}
onChange={event => this.handleInputChange('description', event)}
disabled={screen.isMethodDisabled('description')}
/>
</td>
</tr>
</table>
</ListGroupItem>
<ListGroupItem header="Wellplates">
<ScreenWellplates
wellplates={wellplates}
dropWellplate={wellplate => this.dropWellplate(wellplate)}
deleteWellplate={wellplate => this.deleteWellplate(wellplate)}
/>
</ListGroupItem>
</ListGroup>
<ButtonToolbar>
<Button bsStyle="primary" onClick={() => this.closeDetails()}>Back</Button>
<Button bsStyle="warning" onClick={() => this.handleSubmit()}>{submitLabel}</Button>
</ButtonToolbar>
</Panel>
</div>
);
}
}
|
JavaScript
| 0 |
@@ -5741,12 +5741,13 @@
()%7D%3E
-Back
+Close
%3C/Bu
|
204399123e0353805d3de8b25bf0cad1dee2b5c2
|
refactor code
|
app/containers/TranslationStatus/index.js
|
app/containers/TranslationStatus/index.js
|
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { showLoading, hideLoading } from 'react-redux-loading-bar'
import LinearProgress from 'material-ui/LinearProgress'
import { FormattedMessage } from 'react-intl'
import { makeSelectLocale } from 'containers/LanguageProvider/selectors'
import api from 'services'
import P from 'components/P'
import messages from './messages'
class TranslationStatus extends PureComponent {
state = {
pictogramsValidated: 0,
totalPictograms: 0,
arasaacPhrases: 0,
arasaacTranslated: 0,
statisticsAvailable: false
}
componentDidMount() {
const { language, locale } = this.props
// we use userLocale if given by props (ProfileView), otherwise locale
this.updateData(language || locale)
}
componentDidUpdate(prevProps) {
const { language, locale } = this.props
if (prevProps.language !== language) {
// we use userLocale if given by props (ProfileView), otherwise locale
this.updateData(language || locale)
}
}
updateData = async (language) => {
const { showProgressBar, hideProgressBar } = this.props
showProgressBar()
try {
const translationData = await api.TRANSLATIONS_STATUS(language)
const { pictogramsValidated, totalPictograms, arasaacPhrases, arasaacTranslated } = translationData
if (language === 'en') {
this.setState({ statisticsAvailable: true, pictogramsValidated, totalPictograms, arasaacPhrases: 100, arasaacTranslated: 100 })
} else {
this.setState({ statisticsAvailable: true, pictogramsValidated, totalPictograms, arasaacPhrases, arasaacTranslated })
}
hideProgressBar()
} catch (error) {
this.setState({ statisticsAvailable: false })
console.log(error)
hideProgressBar()
}
}
render() {
const {
pictogramsValidated,
totalPictograms,
arasaacPhrases,
arasaacTranslated,
statisticsAvailable
} = this.state
console.log(this.props.locale)
console.log(statisticsAvailable, 'fffff')
const webTranslated = this.props.locale === 'en' ? 100 : parseInt(((arasaacTranslated) / (arasaacPhrases)) * 100, 10)
const pictosValidated = parseInt((pictogramsValidated / totalPictograms) * 100, 10)
const webTranslatedString = webTranslated.toString()
const pictosValidatedString = pictosValidated.toString()
return (
<div>
{statisticsAvailable ?
(
<div>
<P><FormattedMessage {...messages.webTranslationStatus} values={{ webTranslatedString }} /></P>
<LinearProgress style={{ height: '5px', maxWidth: '500px' }} mode='determinate' value={webTranslated} />
<P><FormattedMessage {...messages.pictosTranslationStatus} values={{ pictosValidatedString }} /> </P>
<LinearProgress style={{ height: '5px', maxWidth: '500px' }} mode='determinate' value={pictosValidated} />
</div>
) : (
<P><FormattedMessage {...messages.noDataAvailable} /></P>
)}
</div>
)
}
}
TranslationStatus.propTypes = {
showProgressBar: PropTypes.func.isRequired,
hideProgressBar: PropTypes.func.isRequired,
language: PropTypes.string,
locale: PropTypes.string.isRequired
}
const mapStateToProps = (state) => ({
locale: makeSelectLocale()(state)
})
const mapDispatchToProps = (dispatch) => ({
showProgressBar: () => dispatch(showLoading()),
hideProgressBar: () => dispatch(hideLoading())
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(TranslationStatus)
|
JavaScript
| 0.023493 |
@@ -1392,192 +1392,8 @@
ata%0A
- if (language === 'en') %7B%0A this.setState(%7B statisticsAvailable: true, pictogramsValidated, totalPictograms, arasaacPhrases: 100, arasaacTranslated: 100 %7D)%0A %7D else %7B%0A
@@ -1516,17 +1516,8 @@
%7D)%0A
- %7D%0A%0A
@@ -1614,33 +1614,8 @@
%7D)%0A
- console.log(error)%0A
@@ -1825,141 +1825,25 @@
cons
-ole.log(this.props.locale)%0A console.log(statisticsAvailable, 'fffff')%0A const webTranslated = this.props.locale === 'en' ? 100 :
+t webTranslated =
par
|
e87f09935cd46150b1edfb103b34fdd9933badce
|
fix resource complete event
|
src/Loader.js
|
src/Loader.js
|
var async = require('async'),
Resource = require('./Resource'),
EventEmitter2 = require('eventemitter2').EventEmitter2;
/**
* Manages the state and loading of multiple resources to load.
*
* @class
* @param baseUrl {string} The base url for all resources loaded by this loader.
*/
function Loader(baseUrl) {
EventEmitter2.call(this);
/**
* The base url for all resources loaded by this loader.
*
* @member {string}
*/
this.baseUrl = baseUrl || '';
/**
* The resources waiting to be loaded.
*
* @member {Resource[]}
*/
this.queue = [];
/**
* The progress percent of the loader going through the queue.
*
* @member {number}
*/
this.progress = 0;
/**
* The percentage of total progress that a single resource represents.
*
* @member {number}
*/
this._progressChunk = 0;
/**
* The middleware to run before loading each resource.
*
* @member {function[]}
*/
this._beforeMiddleware = [];
/**
* The middleware to run after loading each resource.
*
* @member {function[]}
*/
this._afterMiddleware = [];
/**
* The `_loadResource` function bound with this object context.
*
* @private
* @member {function}
*/
this._boundLoadResource = this._loadResource.bind(this);
/**
* The `_onComplete` function bound with this object context.
*
* @private
* @member {function}
*/
this._boundOnComplete = this._onComplete.bind(this);
/**
* Emitted once per loaded or errored resource.
*
* @event progress
*/
/**
* Emitted once per errored resource.
*
* @event error
*/
/**
* Emitted once per loaded resource.
*
* @event load
*/
/**
* Emitted when the loader begins to process the queue.
*
* @event start
*/
/**
* Emitted when the queued resources all load.
*
* @event complete
*/
}
Loader.prototype = Object.create(EventEmitter2.prototype);
Loader.prototype.constructor = Loader;
module.exports = Loader;
/**
* Adds a resource (or multiple resources) to the loader queue.
*
* @alias enqueue
* @param url {string} The url for this resource, relative to the baseUrl of this loader.
* @param [options] {object} The options for the load.
* @param [options.crossOrigin] {boolean} Is this request cross-origin? Default is to determine automatically.
* @param [options.loadType=Resource.LOAD_TYPE.XHR] {Resource.XHR_LOAD_TYPE} How should this resource be loaded?
* @param [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] {Resource.XHR_RESPONSE_TYPE} How should the data being
* loaded be interpreted when using XHR?
* @return {Loader}
*/
Loader.prototype.add = Loader.prototype.enqueue = function (url, options) {
this.queue.push(new Resource(this.baseUrl + url, options));
return this;
};
/**
* Sets up a middleware function that will run *before* the
* resource is loaded.
*
* @alias before
* @param middleware {function} The middleware function to register.
* @return {Loader}
*/
Loader.prototype.pre = Loader.prototype.before = function (fn) {
this._beforeMiddleware.push(fn);
return this;
};
/**
* Sets up a middleware function that will run *after* the
* resource is loaded.
*
* @alias after
* @param middleware {function} The middleware function to register.
* @return {Loader}
*/
Loader.prototype.use = Loader.prototype.after = function (fn) {
this._afterMiddleware.push(fn);
return this;
};
/**
* Resets the queue of the loader to prepare for a new load.
*
* @return {Loader}
*/
Loader.prototype.reset = function () {
this.queue.length = 0;
this.progress = 0;
};
/**
* Starts loading the queued resources.
*
* @fires start
* @param [parallel=true] {boolean} Should the queue be downloaded in parallel?
* @param [callback] {function} Optional callback that will be bound to the `complete` event.
* @return {Loader}
*/
Loader.prototype.load = function (parallel, cb) {
if (typeof parallel === 'function') {
cb = parallel;
}
if (typeof cb === 'function') {
this.once('complete', cb);
}
this._progressChunk = 100 / this.queue.length;
this.emit('start');
// only disable parallel if they explicitly pass `false`
if (parallel === false) {
async.each(this.queue, this._boundLoadResource, this._onComplete);
}
else {
async.eachSeries(this.queue, this._boundLoadResource, this._onComplete);
}
return this;
};
/**
* Loads a single resource.
*
* @fires progress
* @private
*/
Loader.prototype._loadResource = function (resource, next) {
var self = this;
this._runMiddleware(resource, this._beforeMiddleware, function () {
resource.on('progress', self.emit.bind(self, 'progress'));
resource.on('load', self._onLoad.bind(self, resource, next));
resource.load();
});
};
/**
* Called once each resource has loaded.
*
* @fires complete
* @private
*/
Loader.prototype._onComplete = function () {
this.emit('complete');
};
/**
* Called each time a resources is loaded.
*
* @fires progress
* @fires error
* @fires load
* @private
*/
Loader.prototype._onLoad = function (resource, next) {
this.progress += this._progressChunk;
this.emit('progress', resource);
if (resource.error) {
this.emit('error', resource);
}
else {
this.emit('load', resource);
}
this._runMiddleware(resource, this._afterMiddleware, next);
};
/**
* Run middleware functions on a resource.
*
* @private
*/
Loader.prototype._runMiddleware = function (resource, fns, cb) {
var self = this;
async.eachSeries(fns, function (fn, next) {
fn.call(self, resource, next);
}, cb);
};
Loader.LOAD_TYPE = Resource.LOAD_TYPE;
Loader.XHR_READY_STATE = Resource.XHR_READY_STATE;
Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE;
|
JavaScript
| 0.000001 |
@@ -4943,20 +4943,24 @@
rce.on('
-load
+complete
', self.
|
bd02a251a1e181bf741c6fa10f6cd13df3d3ff13
|
Fix inability to type into name inputs
|
src/Person.js
|
src/Person.js
|
import React, { Component } from "react";
import Amount from "./Amount";
class Person extends Component {
constructor(props) {
super(props);
var name = this.props.person || "";
var amount = this.props.amount || 0;
amount = parseFloat(amount);
var max = this.props.max || null;
this.state = {
name: name,
amount: amount,
max: max,
canContinue: name && amount > 0 && (!amount || amount <= max)
};
this.onNext = this.onNext.bind(this);
this.onAmountChanged = this.onAmountChanged.bind(this);
this.onNameChanged = this.onNameChanged.bind(this);
this.onKeyPress = this.onKeyPress.bind(this);
}
onNext() {
if (this.state.canContinue && this.props.onValues) {
this.props.onValues(this.state.name, parseFloat(this.state.amount));
}
}
onAmountChanged(amount) {
this.setState({
amount: amount,
name: this.state.name,
canContinue: this.state.name && amount > 0 && amount <= this.state.max,
max: this.state.max
});
}
onNameChanged(event) {
var name = event.target.value;
if (name) {
this.setState({
amount: this.state.amount,
name: event.target.value,
canContinue: name && this.state.amount > 0 && this.state.amount <= this.state.max,
max: this.state.max
});
}
}
onKeyPress(event) {
if (event.key === "Enter") {
event.preventDefault();
this.onNext();
}
}
render() {
return (
<div>
<p className="app-intro app-instruction lead">
{this.props.title || "?"}
</p>
<form className="form-horizontal">
<div className="form-group">
<div className="input-group">
<span className="input-group-addon" aria-hidden="true">
<span className="glyphicon glyphicon-user"></span>
</span>
<input name={this.props.name}
className="form-control"
onChange={this.onNameChanged}
onKeyPress={this.onKeyPress}
placeholder={this.props.person || "Name"}
value={this.props.person || ""}
type="text"
aria-label={this.personLabel}
autoFocus
label={this.personLabel} />
</div>
</div>
<div className="form-group">
<Amount name="total-person-1"
min={0.01}
max={this.props.max}
label={this.props.amountLabel}
onEnterKey={this.onNext}
onValueChanged={this.onAmountChanged}
value={this.props.amount || ""}
canEditAmount={this.props.canEditAmount} />
</div>
<button type="button" className="btn btn-primary" onClick={this.onNext} disabled={!this.state.canContinue}>{this.props.buttonText}</button>
</form>
</div>
);
}
}
export default Person;
|
JavaScript
| 0 |
@@ -2148,33 +2148,40 @@
-v
+defaultV
alue=%7Bthis.props
|
2ad9d4c22945caf714e90c7e64be58a488f5f864
|
add link to visualization after export
|
server-static/export.js
|
server-static/export.js
|
var source = new EventSource('/export/updates');
source.onopen = function() {
document.querySelectorAll('.fusiontable').forEach(function($table) {
$table.classList.add('fusiontable--loading');
});
};
source.addEventListener(
'message',
function(event) {
var data = JSON.parse(event.data);
if (!data) {
return;
}
var $listEntry = document.querySelector(
'.fusiontable[data-id="' + data.table.id + '"]'
);
$listEntry.classList.remove('fusiontable--loading');
$listEntry.classList.add('fusiontable--success');
var type =
data.driveFile.mimeType === 'application/vnd.google-apps.spreadsheet'
? 'Spreadsheet'
: 'CSV';
var driveLink =
' <a href="https://drive.google.com/open?id=' +
data.driveFile.id +
'" title="Open ' +
data.driveFile.name +
' ' +
type +
'" target="_blank"><small>Open ' +
type +
'</small></a>';
$listEntry.innerHTML += driveLink;
},
false
);
|
JavaScript
| 0 |
@@ -948,16 +948,243 @@
l%3E%3C/a%3E';
+%0A var visualizerLink =%0A ' %3Ca href=%22/visualizer/#file=' +%0A data.driveFile.id +%0A '%22 title=%22Open ' +%0A data.driveFile.name +%0A ' visualization%22 target=%22_blank%22%3E%3Csmall%3EOpen Visualization%3C/small%3E%3C/a%3E';
%0A%0A $l
@@ -1214,16 +1214,39 @@
riveLink
++ ', ' + visualizerLink
;%0A %7D,%0A
|
9d5be1d5ef10e97ffde4db164ea2acebd9b7464b
|
create API documentation
|
server/config/config.js
|
server/config/config.js
|
require('dotenv').config();
module.exports = {
development: {
use_env_variable: 'DEV_DATABASE',
dialect: 'postgres',
},
test: {
use_env_variable: 'TEST_DATABASE',
dialect: 'postgres',
},
production: {
use_env_variable: 'DEV_DATABASE',
dialect: 'postgres',
}
};
|
JavaScript
| 0 |
@@ -240,36 +240,37 @@
_variable: '
-DEV_DATABASE
+PRODUCTION_DB
',%0A diale
|
81017eaea7ce08a951274a6a8dbc11dca38bc27e
|
Revert "RTL: remove blank character inside bdi (#9038)" (#9056)
|
app/javascript/mastodon/components/display_name.js
|
app/javascript/mastodon/components/display_name.js
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
export default class DisplayName extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
others: ImmutablePropTypes.list,
};
render () {
const { account, others } = this.props;
const displayNameHtml = { __html: account.get('display_name_html') };
let suffix;
if (others && others.size > 1) {
suffix = `+${others.size}`;
} else {
suffix = <span className='display-name__account'>@{account.get('acct')}</span>;
}
return (
<span className='display-name'>
<bdi><strong className='display-name__html' dangerouslySetInnerHTML={displayNameHtml} /></bdi>
<span>{suffix}</span>
</span>
);
}
}
|
JavaScript
| 0 |
@@ -743,31 +743,17 @@
bdi%3E
-%0A %3Cspan%3E
+
%7Bsuffix%7D
%3C/sp
@@ -748,23 +748,16 @@
%7Bsuffix%7D
-%3C/span%3E
%0A %3C
|
a88fb122486cbfb47fcf566c87439c445faace56
|
add supports.localStorage
|
src/System.js
|
src/System.js
|
/**
* @author mr.doob / http://mrdoob.com/
*/
System = {
browser: ( function () {
if ( navigator.userAgent.match( /arora/i ) ) {
return 'Arora';
} else if ( navigator.userAgent.match( /chrome/i ) ) {
return 'Chrome';
} else if ( navigator.userAgent.match( /epiphany/i ) ) {
return 'Epiphany';
} else if ( navigator.userAgent.match( /firefox/i ) ) {
return 'Firefox';
} else if ( navigator.userAgent.match( /mobile safari/i ) ) {
return 'Mobile Safari';
} else if ( navigator.userAgent.match( /midori/i ) ) {
return 'Midori';
} else if ( navigator.userAgent.match( /opera/i ) ) {
return 'Opera';
} else if ( navigator.userAgent.match( /safari/i ) ) {
return 'Safari';
} else if ( navigator.userAgent.match( /msie/i ) ) {
return 'Internet Explorer';
}
return false;
} )(),
os: ( function () {
if ( navigator.userAgent.match( /android/i ) ) {
return 'Android';
} else if ( navigator.userAgent.match( /ipod/i ) || navigator.userAgent.match( /ipad/i ) ) {
return 'iOS';
} else if ( navigator.userAgent.match( /linux/i ) ) {
return 'Linux';
} else if ( navigator.userAgent.match( /macintosh/i ) ) {
return 'Macintosh';
} else if ( navigator.userAgent.match( /windows/i ) ) {
return 'Windows';
}
return false;
} )(),
supports: {
canvas: !! window.CanvasRenderingContext2D,
webgl: ( function () {
try {
return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' );
} catch( error ) {
return false;
}
} )(),
worker: !! window.Worker,
file: window.File && window.FileReader && window.FileList && window.Blob
}
};
|
JavaScript
| 0.000001 |
@@ -1707,16 +1707,152 @@
dow.Blob
+,%0A%0A%09%09localStorage: ( function() %7B%0A%0A%09%09%09try %7B%0A%0A%09%09%09%09return !!localStorage.getItem;%0A%0A%09%09%09%7D catch( error ) %7B%0A%0A%09%09%09%09return false;%0A%0A%09%09%09%7D%0A%0A%09%09%7D )()
%0A%0A%09%7D%0A%0A%7D;
|
0496d24ce21842cbca6a588e7263bf577b8b48b1
|
Make show name the slug.
|
decentral.js
|
decentral.js
|
var Maki = require('maki');
var config = require('./config');
var decentral = new Maki( config );
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var Credit = decentral.define('Credit', {
internal: true,
attributes: {
_person: { type: ObjectId , ref: 'Person', required: true },
role: { type: String , enum: ['host', 'producer', 'guest'] }
}
});
var Show = decentral.define('Show', {
attributes: {
name: { type: String , max: 35 , required: true , name: true },
created: { type: Date , default: Date.now },
description: { type: String },
hosts: [ Credit.Schema ]
},
icon: 'unmute'
});
var Recording = decentral.define('Recording', {
attributes: {
_show: { type: ObjectId , ref: 'Show', required: true },
title: { type: String , max: 35 , required: true , name: true },
recorded: { type: Date },
released: { type: Date , default: Date.now },
description: { type: String },
credits: [ Credit.Schema ]
},
icon: 'sound'
});
var Person = decentral.define('Person', {
attributes: {
name: {
given: { type: String },
family: { type: String }
},
gpg: {
fingerprint: { type: String }
},
profiles: {}
},
virtuals: {
'name.full': function() {
return [ this.name.given , this.name.family ].join(' ');
}
},
icon: 'user'
});
decentral.start();
|
JavaScript
| 0.000017 |
@@ -520,32 +520,45 @@
ed: true , name:
+ true , slug:
true %7D,%0A cre
|
dd5ac2f33538e82d685dce5a916ec6fadda32942
|
fix for Resolution method is overspecified -refs #8
|
tests/lib.test.js
|
tests/lib.test.js
|
'use strict';
var assert = require('assert')
var config = require('../config')
var lib = require('../lib/')
var mocks = require('./fixtures')
mocks.initMocks()
describe('Lib', function() {
it('Gets datapackage.json', async (done) => {
let api = new lib.DataHubApi(config)
// let dp = await api.getPackage('admin', 'demo-package')
let dpjson = await api.getPackage('admin', 'demo-package')
assert.equal(dpjson.name, 'demo-package')
assert.equal(dpjson.resources.length, 1)
done()
});
it('Gets README', async (done) => {
let api = new lib.DataHubApi(config)
let readme = await api.getPackageFile('admin', 'demo-package', 'README.md')
assert.equal(readme.slice(0,27), 'DataHub frontend in node.js')
done()
});
})
|
JavaScript
| 0.000001 |
@@ -103,17 +103,16 @@
/lib/')%0A
-%0A
var mock
@@ -157,17 +157,16 @@
ocks()%0A%0A
-%0A
describe
@@ -177,18 +177,13 @@
b',
-function()
+() =%3E
%7B%0A
@@ -210,36 +210,32 @@
e.json', async (
-done
) =%3E %7B%0A let a
@@ -270,70 +270,8 @@
ig)%0A
- // let dp = await api.getPackage('admin', 'demo-package')%0A
@@ -420,27 +420,16 @@
gth, 1)%0A
- done()%0A
%7D);%0A%0A
@@ -454,20 +454,16 @@
async (
-done
) =%3E %7B%0A
@@ -654,19 +654,8 @@
s')%0A
- done()%0A
%7D)
@@ -659,9 +659,8 @@
%7D);%0A%7D)%0A
-%0A
|
2fa0910688e7e692473141eadfcda18e67a45e6f
|
revert pretty
|
tests/oldTests.js
|
tests/oldTests.js
|
require('chai').should()
const z = require('src/z')
describe('old tests', function () {
it('should map an array', function () {
var $map = (numbers, f) => {
return z(numbers)(
(_, xs = []) => [],
(x, xs) => [f(x)].concat(xs.map(f))
)
}
$map([1, 2, 3, 4, 5], number => number * 2).should.eql([2, 4, 6, 8, 10])
})
it('should use 3 positions of pattern matching', function () {
var compress = numbers =>
z(numbers)(
(x, y, xs) => x === y ? compress([x].concat(xs)) : [x].concat(compress([y].concat(xs))),
(x, xs) => x // stopping condition
)
compress([1, 1, 2, 3, 3, 3]).should.eql([1, 2, 3])
})
it('should map a constant', function () {
z('h')((x = 'h') => true, x => false).should.equal(true)
})
it('should map a constant 2', function () {
z('a')((x = 'h') => true, x => false).should.equal(false)
})
it('should map a constant 3', function () {
var factorial = function (number) {
return z(number)(function (x) {
return x === 0 ? 1 : x * factorial(x - 1)
})
}
})
it('should reverse a list', function () {
const myReverse = list =>
z(list)(
(head, tail = []) => [head],
(head, tail) => myReverse(tail).concat(head)
)
myReverse([1, 2, 3, 4, 5]).should.eql([5, 4, 3, 2, 1])
})
it('should reverse a list with function', function () {
const myReverse = list =>
z(list)(
function (head, tail = []) {
return [head]
},
function (head, tail) {
return myReverse(tail).concat(head)
}
)
myReverse([1, 2, 3, 4, 5]).should.eql([5, 4, 3, 2, 1])
})
it('should match array of arrays', function () {
var matched = false
z([1, 2, [3]])(
(x = Array) => { (matched = true) },
(x) => { console.log('here', x) }
)
matched.should.eql(true)
})
it('should match a number', function () {
z(1)(x => true).should.equal(true)
})
it('should match a string', function () {
z('test')(
(x = 'testa') => false,
(x = 'test') => true,
(x = 'testo') => false,
function otherwise () {
return false
}
).should.equal(true)
})
})
|
JavaScript
| 0.000001 |
@@ -730,16 +730,23 @@
z('h')(
+%0A
(x = 'h'
@@ -747,34 +747,42 @@
= 'h') =%3E true,
- x
+%0A (x)
=%3E false).shoul
@@ -766,32 +766,37 @@
(x) =%3E false
+%0A
).should.equal(t
@@ -863,16 +863,23 @@
z('a')(
+%0A
(x = 'h'
@@ -888,18 +888,26 @@
=%3E true,
- x
+%0A (x)
=%3E fals
@@ -907,16 +907,21 @@
=%3E false
+%0A
).should
@@ -1049,16 +1049,25 @@
number)(
+%0A
function
@@ -1069,24 +1069,26 @@
ction (x) %7B%0A
+
retu
@@ -1094,15 +1094,17 @@
urn
+(
x === 0
+)
? 1
@@ -1133,17 +1133,26 @@
)%0A
-%7D
+ %7D%0A
)%0A %7D%0A
@@ -1549,26 +1549,16 @@
= %5B%5D) %7B
-%0A
return
@@ -1563,24 +1563,16 @@
n %5Bhead%5D
-%0A
%7D,%0A
@@ -1598,26 +1598,16 @@
tail) %7B
-%0A
return
@@ -1634,24 +1634,16 @@
at(head)
-%0A
%7D%0A
@@ -1829,16 +1829,24 @@
ay) =%3E %7B
+%0A
(matche
@@ -1854,16 +1854,22 @@
= true)
+%0A
%7D,%0A
@@ -1878,16 +1878,24 @@
(x) =%3E %7B
+%0A
console
@@ -1909,16 +1909,22 @@
ere', x)
+%0A
%7D%0A )
@@ -2017,17 +2017,26 @@
(1)(
-x
+%0A (x)
=%3E true
).sh
@@ -2031,16 +2031,21 @@
=%3E true
+%0A
).should
|
c41d668e10fff0502aa9a5e0d9fb97eda3e1a038
|
Indent application.js according to 2-spaces
|
src/main/resources/assets/app/scripts/routers/application.js
|
src/main/resources/assets/app/scripts/routers/application.js
|
/**
* Application Router
*
*/
define([
'jquery',
'backbone',
'underscore',
'views/application_view',
'views/jobs_collection_view',
'views/job_detail_collection_view',
'views/main_menu',
'views/graphbox_view'
],
function($,
Backbone,
_,
ApplicationView,
JobsCollectionView,
JobDetailCollectionView,
MainMenuView,
GraphboxView) {
var ApplicationRouter;
ApplicationRouter = Backbone.Router.extend({
routes: {
'' : 'index',
'jobs/*path' : 'showJob'
},
initialize: function() {
window.app || (window.app = {});
_.extend(window.app, {
applicationView: new ApplicationView({
collection: window.app.jobsCollection
}).render(),
jobsCollectionView: new JobsCollectionView({
collection: window.app.resultsCollection
}),
detailsCollectionView: new JobDetailCollectionView({
collection: window.app.detailsCollection
}),
mainMenuView: new MainMenuView({
collection: window.app.jobsCollection
}).render()
});
window.app.lightbox = new GraphboxView();
window.app.resultsCollection.trigger('reset');
},
navigateJob: function(jobName) {
this.navigate('jobs/' + jobName, {trigger: true});
},
index: function() {
app.detailsCollection.reset();
app.resultsCollection.reset(app.jobsCollection.models);
},
showJob: function(path) {
app.detailsCollection.deserialize(path);
}
});
return ApplicationRouter;
});
|
JavaScript
| 0 |
@@ -23,11 +23,8 @@
ter%0A
- *%0A
*/%0A
@@ -32,23 +32,16 @@
efine(%5B%0A
-
'jquer
@@ -44,23 +44,16 @@
query',%0A
-
'backb
@@ -58,23 +58,16 @@
kbone',%0A
-
'under
@@ -74,23 +74,16 @@
score',%0A
-
'views
@@ -94,39 +94,32 @@
lication_view',%0A
-
'views/jobs_co
@@ -126,39 +126,32 @@
llection_view',%0A
-
'views/job_det
@@ -172,23 +172,16 @@
_view',%0A
-
'views
@@ -193,23 +193,16 @@
_menu',%0A
-
'views
@@ -221,25 +221,11 @@
ew'%0A
- %5D,%0A
+%5D,%0A
func
@@ -240,24 +240,16 @@
-
-
Backbone
@@ -258,24 +258,16 @@
-
-
_,%0A
@@ -269,24 +269,16 @@
-
-
Applicat
@@ -282,32 +282,24 @@
cationView,%0A
-
Jobs
@@ -310,32 +310,24 @@
ectionView,%0A
-
JobD
@@ -355,24 +355,16 @@
-
-
MainMenu
@@ -377,24 +377,16 @@
-
-
Graphbox
@@ -404,30 +404,8 @@
var
-ApplicationRouter;%0A%0A
Appl
|
072404644af9410a99195a0e9022c7786cf452f9
|
Add comment to function.
|
app/dashboard/static/js/app/utils/urls.js
|
app/dashboard/static/js/app/utils/urls.js
|
/*! Kernel CI Dashboard | Licensed under the GNU GPL v3 (or later) */
define([
'sprintf',
'utils/git-rules',
'URI'
], function(p, gitRules, URI) {
'use strict';
var urls = {};
urls.translateServerURL = function(vUrl, url, path, data) {
var sPath = '',
sURL,
tURI,
tURIp;
if (url !== null && url !== undefined) {
sURL = url;
} else {
sURL = vUrl;
}
if (path !== null && path !== undefined) {
sPath = path;
} else {
if (data !== null && data !== undefined) {
data.forEach(function(value) {
sPath = sPath + value + '/';
});
}
}
tURI = new URI(sURL);
tURIp = tURI.path() + '/' + sPath;
return [tURI, tURIp];
};
urls.translateCommit = function(url, sha) {
var bURL = null,
cURL = null,
idx = 0,
parser,
hostName,
urlPath,
knownGit,
rule,
lenRule;
if ((url !== null && url !== '') && (sha !== null && sha !== '')) {
parser = new URI(url);
hostName = parser.hostname();
urlPath = parser.path();
// Perform translation only if we know the host.
if (gitRules.hasOwnProperty(hostName)) {
knownGit = gitRules[hostName];
rule = knownGit[3];
lenRule = rule.length;
for (idx; idx < lenRule; idx = idx + 1) {
urlPath = urlPath.replace(rule[idx][0], rule[idx][1]);
}
bURL = new URI({
protocol: knownGit[0],
hostname: hostName,
path: p.sprintf(knownGit[1], urlPath)
});
cURL = new URI({
protocol: knownGit[0],
hostname: hostName,
path: p.sprintf(knownGit[2], urlPath) + sha
});
bURL = bURL.href();
cURL = cURL.href();
}
}
return [bURL, cURL];
};
return urls;
});
|
JavaScript
| 0 |
@@ -856,24 +856,124 @@
p%5D;%0A %7D;%0A%0A
+ /*%0A Return a list with:%0A 0. The base git URL%0A 1. The git commit URL%0A */%0A
urls.tra
|
47f9398aee3b8b33631f8c45f04bf001ff16af62
|
Update AutocompleteItem to use formatted suggestion
|
demo/Demo.js
|
demo/Demo.js
|
import React from 'react'
import PlacesAutocomplete, { geocodeByAddress } from '../src'
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {
address: '',
geocodeResults: null,
loading: false
}
this.handleSelect = this.handleSelect.bind(this)
this.handleChange = this.handleChange.bind(this)
this.renderGeocodeFailure = this.renderGeocodeFailure.bind(this)
this.renderGeocodeSuccess = this.renderGeocodeSuccess.bind(this)
}
handleSelect(address) {
this.setState({
address,
loading: true
})
geocodeByAddress(address, (err, { lat, lng }) => {
if (err) {
console.log('Oh no!', err)
this.setState({
geocodeResults: this.renderGeocodeFailure(err),
loading: false
})
}
console.log(`Yay! got latitude and longitude for ${address}`, { lat, lng })
this.setState({
geocodeResults: this.renderGeocodeSuccess(lat, lng),
loading: false
})
})
}
handleChange(address) {
this.setState({
address,
geocodeResults: null
})
}
renderGeocodeFailure(err) {
return (
<div className="alert alert-danger" role="alert">
<strong>Error!</strong> {err}
</div>
)
}
renderGeocodeSuccess(lat, lng) {
return (
<div className="alert alert-success" role="alert">
<strong>Success!</strong> Geocoder found latitude and longitude: <strong>{lat}, {lng}</strong>
</div>
)
}
render() {
const cssClasses = {
root: 'form-group',
label: 'form-label',
input: 'Demo__search-input',
autocompleteContainer: 'Demo__autocomplete-container'
}
const AutocompleteItem = ({ suggestion }) => (<div className="Demo__suggestion-item"><i className='fa fa-map-marker Demo__suggestion-icon'/>{suggestion}</div>)
return (
<div className='page-wrapper'>
<div className='container'>
<h1 className='display-3'>react-places-autocomplete <i className='fa fa-map-marker header'/></h1>
<p className='lead'>A React component to build a customized UI for Google Maps Places Autocomplete</p>
<hr />
<a href='https://github.com/kenny-hibino/react-places-autocomplete' className='Demo__github-link' target="_blank" >
<span className='fa fa-github Demo__github-icon'></span>
View on GitHub
</a>
</div>
<div className='container'>
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
onSelect={this.handleSelect}
classNames={cssClasses}
autocompleteItem={AutocompleteItem}
autoFocus={true}
placeholder="Search Places"
hideLabel={true}
/>
{this.state.loading ? <div><i className="fa fa-spinner fa-pulse fa-3x fa-fw Demo__spinner" /></div> : null}
{!this.state.loading && this.state.geocodeResults ?
<div className='geocoding-results'>{this.state.geocodeResults}</div> :
null}
</div>
</div>
)
}
}
export default Demo
|
JavaScript
| 0 |
@@ -1823,17 +1823,26 @@
em = (%7B
-s
+formattedS
uggestio
@@ -1850,16 +1850,24 @@
%7D) =%3E (
+%0D%0A
%3Cdiv cla
@@ -1897,16 +1897,26 @@
n-item%22%3E
+%0D%0A
%3Ci class
@@ -1966,20 +1966,161 @@
n'/%3E
-%7Bsuggestion%7D
+%0D%0A %3Cstrong%3E%7BformattedSuggestion.mainText%7D%3C/strong%3E%7B' '%7D%0D%0A %3Csmall className=%22text-muted%22%3E%7BformattedSuggestion.secondaryText%7D%3C/small%3E%0D%0A
%3C/di
@@ -2124,16 +2124,18 @@
/div%3E)%0D%0A
+%0D%0A
retu
|
5100413bcdcbcbb0c8a6224a9571e42d5c24d528
|
fix POST url
|
src/mist/io/static/js/app/views/machine_monitoring_dialog.js
|
src/mist/io/static/js/app/views/machine_monitoring_dialog.js
|
define('app/views/machine_monitoring_dialog', [
'text!app/templates/machine_monitoring_dialog.html',
'ember'],
/**
*
* Monitoring Dialog
*
* @returns Class
*/
function(machine_monitoring_dialog_html) {
return Ember.View.extend({
template: Ember.Handlebars.compile(machine_monitoring_dialog_html),
enableMonitoringClick: function() {
if (Mist.authenticated) {
this.openMonitoringDialog()
} else {
$("#login-dialog").popup('open');
}
},
openMonitoringDialog: function() {
var machine = this.get('controller').get('model');
if (Mist.authenticated) {
if (machine.hasMonitoring) {
$('#monitoring-dialog div h1').text('Disable monitoring');
$('#monitoring-enabled').show();
$('#monitoring-disabled').hide();
$('#button-back-enabled').on("click", function() {
$("#monitoring-dialog").popup('close');
});
$('#button-disable-monitoring').on("click", function() {
machine.changeMonitoring();
$('#button-disable-monitoring').off("click");
$("#monitoring-dialog").popup('close');
});
} else {
$('#monitoring-dialog div h1').text('Enable monitoring');
$('#monitoring-disabled').show();
$('#monitoring-enabled').hide()
$('#button-back-disabled').on("click", function() {
$("#monitoring-dialog").popup('close');
});
$('#button-enable-monitoring').on("click", function() {
machine.changeMonitoring();
$('#button-enable-monitoring').off("click");
$("#monitoring-dialog").popup('close');
});
if ((Mist.current_plan) && (Mist.current_plan['title'])) {
if (Mist.current_plan['has_expired']) {
//Trial or Plan expired, hide monitoring-dialog, hide free-trial
$('#enable-monitoring-dialog').hide();
$('#free-trial').hide();
$('#purchase-plan').show();
} else {
//Trial or Plan enabled. Check for quota
if (Mist.current_plan['machine_limit'] <= Mist.monitored_machines.length) {
//Quota exceeded, show buy option
$('#enable-monitoring-dialog').hide();
$('#quota-plan').show();
} else {
//Everything ok, show monitoring-dialog, hide plan-dialog
$('#enable-monitoring-dialog').show();
$('#plan-dialog').hide();
}
}
} else {
//no plans, show plan-dialog, hide monitoring-dialog
if ((Mist.user_details) && (Mist.user_details[0])) {
$('#trial-user-name').val(Mist.user_details[0]);
}
if ((Mist.user_details) && (Mist.user_details[1])) {
$('#trial-company-name').val(Mist.user_details[1]);
}
$('#enable-monitoring-dialog').hide();
$('#monitoring-enabled').hide();
$('#plan-dialog').show();
$('#free-trial').show();
$('.trial-button').show();
}
}
}
$("#monitoring-dialog").popup('open');
this.emailReady();
},
openTrialDialog: function() {
$("#trial-user-details").show();
$('.trial-button').addClass('ui-disabled');
},
clickedPurchaseDialog: function() {
$("#monitoring-dialog").popup('close');
window.location.href = "https://mist.io/account";
},
doLogin: function() {
//sends email, passwords and check if auth is ok
var payload = {
'email': Mist.email,
'password': CryptoJS.SHA256(Mist.password).toString()
};
$("#login-dialog .ajax-loader").show();
$.ajax({
url: '/auth',
type: 'POST',
headers: { "cache-control": "no-cache" },
contentType: 'application/json',
data: JSON.stringify(payload),
dataType: 'json',
timeout : 60000,
success: function(data) {
Mist.set('authenticated', true);
Mist.set('current_plan', data.current_plan);
Mist.set('user_details', data.user_details);
$("#login-dialog .ajax-loader").hide();
//If ok set Mist.auth, Mist.current_plan and Mist.user_details and keep on with enable monitoring (if current plan allows), or show the change plans dialog
$("#login-dialog").popup('close');
},
error: function(jqXHR, textstate, errorThrown) {
$("#login-dialog .ajax-loader").hide();
Mist.notificationController.warn('Authentication error');
$('div.pending-monitoring').hide();
}
});
},
backClicked: function() {
$("#monitoring-dialog").popup('close');
$('#free-trial').hide();
$('#purchase-plan').hide();
$('#quota-plan').hide();
$("#trial-user-details").hide();
$('.trial-button').removeClass('ui-disabled');
},
backLoginClicked: function() {
$('#login-dialog').popup('close');
$('#login-dialog #email').val('');
$('#login-dialog #password').val('');
},
submitTrial: function(){
if ($('#trial-user-name').val() && $('#trial-company-name').val()) {
var payload = {
"action": 'upgrade_plans',
"plan": 'Basic',
"name": $('#trial-user-name').val(),
"company_name": $('#trial-company-name').val()
};
$('#trial-user-details .ajax-loader').show();
$('#submit-trial').addClass('ui-disabled');
$.ajax({
url: 'https://mist.io/account',
type: "POST",
contentType: "application/json",
dataType: "json",
headers: { "cache-control": "no-cache" },
data: JSON.stringify(payload),
success: function(result) {
$('#trial-user-details .ajax-loader').hide();
$('#submit-trial').removeClass('ui-disabled');
$("#monitoring-dialog").popup('close');
Mist.set('current_plan', result);
$("a.monitoring-button").click()
},
error: function(jqXHR, textstate, errorThrown) {
Mist.notificationController.notify(jqXHR.responseText);
$('div.pending-monitoring').hide();
$('#trial-user-details .ajax-loader').hide();
$('.trial-button').removeClass('ui-disabled');
$('#submit-trial').removeClass('ui-disabled');
}
});
} else {
if (!($('#trial-user-name').val())) {
$('#trial-user-name').focus();
} else {
$('#trial-company-name').focus();
}
}
},
emailReady: function(){
if (Mist.email && Mist.password){
$('#auth-ok').button('enable');
} else {
try{
$('#auth-ok').button('disable');
} catch(e){
$('#auth-ok').button();
$('#auth-ok').button('disable');
}
}
}.observes('Mist.email'),
passReady: function(){
this.emailReady();
}.observes('Mist.password')
});
}
);
|
JavaScript
| 0.001473 |
@@ -7676,31 +7676,16 @@
url: '
-https://mist.io
/account
|
f939a016043585522f5fe7f5b0e88f346efb807d
|
Fix regression introduced fixing #2648, fix #2662
|
src/resources-packaged/xbl/orbeon/code-mirror/code-mirror.js
|
src/resources-packaged/xbl/orbeon/code-mirror/code-mirror.js
|
/**
* Copyright (C) 2016 Orbeon, Inc.
*
* 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; 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.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
(function() {
var $ = ORBEON.jQuery;
ORBEON.xforms.XBL.declareCompanion('fr|code-mirror', {
editor: null,
handlers: {},
hasFocus: false, // Heuristic: if has focus, don't update with value from server
userChangedSinceLastBlur: false, // Use CodeMirror's own change event to track whether the value changed
init: function() {
var outer = $(this.container).find('.xbl-fr-code-mirror-editor-outer')[0];
$('<xh:span class="xbl-fr-code-mirror-editor-inner"/>').appendTo(outer);
var inner = $(this.container).find('.xbl-fr-code-mirror-editor-inner')[0];
this.hasFocus = false;
this.userChangedSinceLastBlur= false;
this.editor = CodeMirror(
inner,
{
mode : 'xml',
lineNumbers: true,
indentUnit : 4
}
);
this.handlers = {
'change': _.bind(this.codeMirrorChange, this),
'focus' : _.bind(this.codeMirrorFocus, this),
'blur' : _.bind(this.codeMirrorBlur, this)
};
var editor = this.editor;
_.each(this.handlers, function(key, value) {
editor.on(key, value);
});
this.xformsUpdateReadonly($(this.container).is('.xforms-readonly'));
},
destroy: function() {
// Try to clean-up as much as we can
var editor = this.editor;
_.each(this.handlers, function(key, value) {
editor.off(key, value);
});
this.handlers = {};
this.editor = null;
$(this.container).find('.xbl-fr-code-mirror-editor-outer').empty();
},
xformsFocus: function() {
this.editor.focus();
},
codeMirrorFocus: function() { this.hasFocus = true; },
codeMirrorBlur: function() {
this.hasFocus = false;
if (this.userChangedSinceLastBlur) {
$(this.container).addClass('xforms-visited');
ORBEON.xforms.Document.setValue(
this.container.id,
this.xformsGetValue()
);
this.userChangedSinceLastBlur = false;
}
},
codeMirrorChange: function(codemirror, event) {
if (event.origin != 'setValue') {
this.userChangedSinceLastBlur = true;
}
},
xformsUpdateReadonly: function(readonly) {
if (readonly) {
// Use 'true' instead of 'nocursor' so that copy/paste works:
// https://github.com/orbeon/orbeon-forms/issues/1841
this.editor.setOption('readOnly', 'true');
} else {
this.editor.setOption('readOnly', false);
}
},
xformsUpdateValue: function(newValue) {
var doUpdate =
// As a shortcut, don't update the control if the user is typing in it
! this.hasFocus &&
// Don't update if the new value is the same as the current one, as doing so resets the editor position
newValue != this.editor.getValue();
if (doUpdate) {
// It seems that we need a delay refresh otherwise sometimes the content doesn't appear when in a dialog
// which is just shown. However, this doesn't work 100% of the time it seems.
var editor = this.editor;
var deferred = $.Deferred();
setTimeout(function() {
editor.setValue(newValue);
deferred.resolve();
}, 0);
return deferred.promise();
}
},
xformsGetValue: function() {
return this.editor.getValue();
}
});
})();
|
JavaScript
| 0 |
@@ -1917,34 +1917,34 @@
s, function(
-key,
value
+, key
) %7B%0A
|
61560d0ab16a4dcb8e383dd5c408d06889d2ed81
|
Update tipuesearch_set.js
|
assets/tipuesearch/tipuesearch_set.js
|
assets/tipuesearch/tipuesearch_set.js
|
/*
Tipue Search 5.0
Copyright (c) 2015 Tipue
Tipue Search is released under the MIT License
http://www.tipue.com/search
*/
var tipuesearch_pages =
["http://sorokacrc.org/",
"http://sorokacrc.org/about/",
"http://sorokacrc.org/vision/",
"http://sorokacrc.org/team/",
"http://sorokacrc.org/collaboration/",
"http://sorokacrc.org/media/",
"http://sorokacrc.org/convention/",
"http://sorokacrc.org/soroka/",
"http://sorokacrc.org/clinicalresearch/",
"http://sorokacrc.org/currentprojects/",
"http://sorokacrc.org/therap/",
"http://sorokacrc.org/sponsors/",
"http://sorokacrc.org/grants/",
"http://sorokacrc.org/services/",
"http://sorokacrc.org/acares/",
"http://sorokacrc.org/indures/",
"http://sorokacrc.org/pubs/"
];
/*
Stop words
Stop words list from http://www.ranks.nl/stopwords
*/
var tipuesearch_stop_words = ["a", "about", "above", "after", "again", "against", "all", "am", "an", "and", "any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by", "can't", "cannot", "could", "couldn't", "did", "didn't", "do", "does", "doesn't", "doing", "don't", "down", "during", "each", "few", "for", "from", "further", "had", "hadn't", "has", "hasn't", "have", "haven't", "having", "he", "he'd", "he'll", "he's", "her", "here", "here's", "hers", "herself", "him", "himself", "his", "how", "how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't", "it", "it's", "its", "itself", "let's", "me", "more", "most", "mustn't", "my", "myself", "no", "nor", "not", "of", "off", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over", "own", "same", "shan't", "she", "she'd", "she'll", "she's", "should", "shouldn't", "so", "some", "such", "than", "that", "that's", "the", "their", "theirs", "them", "themselves", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "through", "to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "were", "weren't", "what", "what's", "when", "when's", "where", "where's", "which", "while", "who", "who's", "whom", "why", "why's", "with", "won't", "would", "wouldn't", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves"];
// Word replace
var tipuesearch_replace = {'words': [
{'word': 'tipua', 'replace_with': 'tipue'},
{'word': 'javscript', 'replace_with': 'javascript'},
{'word': 'jqeury', 'replace_with': 'jquery'}
]};
// Weighting
var tipuesearch_weight = {'weight': [
{'url': 'http://www.tipue.com', 'score': 200},
{'url': 'http://www.tipue.com/search', 'score': 100},
{'url': 'http://www.tipue.com/about', 'score': 100}
]};
// Stemming
var tipuesearch_stem = {'words': [
{'word': 'e-mail', 'stem': 'email'},
{'word': 'javascript', 'stem': 'jquery'},
{'word': 'javascript', 'stem': 'js'}
]};
// Internal strings
var tipuesearch_string_1 = 'No title';
var tipuesearch_string_2 = 'Showing results for';
var tipuesearch_string_3 = 'Search instead for';
var tipuesearch_string_4 = '1 result';
var tipuesearch_string_5 = 'results';
var tipuesearch_string_6 = 'Prev';
var tipuesearch_string_7 = 'Next';
var tipuesearch_string_8 = 'Nothing found';
var tipuesearch_string_9 = 'Common words are largely ignored';
var tipuesearch_string_10 = 'Search too short';
var tipuesearch_string_11 = 'Should be one character or more';
var tipuesearch_string_12 = 'Should be';
var tipuesearch_string_13 = 'characters or more';
|
JavaScript
| 0 |
@@ -190,21 +190,24 @@
crc.org/
-a
+A
bout
+ Us
/%22,%0A%22htt
@@ -224,17 +224,17 @@
crc.org/
-v
+V
ision/%22,
@@ -256,17 +256,17 @@
crc.org/
-t
+T
eam/%22,%0A%22
@@ -286,17 +286,17 @@
crc.org/
-c
+C
ollabora
@@ -325,17 +325,17 @@
crc.org/
-m
+M
edia/%22,%0A
@@ -356,17 +356,17 @@
crc.org/
-c
+C
onventio
@@ -392,22 +392,48 @@
crc.org/
-s
+S
oroka
+ University Medical Center
/%22,%0A%22htt
@@ -454,17 +454,18 @@
org/
-c
+C
linical
-r
+ R
esea
@@ -497,16 +497,17 @@
org/
-c
+C
urrent
-p
+ P
roje
@@ -539,14 +539,25 @@
org/
-t
+T
herap
+eutic Areas
/%22,%0A
@@ -582,16 +582,26 @@
org/
-s
+S
ponsor
-s
+ed Research
/%22,%0A
@@ -622,17 +622,17 @@
crc.org/
-g
+G
rants/%22,
@@ -654,17 +654,17 @@
crc.org/
-s
+S
ervices/
@@ -692,14 +692,25 @@
org/
-acares
+Academic Research
/%22,%0A
@@ -735,15 +735,36 @@
org/
-indures
+Industry- Initiated Research
/%22,%0A
@@ -789,11 +789,19 @@
org/
-p
+P
ub
+lication
s/%22%0A
|
bf2dd558abb2207de11eee261caeb02b27ca21df
|
fix variables names and increase documentation
|
app/templates/cookie-info/_cookie-info.js
|
app/templates/cookie-info/_cookie-info.js
|
/**
* Save Cookie when accepting the terms from the cookie-info.
* the script requires the lib cookie.js from markusfalk, 'bower install markusfalk/cookie --save'
* @module CookieInfo
* @requires jquery
* @requires _core
* @requires jquery.exists
* @requires cookie
* @author Christian Schramm / André Meier da Silva
*/
define([
'jquery',
'_core',
'jquery.exists',
'cookie'
], function(
$,
_Core,
exists,
Cookie
) {
'use strict';
var CookieInfo = {
/**
* Caches all jQuery Objects for later use.
* @function _cacheElements
* @private
*/
_cacheElements: function() {
this.$cookie_info = _Core.$body.find('.cookie-info');
this.$cookie_button = _Core.$body.find('.cookie-accept');
this.accept_cookies = true;
this.cookie_expiration_time = 365; // days
},
/**
* Initiates the module.
* @function init
* @public
*/
init: function() {
CookieInfo._cacheElements();
CookieInfo.$cookie_info.exists(function() {
CookieInfo._checkCookie();
});
},
/**
* Binds all events to jQuery DOM objects.
* @function _bindEvents
* @private
*/
_bindEvents: function() {
CookieInfo.$cookie_button.on('click', function (event) {
CookieInfo._hideCookieInfo();
CookieInfo._writeCookie(accept_cookies);
});
},
/**
* Check if Cookies are available and isn't set to true.
* @function _checkCookie
* @private
*/
_checkCookie: function() {
if((navigator.cookieEnabled)) {
if (Cookie.read('cookiesAccepted') !== 'true') {
CookieInfo._writeCookie(!accept_cookies);
CookieInfo.$cookie_info.slideDown();
CookieInfo._bindEvents();
}
}
else {
/** Add Class no-cookies to the HTML tag if Cookies aren't enabled */
_Core.$html.addClass('no-cookies');
}
},
/**
* Write Cookie.
* @function _checkCookie
* @private
*/
_writeCookie: function(value) {
Cookie.create('cookiesAccepted', value, cookie_expiration_time);
},
/**
* Hide CookieInfo if Cookieterm is accepted.
* @function _hideCookieInfo
* @private
*/
_hideCookieInfo: function() {
CookieInfo.$cookie_info.slideUp();
}
};
return /** @alias module:CookieInfo */ {
/** init */
init: CookieInfo.init
};
});
|
JavaScript
| 0 |
@@ -1350,16 +1350,27 @@
eCookie(
+CookieInfo.
accept_c
@@ -1374,24 +1374,24 @@
t_cookies);%0A
-
%7D);%0A
@@ -1680,16 +1680,27 @@
Cookie(!
+CookieInfo.
accept_c
@@ -2011,32 +2011,92 @@
on _checkCookie%0A
+ * @param %7Bbollean%7D - value to be written on the Cookie%0A
* @private%0A
@@ -2135,24 +2135,24 @@
on(value) %7B%0A
-
Cookie
@@ -2185,16 +2185,27 @@
value,
+CookieInfo.
cookie_e
|
971ce8c35f889b4fda945677ced95d41fcff3214
|
FIX scrolling behavior of mobile navigation (prevent navigation to close on scroll)
|
tools/plenty-2.js
|
tools/plenty-2.js
|
/* plenty scripts */
(function( $ )
{
/*
* Initialization
*/
$( document ).ready( function()
{
$( '.mainNavigation' ).on( 'scroll touchmove mousewheel', function( event )
{
event.preventDefault();
} );
// cancel login
$( '[data-plenty="cancelLogin"]' ).click( function()
{
$( this ).closest( '.dropdown' ).removeClass( 'open' );
if ( plenty.MediaSizeService.interval() != 'xs' && plenty.MediaSizeService.interval() != 'sm' )
{
$( this ).closest( '[data-plenty="loginFormContainer"]' ).hide( 1, function()
{
$( this ).css( {overflow: 'hidden'} ).animate( {height: 0}, 250, function()
{
$( this ).delay( 300 ).queue( function()
{
$( this ).dequeue().removeAttr( 'style' );
} );
} );
} );
}
} );
// mobile navigation / aside panel
$( window ).on( 'orientationchange sizeChange', function()
{
if ( $( 'body' ).is( '.navigation-visible' ) && !$( 'input' ).is( ':focus' ) )
{
$( 'body.aside-visible' ).removeClass( 'aside-visible' );
$( 'body.navigation-visible' ).removeClass( 'navigation-visible' );
}
} );
// initialize touch functionality for mobile navigation / aside panel (requires jquery.touchSwipe.min.js)
$( '.touch body > .wrapper' ).swipe( {
swipeLeft : swipeLeft,
swipeRight : swipeRight,
allowPageScroll : 'auto',
excludedElements: 'form, input, button, select, .owl-item, .ui-slider-handle'
} );
function swipeLeft( event, direction, distance, duration, fingerCount )
{
if ( plenty.MediaSizeService.interval() == 'xs' || plenty.MediaSizeService.interval() == 'sm' )
{
if ( $( 'body' ).is( '.navigation-visible' ) && !$( 'input' ).is( ':focus' ) )
{
$( 'body' ).removeClass( 'navigation-visible' );
}
else if ( !$( 'body' ).is( '.aside-visible' ) )
{
$( 'body' ).addClass( 'aside-visible' )
}
}
}
function swipeRight( event, direction, distance, duration, fingerCount )
{
if ( plenty.MediaSizeService.interval() == 'xs' || plenty.MediaSizeService.interval() == 'sm' )
{
if ( !$( 'body' ).is( '.navigation-visible' ) && !$( 'body' ).is( '.aside-visible' ) )
{
$( 'body' ).addClass( 'navigation-visible' );
}
else if ( $( 'body' ).is( '.aside-visible' ) )
{
$( 'body' ).removeClass( 'aside-visible' );
}
}
}
// inizialize cross selling slider (requires owl.carousel.js)
$( '.crossSellingSlider' ).owlCarousel( {
items : 4,
itemsDesktop : [1199, 3],
itemsDesktopSmall: [991, 4],
itemsTablet : [767, 2],
navigation : true,
navigationText : false,
rewindNav : false,
pagination : true,
mouseDrag : true,
afterMove : function( current )
{
$( current ).find( 'img[data-plenty-lazyload]' ).trigger( 'appear' );
}
} );
// inizialize preview image slider (requires owl.carousel.js)
$( '.previewImageSlider' ).owlCarousel( {
items : 1,
itemsDesktop : false,
itemsDesktopSmall: false,
itemsTablet : false,
itemsMobile : false,
navigation : true,
navigationText : false,
lazyLoad : true,
rewindNav : false,
pagination : true,
afterInit : function()
{
$( '.owl-controls' ).removeAttr( 'style' );
},
afterUpdate : function()
{
$( '.owl-controls' ).removeAttr( 'style' );
},
afterLazyLoad : function( owl )
{
owl.find( 'img:visible' ).css( 'display', 'inline-block' );
}
} );
} );
/*
* Display error modal for old browsers
*/
$( window ).load( function()
{
// display errors for old browsers
if ( $( 'body' ).is( 'ielte7' ) )
{
$( '[data-plenty="browserErrorModal"] .modal-title' ).append( 'Ihr Browser ist veraltet!' );
$( '[data-plenty="browserErrorModal"] .modal-body' ).append( '<p>Um die Funktionen dieser Seite nutzen zu können, benötigen Sie eine aktuelle Version Ihres Browsers.<br>'
+ 'Bitte aktuallisieren Sie Ihren Browser, um Ihren Einkauf fortsetzen zu können.</p>' );
$( '[data-plenty="browserErrorModal"]' ).modal( {
show : true,
backdrop: 'static',
keyboard: false
} );
}
} );
/*
* jQuery plugin: auto-hide
* automatically hide or remove elements
* Usage:
* $(selector).autoHide(options);
*/
$.fn.autoHide = function( options )
{
var defaults = {
hideAfter : 4000, // delay to hide or remove element, in milliseconds
pauseOnHover : true, // pause delay when element is hovered
removeFromDOM : false, // remove the element from the DOM instead of hiding it
overlaySelector : false, // jQuery selector of an overlay, if used. Will be hidden after delay
closeSelector : false, // jQuery selector of a child-element to hide/ delete the element manually
hideOnOverlayClick: true // hide/ delete the element by clicking the overlay
};
var settings = $.extend( defaults, options );
this.each( function( i, element )
{
/* hides/ removes the element. If overlay selector is set, hide it too */
var doClose = function()
{
if ( !!settings.overlaySelector )
{
$( settings.overlaySelector ).hide();
}
// remove or hide after 'hideAfter' ms
if ( settings.removeFromDOM )
{
$( element ).remove();
}
else
{
$( element ).hide();
}
};
/* start/ continue delay to close/ hide element */
var startClosing = function( time )
{
return setTimeout( function()
{
doClose();
}, time );
};
if ( settings.hideAfter > 0 )
{
// START
var timeStart = (new Date).getTime();
var timeout = startClosing( settings.hideAfter );
// PAUSE & CONTINUE
if ( settings.pauseOnHover )
{
var timeRemaining = 0;
$( element ).hover( function()
{
// store remaining time
timeRemaining = (new Date).getTime() - timeStart;
// stop closing on mouse in
clearTimeout( timeout );
}, function()
{
// continue closing in mouse out
if ( timeRemaining > 0 )
{
timeout = startClosing( timeRemaining );
}
} );
}
}
// STOP
if ( !!settings.closeSelector )
{
$( element ).find( settings.closeSelector ).click( doClose );
}
if ( settings.hideOnOverlayClick && !!settings.overlaySelector )
{
$( settings.overlaySelector ).click( doClose );
}
} );
};
}( jQuery ));
|
JavaScript
| 0 |
@@ -157,18 +157,8 @@
oll
-touchmove
mous
|
6358ead5f808194b27c2e8a597cab232f7a385e2
|
add inline-source-map for test
|
gulp/scripts.js
|
gulp/scripts.js
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var webpack = require('webpack-stream');
var $ = require('gulp-load-plugins')();
function webpackWrapper(watch, test, callback) {
var webpackOptions = {
watch: watch,
module: {
preLoaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader'}],
loaders: [{ test: /\.js$/, exclude: /node_modules/, loaders: ['ng-annotate', 'babel-loader']}]
},
output: { filename: 'ng-rules.js' }
};
if(watch) {
webpackOptions.devtool = 'inline-source-map';
}
var webpackChangeHandler = function(err, stats) {
if(err) {
conf.errorHandler('Webpack')(err);
}
$.util.log(stats.toString({
colors: $.util.colors.supportsColor,
chunks: false,
hash: false,
version: false
}));
if(watch) {
watch = false;
callback();
}
};
var sources = [ path.join(conf.paths.src, '/ng-rules.js') ];
if (test) {
sources.push(path.join(conf.paths.src, '/**/*.spec.js'));
}
return gulp.src(sources)
.pipe(webpack(webpackOptions, null, webpackChangeHandler))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/')));
}
gulp.task('scripts', function () {
return webpackWrapper(false, false);
});
gulp.task('scripts:watch', ['scripts'], function (callback) {
return webpackWrapper(true, false, callback);
});
gulp.task('scripts:test', function () {
return webpackWrapper(false, true);
});
gulp.task('scripts:test-watch', ['scripts'], function (callback) {
return webpackWrapper(true, true, callback);
});
|
JavaScript
| 0.000001 |
@@ -528,32 +528,40 @@
%7D;%0A%0A if(watch
+ %7C%7C test
) %7B%0A webpackO
|
15a04ecaeb0c6b284bb706fee78bb40518b03fab
|
Fix relative timestamp in versions
|
apps/files_versions/js/versionstabview.js
|
apps/files_versions/js/versionstabview.js
|
/*
* Copyright (c) 2015
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function() {
/**
* @memberof OCA.Versions
*/
var VersionsTabView = OCA.Files.DetailTabView.extend(/** @lends OCA.Versions.VersionsTabView.prototype */{
id: 'versionsTabView',
className: 'tab versionsTabView',
_template: null,
$versionsContainer: null,
events: {
'click .revertVersion': '_onClickRevertVersion'
},
initialize: function() {
OCA.Files.DetailTabView.prototype.initialize.apply(this, arguments);
this.collection = new OCA.Versions.VersionCollection();
this.collection.on('request', this._onRequest, this);
this.collection.on('sync', this._onEndRequest, this);
this.collection.on('update', this._onUpdate, this);
this.collection.on('error', this._onError, this);
this.collection.on('add', this._onAddModel, this);
},
getLabel: function() {
return t('files_versions', 'Versions');
},
getIcon: function() {
return 'icon-history';
},
nextPage: function() {
if (this._loading) {
return;
}
if (this.collection.getFileInfo() && this.collection.getFileInfo().isDirectory()) {
return;
}
this.collection.fetch();
},
_onClickRevertVersion: function(ev) {
var self = this;
var $target = $(ev.target);
var fileInfoModel = this.collection.getFileInfo();
var revision;
if (!$target.is('li')) {
$target = $target.closest('li');
}
ev.preventDefault();
revision = $target.attr('data-revision');
var versionModel = this.collection.get(revision);
versionModel.revert({
success: function() {
// reset and re-fetch the updated collection
self.$versionsContainer.empty();
self.collection.setFileInfo(fileInfoModel);
self.collection.reset([], {silent: true});
self.collection.fetch();
self.$el.find('.versions').removeClass('hidden');
// update original model
fileInfoModel.trigger('busy', fileInfoModel, false);
fileInfoModel.set({
size: versionModel.get('size'),
mtime: versionModel.get('timestamp') * 1000,
// temp dummy, until we can do a PROPFIND
etag: versionModel.get('id') + versionModel.get('timestamp')
});
},
error: function() {
fileInfoModel.trigger('busy', fileInfoModel, false);
self.$el.find('.versions').removeClass('hidden');
self._toggleLoading(false);
OC.Notification.show(t('files_version', 'Failed to revert {file} to revision {timestamp}.',
{
file: versionModel.getFullPath(),
timestamp: OC.Util.formatDate(versionModel.get('timestamp') * 1000)
}),
{
type: 'error'
}
);
}
});
// spinner
this._toggleLoading(true);
fileInfoModel.trigger('busy', fileInfoModel, true);
},
_toggleLoading: function(state) {
this._loading = state;
this.$el.find('.loading').toggleClass('hidden', !state);
},
_onRequest: function() {
this._toggleLoading(true);
},
_onEndRequest: function() {
this._toggleLoading(false);
this.$el.find('.empty').toggleClass('hidden', !!this.collection.length);
},
_onAddModel: function(model) {
var $el = $(this.itemTemplate(this._formatItem(model)));
this.$versionsContainer.append($el);
$el.find('.has-tooltip').tooltip();
},
template: function(data) {
return OCA.Versions.Templates['template'](data);
},
itemTemplate: function(data) {
return OCA.Versions.Templates['item'](data);
},
setFileInfo: function(fileInfo) {
if (fileInfo) {
this.render();
this.collection.setFileInfo(fileInfo);
this.collection.reset([], {silent: true});
this.nextPage();
} else {
this.render();
this.collection.reset();
}
},
_formatItem: function(version) {
var timestamp = version.get('timestamp') * 1000;
var size = version.has('size') ? version.get('size') : 0;
return _.extend({
versionId: version.get('id'),
formattedTimestamp: OC.Util.formatDate(timestamp),
relativeTimestamp: OC.Util.relativeModifiedDate(timestamp),
humanReadableSize: OC.Util.humanFileSize(size, true),
altSize: n('files', '%n byte', '%n bytes', size),
hasDetails: version.has('size'),
downloadUrl: version.getDownloadUrl(),
downloadIconUrl: OC.imagePath('core', 'actions/download'),
downloadName: version.get('name'),
revertIconUrl: OC.imagePath('core', 'actions/history'),
previewUrl: version.getPreviewUrl(),
revertLabel: t('files_versions', 'Restore'),
canRevert: (this.collection.getFileInfo().get('permissions') & OC.PERMISSION_UPDATE) !== 0
}, version.attributes);
},
/**
* Renders this details view
*/
render: function() {
this.$el.html(this.template({
emptyResultLabel: t('files_versions', 'No other versions available'),
}));
this.$el.find('.has-tooltip').tooltip();
this.$versionsContainer = this.$el.find('ul.versions');
this.delegateEvents();
},
/**
* Returns true for files, false for folders.
*
* @return {bool} true for files, false for folders
*/
canDisplay: function(fileInfo) {
if (!fileInfo) {
return false;
}
return !fileInfo.isDirectory();
}
});
OCA.Versions = OCA.Versions || {};
OCA.Versions.VersionsTabView = VersionsTabView;
})();
|
JavaScript
| 0.000054 |
@@ -4105,24 +4105,62 @@
timestamp),%0A
+%09%09%09%09millisecondsTimestamp: timestamp,%0A
%09%09%09%09humanRea
|
8ec055dbf41ca4da8a271cc3ccf16a523077b9f3
|
fix gulpfile, nodemon watch jsx files
|
gulpfile.babel.js
|
gulpfile.babel.js
|
'use strict';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.config';
import compass from 'gulp-compass';
import minifyCSS from 'gulp-minify-css';
import nodemon from 'gulp-nodemon';
var port = process.env.HOT_LOAD_PORT || 3030;
gulp.task('default', ['webpack-dev-server', 'compass:build', 'watch', 'start']);
gulp.task('build', ['webpack:build', 'compass:build']);
gulp.task('watch', function () {
gulp.watch('./sass/*.scss', ['compass:build']);
});
// noscript scss file build
gulp.task('compass:build', () => {
gulp.src('./sass/noscript.scss')
.pipe(compass({
css: 'public/css',
sass: 'sass'
}))
.pipe(minifyCSS())
.pipe(gulp.dest('public/css'));
});
gulp.task('webpack:build', (callback) => {
webpack(webpackConfig, (err, stats) => {
if (err) throw new gutil.PluginError('webpack:build', err);
gutil.log('[webpack:build]', stats.toString({colors: true}));
callback();
});
});
gulp.task('webpack-dev-server', (callback) => {
new WebpackDevServer(webpack(webpackConfig), {
contentBase: `http://localhost:${port}`,
publicPath: webpackConfig.output.publicPath,
stats: { colors: true },
hot: true,
historyApiFallback: true
}).listen(port, 'localhost', (err, result) => {
if (err) throw new gutil.PluginError('webpack-dev-server', err);
gutil.log('[webpack-dev-server]', `http://localhost:${port}`);
});
});
gulp.task('start', (callback) => {
nodemon({
exec: 'babel-node',
script: 'server.js',
ext: 'js',
ignore: 'public',
env: { 'NODE_ENV': process.env.NODE_ENV }
})
});
|
JavaScript
| 0 |
@@ -1626,16 +1626,20 @@
ext: 'js
+ jsx
',%0A i
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.