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 |
|---|---|---|---|---|---|---|---|
bdb9d0e6473fcef81c770912491ab51c3167a113 | Remove reference to customFooter, which no longer exists | Apps/UseUI/dashboard-client.js | Apps/UseUI/dashboard-client.js | /*
*
* Copyright (C) 2011, The Locker Project
* All rights reserved.
*
* Please see the LICENSE file for more information.
*
*/
var express = require('express'),
connect = require('connect'),
path = require('path'),
async = require('async'),
fs = require('fs'),
socketio = require('socket.io'),
request = require('request');
var logger = require("logger").logger;
var externalBase;
var locker;
module.exports = function(passedLocker, passedExternalBase, listenPort, callback) {
locker = passedLocker;
externalBase = passedExternalBase;
app.listen(listenPort, callback);
};
var app = express.createServer();
app.use(express.cookieParser());
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false
});
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
app.get('/app',
function(req, res) {
var lconfig = require('../../Common/node/lconfig.js');
lconfig.load('../../Config/config.json');
var rev = fs.readFileSync(path.join(lconfig.lockerDir, '/../', 'gitrev.json'), 'utf8');
res.render('app', {
dashboard: lconfig.dashboard,
customFooter: customFooter,
revision: rev.substring(1,11)
});
});
// dumb defaults
var options = { logger: {
info: new Function(),
error: new Function(),
warn: new Function(),
debug: new Function()
}};
var io = socketio.listen(app,options);
app.get('/apps', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
var apps = {contacts: {url : externalBase + '/Me/contactsviewer/', id : 'contactsviewer'},
photos: {url : externalBase + '/Me/photosviewer/', id : 'photosviewer'},
links: {url : externalBase + '/Me/linkalatte/', id : 'linkalatte'},
search: {url : externalBase + '/Me/searchapp/', id : 'searchapp'}};
res.end(JSON.stringify(apps));
});
var eventInfo = {
"link":{"name":"link", "timer":null, "count":0, "new":0, "updated":0},
"contact/full":{"name":"contact", "timer":null, "count":0, "new":0, "updated":0},
"photo":{"name":"photo", "timer":null, "count":0, "new":0, "updated":0}
};
// lame way to track if any browser is actually open right now
var isSomeoneListening = 0;
app.post('/event', function(req, res) {
res.send({}); // any positive response
if(isSomeoneListening == 0) return; // ignore if nobody is around, shouldn't be getting any anyway
if (req && req.body) {
var evInfo = eventInfo[req.body.type];
if (evInfo.timer) {
clearTimeout(evInfo.timer);
}
evInfo.timer = function(ev){ evInfo = ev; return setTimeout(function() {
// stuff changed, go get the newest total to see if it did
request.get({uri:locker.lockerBase+'/Me/'+evInfo.name+'s/state',json:true},function(err,res,body){
if(!body || !body.count || evInfo.count == body.count) return;
io.sockets.emit('event',{"name":evInfo.name, "new":(body.count - evInfo.count), "count":body.count, "updated":body.updated});
evInfo.count = body.count;
evInfo.updated = body.updated;
saveState();
});
}, 2000)}(evInfo); // wrap for a new stack w/ evInfo isolated
}
});
// just snapshot to disk every time we push an event so we can compare in the future
function saveState()
{
var counts = {};
for (var key in eventInfo) {
if (eventInfo.hasOwnProperty(key)) counts[key] = {count:eventInfo[key].count};
}
fs.writeFileSync("state.json", JSON.stringify(counts));
}
// compare last-sent totals to current ones and send differences
function bootState()
{
if(isSomeoneListening > 0) return; // only boot after we've been idle
logger.debug("booting state fresh");
async.forEach(['contacts','links','photos'],function(coll,callback){
logger.debug("fetching "+locker.lockerBase+'/Me/'+coll+'/state '+ JSON.stringify(locker) );
request.get({uri:locker.lockerBase+'/Me/'+coll+'/state',json:true},function(err,res,body){
if(coll == 'links') var evInfo = eventInfo['link'];
if(coll == 'photos') var evInfo = eventInfo['photo'];
if(coll == 'contacts') var evInfo = eventInfo['contact/full'];
evInfo.count = (body && body.count && body.count > 0) ? body.count : 0;
evInfo.updated = (body && body.updated && body.updated > 0) ? body.updated : 0;
callback();
});
},function(){
var last = {
"link":{"count":0},
"contact/full":{"count":0},
"photo":{"count":0}
};
// try to load from file passively
try {
last = JSON.parse(fs.readFileSync('state.json'));
} catch(err) {
}
for(var type in eventInfo) {
// stupd vrbos
if(eventInfo[type].count > last[type].count) io.sockets.emit('event',{"name":eventInfo[type].name, "updated":eventInfo[type].updated, "new":eventInfo[type].count - last[type].count});
}
saveState(); // now that we possibly pushed events, note it
locker.listen("photo","/event");
locker.listen("link","/event");
locker.listen("contact/full","/event");
var counts = {};
for (var key in eventInfo) {
if (eventInfo.hasOwnProperty(key)) counts[eventInfo[key].name] = {count:eventInfo[key].count, updated:eventInfo[key].updated};
}
io.sockets.emit("counts", counts);
});
}
io.sockets.on('connection', function (socket) {
logger.debug("+++++++++++++++");
logger.debug("++++++++++ got new socket.io connection");
logger.debug("+++++++++++++++");
bootState();
isSomeoneListening++;
var counts = {};
for (var key in eventInfo) {
if (eventInfo.hasOwnProperty(key)) counts[eventInfo[key].name] = {count:eventInfo[key].count, updated:eventInfo[key].updated};
}
socket.emit("counts", counts);
socket.on('disconnect', function () {
isSomeoneListening--;
// when nobody is around, don't receive events anymore
if(isSomeoneListening == 0)
{
logger.debug("everybody left, quiesce");
locker.deafen("photo","/event");
locker.deafen("link","/event");
locker.deafen("contact/full","/event");
}
});
});
| JavaScript | 0 | @@ -1230,44 +1230,8 @@
rd,%0A
- customFooter: customFooter,%0A
|
3b95b1734cdfa3b7bb5cb38990265dc1db683ab1 | Use expect.shift instead of building an array of arguments for expect when delegating to the next assertion. | lib/unexpectedMockCouchdb.js | lib/unexpectedMockCouchdb.js | var BufferedStream = require('bufferedstream');
var createMockCouchAdapter = require('./createMockCouchAdapter');
var http = require('http');
var mockCouch = require('mock-couch-alexjeffburke');
var url = require('url');
function generateCouchdbResponse(databases, req, res) {
var responseObject = null;
var couchdbHandler = createMockCouchAdapter();
var couchdb = new mockCouch.MockCouch(couchdbHandler, {});
Object.keys(databases).forEach(function (databaseName) {
couchdb.addDB(databaseName, databases[databaseName].docs || []);
});
// run the handler
couchdbHandler(req, res, function () {});
}
module.exports = {
name: 'unexpected-couchdb',
installInto: function (expect) {
expect.installPlugin(require('unexpected-mitm'));
expect.addAssertion('<any> with couchdb mocked out <object> <assertion>', function (expect, subject, couchdb) {
expect.errorMode = 'nested';
var nextAssertionArgs = this.args.slice(1);
var args = [subject, 'with http mocked out', {
response: generateCouchdbResponse.bind(null, couchdb)
}].concat(nextAssertionArgs);
return expect.apply(expect, args);
});
}
};
| JavaScript | 0 | @@ -958,83 +958,88 @@
-var nextAssertionArgs = this.args.slice(1);%0A var args = %5Bsubject
+return expect(function () %7B%0A return expect.shift();%0A %7D
, 'w
@@ -1149,82 +1149,24 @@
%7D
-%5D.concat(nextAssertionArgs);%0A%0A return expect.apply(expect, args
+, 'not to error'
);%0A
@@ -1172,22 +1172,21 @@
%7D);%0A
-%0A
%7D%0A%7D;%0A
|
0529342dadeeaa9de717efd495a81f7c47b50020 | Fix popupStyle check | wrappers/map.js | wrappers/map.js | 'use strict';
var L = require('../vendor/leaflet.js')
require('../vendor/leaflet.markercluster-src.js')(L)
var EventEmitter = require('events').EventEmitter
var mapTileLayer = require('./tilelayer')
var mediator = require('../lib/mediator')
var nn = require('nevernull')
L.Icon.Default.imagePath = 'http://cdn.leafletjs.com/leaflet-0.7/images'
class Map extends EventEmitter {
/**
* Creates a map with given config
*/
constructor(config) {
this.map = L.map(config.domElementId, config.mapOptions).fitBounds(config.bounds)
this.tileLayers = {}
this.geojsonLayers = {}
this.key = {}
this.dataServices = {}
this.mediator = mediator()
this.map.on('click', (event) => this.emit('click', event))
}
/**
* Adds a tile layer to the map with given config
*/
setTileLayer(name, config) {
this.tileLayers[name] = mapTileLayer(config.url, config)
this.tileLayers[name].addTo(this.map)
}
removeTileLayer(name) {
this.tileLayers[name].removeFrom(this.map)
}
/**
* Add a geojson layer to the map with given config
*/
setGeojsonLayer(name, config) {
var options = {}
var map = this
var layer
if (config.layerStyle)
options.style = (feature) => config.layerStyle(feature.properties)
if (config.listens) {
config.listens.forEach((listenerConfig) => {
map.mediator.register(listenerConfig)
})
}
if (config.popupStyle || config.notifies) {
options.onEachFeature = (feature, layer) => {
layer.on('click', function () {
map.emit('marker.click', feature)
})
if (!config.popupFilter || config.popupFilter(feature)) {
// don't bind the feature popup if it isn't defined in config
if (typeof config.popupStyle(feature.properties) !== 'undefined') {
layer.bindPopup(config.popupStyle(feature.properties))
}
}
if (config.notifies) {
config.notifies.forEach((eventType) => {
layer.on(eventType, () => map.mediator.notify(eventType, name, feature, map))
})
}
}
}
if (config.iconStyle)
options.pointToLayer = (feature, latLng) => L.marker(latLng, { icon: L.icon(config.iconStyle(feature.properties)) })
if (config.geojsonFilter)
options.filter = (feature) => config.geojsonFilter(feature)
if (this.geojsonLayers[name]) {
this.geojsonLayers[name].removeFrom(this.map)
delete this.geojsonLayers[name]
}
// if clustering is defined then add a marker cluster layer
// else add a geoJson layer
if (nn(config)('cluster').val) {
// if an icon is supplied use it
// unless showClusterCount is also specified, then show a DivIcon with supplied config
if (nn(config)('cluster.icon').val) {
if (nn(config)('cluster.icon.showClusterCount').val) {
config.cluster.iconCreateFunction = function (cluster) {
var iconClass = config.cluster.icon.iconClass !== 'undefined' ? config.cluster.icon.iconClass : 'cluster-icon'
config.cluster.icon.html = '<div class="' + iconClass + '"><div class="cluster-count">' + cluster.getChildCount() + '</div></div>'
return L.divIcon(config.cluster.icon)
}
} else {
config.cluster.iconCreateFunction = function () {
return L.icon(config.cluster.icon)
}
}
}
layer = new L.MarkerClusterGroup(config.cluster)
layer.addLayer(L.geoJson(config.geojson, options))
} else {
layer = L.geoJson(config.geojson, options)
}
this.geojsonLayers[name] = layer
}
showGeojsonLayer(name) {
if (this.geojsonLayers[name])
this.geojsonLayers[name].addTo(this.map)
}
hideGeojsonLayer(name) {
if (this.geojsonLayers[name])
this.geojsonLayers[name].removeFrom(this.map)
}
stopDataService(name) {
if (this.dataServices[name])
this.dataServices[name].stop()
}
startDataService(name) {
if (this.dataServices[name])
this.dataServices[name].start()
}
}
module.exports = function (config) {
return new Map(config)
}
| JavaScript | 0.000001 | @@ -1321,16 +1321,17 @@
erties)%0A
+%0A
if (
@@ -1456,24 +1456,25 @@
%7D)%0A %7D%0A
+%0A
if (conf
@@ -1814,15 +1814,8 @@
if (
-typeof
conf
@@ -1831,44 +1831,8 @@
tyle
-(feature.properties) !== 'undefined'
) %7B%0A
@@ -2126,24 +2126,25 @@
%7D%0A %7D%0A
+%0A
if (conf
@@ -2153,24 +2153,24 @@
.iconStyle)%0A
-
option
@@ -2276,24 +2276,25 @@
erties)) %7D)%0A
+%0A
if (conf
|
6e84516cafa972981ec1fc7847cbf1fb51809778 | bump minimum supported ghost version to 1.0.0-rc.1 | lib/utils/resolve-version.js | lib/utils/resolve-version.js | 'use strict';
const semver = require('semver');
const Promise = require('bluebird');
const filter = require('lodash/filter');
const includes = require('lodash/includes');
const yarn = require('./yarn');
const errors = require('../errors');
const MIN_RELEASE = '>= 1.0.0-beta.1';
/**
* Resolves the ghost version to installed based on available NPM versions
* and/or a passed version & any locally installed versions
*
* @param {string} version Any version supplied manually by the user
* @param {string} update Current version if we are updating
* @return Promise<string> Promise that resolves with the version to install
*/
module.exports = function resolveVersion(version, update) {
// If version contains a leading v, remove it
if (version && version.match(/^v[0-9]/)) {
version = version.slice(1);
}
if (version && !semver.satisfies(version, MIN_RELEASE)) {
return Promise.reject(new errors.CliError({
message: 'Ghost-CLI cannot install versions of Ghost less than 1.0.0',
log: false
}));
}
return yarn(['info', 'ghost', 'versions', '--json']).then((result) => {
try {
let versions = JSON.parse(result.stdout).data || [];
versions = filter(versions, function (availableVersion) {
if (update) {
return semver.satisfies(availableVersion, '>' + update);
}
return semver.satisfies(availableVersion, MIN_RELEASE);
});
if (!versions.length) {
return Promise.reject(new errors.CliError({
message: 'No valid versions found.',
log: false
}));
}
if (version && !includes(versions, version)) {
return Promise.reject(new errors.CliError({
message: `Invalid version specified: ${version}`,
log: false
}));
}
return version || versions.pop();
} catch (e) {
return Promise.reject(new errors.CliError({
message: 'Ghost-CLI was unable to load versions from Yarn.',
log: false
}));
}
});
};
| JavaScript | 0 | @@ -277,12 +277,10 @@
0.0-
-beta
+rc
.1';
|
52f072e3e2761a21d28f834bcc00a7437f0f5ebf | Add model.CARD in CardController | js/myapp/card.js | js/myapp/card.js |
// ----------------------------------------------------------------
// Card Class
class CardModel extends SwitchModel {
constructor({
name,
lsKeyView,
triggerSelector,
switchSelector
} = {}) {
super({
name: name,
lsKeyView: lsKeyView,
triggerSelector: triggerSelector,
switchSelector: switchSelector
});
this.NAME = name;
this.CARD_AREA_SELECTOR = '#card-area';
this.$CARD_AREA_SELECTOR = $(this.CARD_AREA_SELECTOR);
this.TEMPLATE_CARD_TABLE_SELECTOR = '#card-table-template';
this.$TEMPLATE_CARD_TABLE_SELECTOR = $(this.TEMPLATE_CARD_TABLE_SELECTOR);
this.CARD_TBODY = '#card-tbody';
this.$CARD_TBODY = $(this.CARD_TBODY);
}
}
class CardView extends SwitchView {
constructor(_model = new CardModel()) {
super(_model);
}
generateCardArea(_alertType = 'success', _message = null, _close = true) {
this.model.$CARD_AREA_SELECTOR.empty();
this.model.$CARD_AREA_SELECTOR.append(Content.getHeader('名刺情報'));
this.generateAlert(this.model.$CARD_AREA_SELECTOR, _alertType, _message, _close);
let template = null;
if (this.model.DOWNLOAD) {
template = this.model.$TEMPLATE_CARD_TABLE_SELECTOR.text();
const compiled = _.template(template);
const model = {};
this.model.$CARD_AREA_SELECTOR.append(compiled(model));
this.model.$CARD_TBODY = $(this.model.CARD_TBODY);
}
}
}
// ----------------------------------------------------------------
// Controller
class CardController extends CommonController {
constructor(_obj) {
super(_obj);
this.model = new CardModel(_obj);
this.view = new CardView(this.model);
this.model.ID = null;
this.model.HASH = null;
this.model.DOWNLOAD = null;
this.downloadCard();
}
setUser(_id = null, _hash = null) {
this.model.ID = _id;
this.model.HASH = _hash;
this.downloadCard(this.model.ID, this.model.HASH)
}
downloadCard(_id = null, _hash = null) {
this.model.DOWNLOAD = false;
this.view.generateLoading(this.model.$CARD_AREA_SELECTOR, '通信中', `ユーザーID ${_id} の名刺データを取得中`);
if (_id != null && _hash != null) {
$.ajax({
url: 'ruby/getCard.rb',
data: {
id: _id,
password: _hash
},
dataType: 'json',
success: (_data) => {
Log.logClass(this.NAME, 'getCard ajax success');
if (Object.keys(_data).length > 0) {
this.model.DOWNLOAD = true;
this.view.generateCardArea('success', `名刺データの取得に成功しました。`);
} else {
this.view.generateCardArea('danger', '名刺データは存在しません。', false);
}
},
error: () => {
Log.logClass(this.NAME, 'getCard ajax failed');
this.view.generateCardArea('danger', 'ajax通信に失敗しました。', false);
}
});
} else {
this.view.generateCardArea('danger', 'ログインしてください。', false);
}
}
}
// ----------------------------------------------------------------
// Event
class CardEvent extends CommonEvent {
constructor({
name = 'Card Event'
} = {})
{
super({
name: name
});
this.NAME = name;
this.CONTROLLER = new CardController({
name: 'Card Switch',
lsKeyView: 'card',
triggerSelector: '#action-card',
switchSelector: '#card-area'
});
}
}
| JavaScript | 0.000001 | @@ -1772,24 +1772,52 @@
OAD = null;%0A
+ this.model.CARD = null;%0A
%0A thi
@@ -2544,16 +2544,53 @@
= true;%0A
+ this.model.CARD = _data;%0A
|
9a4358f6f1726f7834fa009b18ef57c781a5937b | Modify the configuration of fis to remove the useless configurations | fis-conf.js | fis-conf.js | // default settings. fis3 release
// Global start
fis.match('src/ui-p2p-lending.less', {
parser: fis.plugin('less'),
rExt: '.css'
})
fis.match('src/*.less', {
packTo: 'dist/ui-p2p-lending.css'
})
// Global end
// default media is `dev`
// extends GLOBAL config
| JavaScript | 0.000001 | @@ -1,55 +1,4 @@
-// default settings. fis3 release%0A%0A// Global start%0A
fis.
@@ -80,142 +80,46 @@
css'
-%0A%7D)%0A%0Afis.match('src/*.less', %7B%0A packTo: 'dist/ui-p2p-lending.css'%0A%7D)%0A%0A// Global end%0A%0A// default media is %60dev%60%0A%0A// extends GLOBAL config
+,%0A release: 'dist/ui-p2p-lending.css'%0A%7D)
%0A
|
9698103cfa452b083f035ac63426d1a2525575dc | add copyright comments | fis-page.js | fis-page.js | /*
* fis-page
*
* Licensed under the MIT license.
* https://github.com/exp-team/fis-page/blob/master/LICENSE
*/
'use strict';
module.exports = function(fis) {
//TODO
} | JavaScript | 0 | @@ -11,16 +11,53 @@
page%0A *%0A
+ * Copyright (c) 2015 Baidu EXP Team%0A
* Licen
|
abded4b08c2b385dc1c187db73b40acf313c5e9d | fix to loading page | www/js/index.js | www/js/index.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
window.location.replace("#mainpage");
console.log('Received Event: ' + id);
}
};
| JavaScript | 0.000001 | @@ -1513,24 +1513,77 @@
ction(id) %7B%0A
+ $(%22#loadingpage%22).append(%22%3Cdiv%3EDone%3C/div%3E%22);%0A
wind
|
d8ccdfcd4a43df13878e732c04f42fd920bc4d09 | use styled-components instead of styled-jsx | src/pages/button.js | src/pages/button.js | import React from 'react';
class ButtonPage extends React.Component {
static getInitialProps ({ query: { color, collectiveSlug, verb } }) {
return { color, collectiveSlug, verb }
}
render() {
const { color = 'white', collectiveSlug, verb = 'donate' } = this.props;
return (
<div>
<style jsx>{`
:global(body) {
margin: 0;
}
.collect-btn {
width: 300px;
height: 50px;
overflow: hidden;
margin: 0;
padding: 0;
background-repeat: no-repeat;
float:left;
border: none;
background-color: transparent;
cursor: pointer;
}
.collect-btn.contribute {
width: 338px;
}
.donate.collect-btn.blue {
background-image: url(/static/images/buttons/donate-button-blue.svg);
}
.donate.collect-btn.white {
background-image: url(/static/images/buttons/donate-button-white.svg);
}
.contribute.collect-btn.blue {
background-image: url(/static/images/buttons/contribute-button-blue.svg);
}
.contribute.collect-btn.white {
background-image: url(/static/images/buttons/contribute-button-white.svg);
}
.collect-btn:hover {
background-position: 0 -50px;
}
.collect-btn:active {
background-position: 0 -100px;
}
.collect-btn:focus {
outline: 0;
}
.collect-btn.hover {
background-position: 0 -100px;
}
`}</style>
<a type="button" className={`collect-btn ${color} ${verb}`} target="_blank" rel="noopener noreferrer" href={`https://opencollective.com/${collectiveSlug}/${verb}`} />
</div>
);
}
}
export default ButtonPage;
| JavaScript | 0.000193 | @@ -24,886 +24,158 @@
t';%0A
-%0Aclass ButtonPage extends React.Component %7B%0A static getInitialProps (%7B query: %7B color, collectiveSlug, verb %7D %7D) %7B%0A return %7B color, collectiveSlug, verb %7D%0A %7D%0A%0A render() %7B%0A const %7B color = 'white', collectiveSlug, verb = 'donate' %7D = this.props;%0A%0A return (%0A %3Cdiv%3E%0A %3Cstyle jsx%3E%7B%60%0A :global(body) %7B%0A margin: 0;%0A %7D%0A%0A .collect-btn %7B %0A width: 300px;%0A height: 50px;%0A overflow: hidden;%0A margin: 0;%0A padding: 0;%0A background-repeat: no-repeat;%0A float:left;%0A border: none;%0A background-color: transparent;%0A cursor: pointer;%0A %7D%0A%0A .collect-btn.contribute %7B%0A width: 338px;%0A %7D%0A%0A .donate.collect-btn.blue %7B%0A background-image:
+import styled from 'styled-components';%0A%0Aconst CollectButton = styled.a%60%0A background-color: transparent;%0A background-image: $%7B(%7B color, verb %7D) =%3E %60
url(
@@ -197,30 +197,31 @@
buttons/
-donate
+$%7Bverb%7D
-button-
blue.svg
@@ -216,492 +216,245 @@
ton-
-blue.svg);%0A %7D%0A%0A .donate.collect-btn.white %7B%0A background-image: url(/static/images/buttons/donate-button-white.svg);%0A %7D%0A%0A .contribute.collect-btn.blue %7B%0A background-image: url(/static/images/buttons/contribute-button-blue.svg);%0A %7D%0A%0A .contribute.collect-btn.white %7B%0A background-image: url(/static/images/buttons/contribute-button-white.svg);%0A %7D%0A%0A .collect-btn
+$%7Bcolor%7D.svg)%60%7D;%0A background-repeat: no-repeat;%0A cursor: pointer;%0A display: block;%0A float: left;%0A height: 50px;%0A margin: 0;%0A overflow: hidden;%0A padding: 0;%0A width: $%7B(%7B verb %7D) =%3E verb === 'contribute' ? '338px' : '300px'%7D;%0A%0A &
:hov
@@ -454,34 +454,24 @@
&:hover %7B%0A
-
backgrou
@@ -498,44 +498,14 @@
;%0A
- %7D%0A .collect-btn
+%7D%0A%0A &
:act
@@ -510,26 +510,16 @@
ctive %7B%0A
-
back
@@ -551,44 +551,14 @@
;%0A
- %7D%0A .collect-btn
+%7D%0A%0A &
:foc
@@ -562,26 +562,16 @@
focus %7B%0A
-
outl
@@ -584,201 +584,315 @@
;%0A
- %7D%0A%0A .collect-btn.hover %7B%0A background-position: 0 -100px;%0A %7D%0A %60%7D%3C/style%3E%0A %3Ca type=%22button%22 className=%7B%60collect-btn $%7Bcolor%7D $%7Bverb%7D%60%7D
+%7D%0A%60;%0A%0Aclass ButtonPage extends React.Component %7B%0A static getInitialProps (%7B query: %7B color, collectiveSlug, verb %7D %7D) %7B%0A return %7B color, collectiveSlug, verb %7D%0A %7D%0A%0A render() %7B%0A const %7B color = 'white', collectiveSlug, verb = 'donate' %7D = this.props;%0A%0A return (%0A %3CCollectButton type=%22button%22
tar
@@ -996,22 +996,35 @@
%7D%60%7D
-/%3E%0A %3C/div
+color=%7Bcolor%7D verb=%7Bverb%7D /
%3E%0A
|
61fe248104b1623c67c00c3e11e9f7f6d7a6fa29 | this ad-hoc log level reading is bollocks | modules/module-operator.js | modules/module-operator.js | // Channel op module
var Q = require('q');
var _ = require('underscore');
var logger = new require('toplog')({concern: 'operator'});
exports.type = 'command';
var util = null;
exports.listAll = function() {
return Object.keys(exports.getHelp());
};
exports.getHelp = function() {
return {
'*': 'can I use admin stuff?',
'op': '`op [#channel] <target>` - make someone a channel operator',
'deop': '`deop [#channel] <target>` - remove someone\'s channel operator powers',
'voice': '`voice [#channel] <target>` - add voice to someone',
'devoice': '`devoice [#channel] <target>` - remove voice from someone',
'ban': '`ban [#channel] <target>` - ban someone from the channel',
'unban': '`unban [#channel] <target>` - unban someone from the channel',
'kick': '`kick [#channel] <target>` - kicks the target off the channel',
'mode': '`mode [#channel] <mode> <target> ` - sets a bunch of modes on the target',
'quiet': '`quiet [#channel] <target>` - sets the +q flag on a target, like a ban except they can join',
'invite': '`invite [#channel] <target>` - invite the target to the channel',
'topic': '`topic [#channel] <topic...>` - set the channel topic'
};
};
exports.listener = function(line, words, respond, util) {
var call = this.event.slice(9);
// 1. *I* have to be ops
util.isOperatorIn(util.config.get('nick', 'boxnode'), line.params[0]).done(function(y) {
if (!y) {
if (util.config.get('loud', false))
respond(util.config.get('modules.operator.not_an_op', 'I am not an op!'));
return;
}
// 2. the caller has to be permitted to do the thing
var permitted = util.matchesHostname(util.config.get('owner'), line.hostmask);
permitted = permitted || _.any(util.config.get('modules.operator.authorized'), function(ea) {
return util.matchesHostname(ea, line.hostmask);
});
logger.verbose('caller permitted: their hostname is allowed');
var oppromise, voicepromise;
if (util.config.get('modules.operator.ops_allowed', false)) {
var oppromise = util.isOperatorIn(line.nick, line.params[0])
.then(function(y) {
permitted = permitted || y;
logger.verbose('caller permitted: ops_allowed && they\'re an op');
});
} else {
oppromise = Q.defer();
oppromise.resolve();
oppromise = oppromise.promise;
}
if (util.config.get('modules.operator.voices_allowed', false)) {
var voicepromise = util.isVoiceIn(line.nick, line.params[0])
.then(function(y) {
permitted = permitted || y;
logger.verbose('caller permitted: voices_allowed && they\'re a voice');
});
} else {
voicepromise = Q.defer();
voicepromise.resolve();
voicepromise = voicepromise.promise;
}
Q.all([voicepromise, oppromise]).then(function() {
if (!permitted) {
if (util.config.get('modules.operator.loud'))
respond(util.config.get('modules.operator.not_allowed') || 'You are not allowed to do this!');
return;
}
logger.debug('Performing op command: ' + call)
// Actually do the shit they told us to
var command = call;
words.shift();
var channel = words.shift(), target;
if (!util.isChannel(channel)) {
target = channel;
channel = util.params[0];
}
target = target || words.shift() || line.hostmask;
switch (command) {
case 'op':
respond.MODE(channel, '+o', target);
break;
case 'deop':
respond.MODE(channel, '-o', target);
break;
case 'voice':
respond.MODE(channel, '+v', target);
break;
case 'devoice':
respond.MODE(channel, '-v', target);
break;
}
});
});
};
exports.init = function(u, alias) {
alias('op', 'operator.op');
util = u;
logger.currprops.loglevel = util.config.get('loglevels.operator', 'VERBOSE');
};
| JavaScript | 0.999999 | @@ -1,8 +1,9 @@
+2
// Chann
@@ -3938,16 +3938,19 @@
= u;%0A%0A
+ //
logger.
|
e39c79203483bae56b0ece785eb6b03e61d84c1b | add temp constant | index.android.js | index.android.js | var React = require('react-native');
var { requireNativeComponent, PropTypes, NativeModules, View } = React;
var ReactNativeCameraModule = NativeModules.ReactCameraModule;
var ReactCameraView = requireNativeComponent('ReactCameraView', {
name: 'ReactCameraView',
propTypes: {
...View.propTypes,
scaleX: PropTypes.number,
scaleY: PropTypes.number,
translateX: PropTypes.number,
translateY: PropTypes.number,
rotation: PropTypes.number,
type: PropTypes.oneOf(['back', 'front'])
}
});
var constants = {
'Aspect': {
'stretch': 'stretch',
'fit': 'fit',
'fill': 'fill'
},
'BarCodeType': {
'upca': 'upca',
'upce': 'upce',
'ean8': 'ean8',
'ean13': 'ean13',
'code39': 'code39',
'code93': 'code93',
'codabar': 'codabar',
'itf': 'itf',
'rss14': 'rss14',
'rssexpanded': 'rssexpanded',
'qr': 'qr',
'datamatrix': 'datamatrix',
'aztec': 'aztec',
'pdf417': 'pdf417'
},
'Type': {
'front': 'front',
'back': 'back'
},
'CaptureMode': {
'still': 'still',
'video': 'video'
},
'CaptureTarget': {
'memory': 'base64',
'disk': 'disk',
'cameraRoll': 'gallery'
},
'Orientation': {
'auto': 'auto',
'landscapeLeft': 'landscapeLeft',
'landscapeRight': 'landscapeRight',
'portrait': 'portrait',
'portraitUpsideDown': 'portraitUpsideDown'
},
'FlashMode': {
'off': 'off',
'on': 'on',
'auto': 'auto'
},
'TorchMode': {
'off': 'off',
'on': 'on',
'auto': 'auto'
}
};
var ReactCameraViewWrapper = React.createClass({
getDefaultProps() {
return ({
type: constants.Type.back,
captureTarget: constants.CaptureTarget.cameraRoll
});
},
render () {
return (
<ReactCameraView {...this.props}></ReactCameraView>
);
},
capture (options, callback) {
var component = this;
var defaultOptions = {
type: component.props.type,
target: component.props.captureTarget,
sampleSize: 0,
title: '',
description: ''
};
return new Promise(function(resolve, reject) {
if (!callback && typeof options === 'function') {
callback = options;
options = {};
}
ReactNativeCameraModule.capture(Object.assign(defaultOptions, options || {}), function(err, data) {
if (typeof callback === 'function') callback(err, data);
err ? reject(err) : resolve(data);
});
});
}
});
ReactCameraViewWrapper.constants = constants;
module.exports = ReactCameraViewWrapper;
| JavaScript | 0.000009 | @@ -1292,16 +1292,40 @@
'disk',%0A
+ 'temp': 'temp',%0A
|
670cd621eee55e914db479de17931e910c0611bd | Update index.js | www/js/index.js | www/js/index.js | //listen for deviceready event and launch onDeviceReady when phonegap is fully running
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
initializeApp(); //launch the initializeApp function
}
function initializeApp(){
// add a watch for compass.
navigator.compass.watchHeading(onCompassSuccess, onCompassError);
}
function onCompassSuccess(heading) {
// display the bearing
var heading = heading.magneticHeading.toFixed(0);
var color = hsvToRgb(heading);
var cssColor = "rgb(" + color.join() + ")";
document.getElementById("innerLeft").style.backgroundColor = cssColor;
};
function onCompassError(error) {
alert('CompassError: ' + error.code);
};
/**
* HSV to RGB color conversion
*
* H runs from 0 to 360 degrees
* S and V run from 0 to 100
*
* Ported from the excellent java algorithm by Eugene Vishnevsky at:
* http://www.cs.rit.edu/~ncs/color/t_convert.html
*/
function hsvToRgb(h, s, v) {
var r, g, b;
var i;
var f, p, q, t;
// Make sure our arguments stay in-range
h = Math.max(0, Math.min(360, h));
s = Math.max(0, Math.min(100, s));
v = Math.max(0, Math.min(100, v));
// We accept saturation and value arguments from 0 to 100 because that's
// how Photoshop represents those values. Internally, however, the
// saturation and value are calculated from a range of 0 to 1. We make
// That conversion here.
s /= 100;
v /= 100;
if(s == 0) {
// Achromatic (grey)
r = g = b = v;
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
h /= 60; // sector 0 to 5
i = Math.floor(h);
f = h - i; // factorial part of h
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch(i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default: // case 5:
r = v;
g = p;
b = q;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
} | JavaScript | 0.000002 | @@ -362,24 +362,62 @@
sError);%0A%7D%0A%0A
+var saturation = 50;%0Avar value = 50;%0A%0A
function onC
@@ -476,23 +476,21 @@
var
-heading
+value
= headi
@@ -516,17 +516,17 @@
toFixed(
-0
+2
);%0A v
@@ -552,16 +552,35 @@
(heading
+, saturation, value
);%0A v
@@ -697,16 +697,235 @@
sColor;%0A
+ document.getElementById(%22innerLeft%22).style.borderColor = cssColor;%0A document.getElementById(%22innerRight%22).style.backgroundColor = cssColor;%0A document.getElementById(%22innerRight%22).style.borderColor = cssColor;%0A
%7D;%0A%0A%0Afun
@@ -2723,8 +2723,9 @@
255)%5D;%0A%7D
+%0A
|
55cb8fb6429e444fcf6991631121e573f65cddf2 | validate that id must be a hex value | modules/user/view/route.js | modules/user/view/route.js | 'use strict';
const handler = require('./handler');
module.exports = [
{
method: 'GET',
path: '/recipe/manage-users',
handler: handler.redirect,
config: {
description: 'User Management',
plugins: {
lout: false
}
}
},
{
method: 'GET',
path: '/recipe/manage-users/list',
handler: handler.list,
config: {
plugins: {
lout: false
}
}
},
{
method: 'GET',
path: '/recipe/manage-users/edit/{id}',
handler: handler.view,
config: {
plugins: {
lout: false
}
}
}
];
| JavaScript | 0.000011 | @@ -45,16 +45,44 @@
ndler');
+%0Aconst Joi = require('joi');
%0A%0Amodule
@@ -712,32 +712,158 @@
lout: false%0A
+ %7D,%0A validate: %7B%0A params: %7B%0A id: Joi.string().hex()%0A %7D%0A
%7D%0A
|
500bacd7a6ce7b00bbf168319edfa0acfeed528c | Add code to send error info from client to kadira server | lib/client/kadira.js | lib/client/kadira.js |
Kadira = {};
Kadira.options = __meteor_runtime_config__.kadira;
if(Kadira.options && Kadira.options.endpoint) {
Kadira.syncedDate = new Ntp(Kadira.options.endpoint);
Kadira.syncedDate.sync();
}
| JavaScript | 0 | @@ -193,8 +193,847 @@
nc();%0A%7D%0A
+%0A/**%0A * Send error metrics/traces to kadira server%0A * @param %7BObject%7D payload Contains browser info and error traces%0A */%0Afunction sendPayload (payload) %7B%0A var retryCount = 0;%0A var endpoint = Kadira.options.endpoint + '/errors';%0A var retry = new Retry(%7B%0A minCount: 0,%0A baseTimeout: 1000*5,%0A maxTimeout: 1000*60,%0A %7D);%0A%0A tryToSend();%0A%0A function tryToSend() %7B%0A if(retryCount++ %3C 5) %7B%0A retry.retryLater(retryCount++, sendPayload);%0A %7D else %7B%0A console.warn('Error sending error traces to kadira server');%0A %7D%0A %7D%0A%0A function sendPayload () %7B%0A $.ajax(%7Burl: endpoint, data: payload, error: tryToSend%7D);%0A %7D%0A%0A%7D%0A%0Afunction addBrowserInfo (errorInfo) %7B%0A _(errorInfo).extend(%7B%0A appId: Kadira.options.appId,%0A browser: window.navigator.userAgent,%0A userId: Meteor.userId,%0A randomId: Meteor.uuid(),%0A %7D);%0A%7D%0A
|
2026a194d16b6fc2b4a8a61075ce6b4c5f1e109f | rewrite test cases to use `beforeEach` | test/strategy/DebugConfigStrategyTest.js | test/strategy/DebugConfigStrategyTest.js | 'use strict';
var common = require('../common');
var assert = common.assert;
var strategy = require('../../lib/strategy');
var DebugConfigStrategy = strategy.DebugConfigStrategy;
function MockLogger(listener) {
this.listener = listener;
}
MockLogger.prototype.debug = function (message) {
this.listener('debug', message);
};
describe('DebugConfigStrategy', function () {
var mockLogger;
var testSection;
var testConfig;
var testStrategy;
var testListener;
var loggedTestMessages = [];
before(function () {
testSection = 'test';
testConfig = { abc: '123' };
testListener = function onMessageLogged(type, message) {
loggedTestMessages.push({ type: type, message: message });
};
mockLogger = new MockLogger(testListener);
testStrategy = new DebugConfigStrategy(mockLogger, testSection);
});
describe('when processing', function () {
it('should log debug message', function (done) {
testStrategy.process(testConfig, function (err, config) {
assert.equal(loggedTestMessages.length, 1);
assert.deepEqual(loggedTestMessages[0], { type: 'debug', message: 'test:\n' + JSON.stringify(testConfig, null, 4) + '\n' });
done();
});
});
it('should call callback with provided config', function (done) {
testStrategy.process(testConfig, function (err, config) {
assert.notOk(err);
assert.deepEqual(config, testConfig);
done();
});
});
})
});
| JavaScript | 0 | @@ -856,23 +856,34 @@
be('
-when
+.
process
-ing
+(config, callback)
', f
@@ -903,39 +903,44 @@
-it('should log debug message',
+var returnedConfig;%0A%0A beforeEach(
func
@@ -1011,32 +1011,151 @@
rr, config) %7B%0A
+ returnedConfig = config;%0A%0A done(err);%0A %7D);%0A %7D);%0A%0A it('should log debug message', function () %7B%0A
assert.equ
@@ -1188,18 +1188,16 @@
th, 1);%0A
-
as
@@ -1323,34 +1323,8 @@
%7D);%0A
- done();%0A %7D);%0A
@@ -1394,109 +1394,12 @@
on (
-done
) %7B%0A
- testStrategy.process(testConfig, function (err, config) %7B%0A assert.notOk(err);%0A
@@ -1417,17 +1417,25 @@
epEqual(
-c
+returnedC
onfig, t
@@ -1450,34 +1450,8 @@
g);%0A
- done();%0A %7D);%0A
@@ -1458,13 +1458,14 @@
%7D);%0A %7D)
+;
%0A%7D);%0A
|
003b0e721f2c7a181bc3d514848b9e9353a9a5c5 | Fix bamboo location. | js/Objects.js | js/Objects.js | var VeggieWar = VeggieWar || {};
VeggieWar.Bamboo = function (game, location) {
this.game = game.game;
this.veggie = game;
this.location = location;
this.GROW_SPEED = 2000;
this.bamboo = null;
};
VeggieWar.Bamboo.prototype = {
isOccupied: function() {
return this.bamboo != null;
},
spawn: function() {
this.bamboo = this.game.add.sprite(this.location.x, this.location.y, 'bamboo', 0, this.veggie.bamboos);
this.bamboo.anchor.setTo(0.5, 1.0);
this.bamboo.scale.setTo(0.5, 0.01);
this.bamboo.me = this;
this.game.physics.arcade.enable(this.bamboo);
this.game.sound.play('s_grow');
this.bamboo.body.allowRotation = true;
this.game.add.tween(this.bamboo.scale).to({x: 1, y: 1}, this.GROW_SPEED, Phaser.Easing.Quadratic.InOut).start();
},
destroy: function() {
if(this.bamboo == null) {
return false;
}
this.game.add.tween(this.bamboo.body).to({angularVelocity: 1000}, this.GROW_SPEED, Phaser.Easing.Quadratic.InOut).start().onComplete.add(function() {
this.kill();
}, this.bamboo);
this.bamboo = null;
return true;
}
}
| JavaScript | 0.000002 | @@ -940,16 +940,118 @@
%7D%0A%0A
+ this.bamboo.anchor.setTo(0.5, 0.5);%0A this.bamboo.position.y -= this.bamboo.height / 2;%0A
|
aa688e6d5d58eb1a5822c02a9289282acbfb1e6a | fix minor buffering issue | js/alexcam.js | js/alexcam.js | /*global $, jQuery, console, LocalMediaStream, MediaStreamRecorder */
var mirror = {};
function playbackVideo(stream) {
'use strict';
var video;
video = document.querySelector('video');
if (stream instanceof LocalMediaStream) {
video.src = window.URL.createObjectURL(stream); // initial page playback
} else {
video.src = mirror.recorded_videos[0]; // the unending stream of delayed videos
video.onended = function () {
if (mirror.delayed === true) {
playbackVideo(true);
}
};
}
}
function recordVideo(stream) {
'use strict';
mirror.recorder = new MediaStreamRecorder(stream); // eventually move this into the app itself
mirror.recorder.mimeType = 'video/webm';
mirror.recorder.ondataavailable = function (blob) {
mirror.recorded_videos.push(window.URL.createObjectURL(blob));
if (mirror.recorded_videos.length > 2) {
window.URL.revokeObjectURL(mirror.recorded_videos[0]);
mirror.recorded_videos.shift();
}
};
mirror.recorder.start(mirror.delay * 500);
}
function delayedStream(stream) {
'use strict';
if (mirror.recorded_videos < 2) {
$("#delay").button("option", "label", "Buffering...");
setTimeout(delayedStream, mirror.delay * 500);
return (false);
}
// In case it was set to Buffering..., or it's delayed
$("#delay").button("option", "label", "Resume Normal Playback");
playbackVideo(true);
}
function startVideoStream() {
'use strict';
// Attempt to get ahold of the media extension (webrtc)
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({audio: false, video: true}, function (stream) {
mirror.stream = stream;
playbackVideo(stream);
recordVideo(stream);
}, function () {
document.querySelector('body').innerHTML = "<p>sorry, no media support</p>";
});
}
$(document).ready(function () {
'use strict';
var i;
mirror.delayed = false; // set the mirror as not being delayed
mirror.defaultdelay = 5;
mirror.delay = mirror.defaultdelay;
mirror.recorded_videos = [];
$("#delay").button().on("click", function () {
if (mirror.delayed === true) {
mirror.delayed = false;
$("#delay").button("option", "label", "Delay Playback " + mirror.delay + " Seconds");
playbackVideo(mirror.stream);
} else {
mirror.delayed = true;
delayedStream(mirror.stream);
}
});
$("#seconds").slider({
min: 1,
max: 30,
value: mirror.defaultdelay,
create: function () {
mirror.delay = $("#seconds").slider("option", "value");
$("#delay").button("option", "label", "Delay Playback " + mirror.delay + " Seconds");
},
change: function () {
mirror.delay = $("#seconds").slider("option", "value");
$("#delay").button("option", "label", "Delay Playback " + mirror.delay + " Seconds");
// Jump to normal playback, stop the recorder, delete all previously recorded videos, and then start buffering again
playbackVideo(mirror.stream);
mirror.recorder.stop();
for (i = 0; i < mirror.recorded_videos.length; i += 1) {
window.URL.revokeObjectURL(mirror.recorded_videos[i]);
}
mirror.recorded_videos = [];
recordVideo(mirror.stream);
}
});
// load the default video stream on and request permissions, on page load
startVideoStream();
});
| JavaScript | 0.000001 | @@ -1217,32 +1217,17 @@
Stream,
-mirror.delay * 5
+1
00);%0A
|
5fe9ae344085416fe83759ac5bc929c43e93a80e | implement a js alert if you don't pick a state. closes #423. closes #422 | www/js/stack.js | www/js/stack.js | var $welcomeScreen = null;
var $welcomeButton = null;
var $statePickerScreen = null;
var $statePickerSubmitButton = null;
var $statePickerForm = null;
var $header = null;
var $headerControls = null;
var $fullScreenButton = null;
var stack = [];
var nextStack = [];
var currentSlide = 0;
var isRotating = false;
var state = null;
var $audioPlayer = null;
var $stack = null;
var timer = null;
var resizeSlide = function(slide) {
var $w = $(window).width();
var $h = $(window).height();
slide.width($w);
slide.height($h);
}
var rotateSlide = function() {
console.log('Rotating to next slide');
isRotating = true;
currentSlide += 1;
if (currentSlide >= stack.length) {
if (nextStack.length > 0) {
console.log('Switching to new stack');
stack = nextStack;
nextStack = [];
}
currentSlide = 0;
}
if (stack[currentSlide]['slug'] === 'state') {
slide_path = 'slides/state-' + state + '.html';
} else {
slide_path = 'slides/' + stack[currentSlide]['slug'] + '.html';
}
$.ajax({
url: APP_CONFIG.S3_BASE_URL + '/' + slide_path,
success: function(data) {
var $oldSlide = $('#stack').find('.slide');
var $newSlide = $(data);
$('#stack').append($newSlide);
resizeSlide($newSlide)
$oldSlide.fadeOut(function(){
$(this).remove();
});
$newSlide.fadeIn(function(){
console.log('Slide rotation complete');
setTimeout(rotateSlide, APP_CONFIG.SLIDE_ROTATE_INTERVAL * 1000);
});
}
});
}
function getStack() {
console.log('Updating the stack');
$.ajax({
url: APP_CONFIG.S3_BASE_URL + '/live-data/stack.json',
dataType: 'json',
success: function(data) {
nextStack = data;
console.log('Stack update complete');
if (!isRotating) {
rotateSlide();
}
setTimeout(getStack, APP_CONFIG.STACK_UPDATE_INTERVAL * 1000);
}
});
}
var onWelcomeButtonClick = function() {
$welcomeScreen.hide();
$statePickerScreen.show();
resizeSlide($statePickerScreen);
$('.state-selector').chosen({max_selected_options: 1});
}
var onFullScreenButtonClick = function() {
var elem = document.getElementById("stack");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
var onMouseMove = function() {
$header.hide();
$headerControls.show();
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onMouseEnd, 200);
}
var onMouseEnd = function() {
if (!($headerControls.data('hover'))) {
console.log($headerControls.data('hover'));
$header.show();
$headerControls.hide();
}
}
var onControlsHover = function() {
$headerControls.data('hover', true);
$header.hide();
$headerControls.show();
}
var offControlsHover = function() {
$headerControls.data('hover', false);
$headerControls.hide();
$header.show();
}
var setUpAudio = function() {
$audioPlayer.jPlayer({
ready: function () {
$(this).jPlayer('setMedia', {
mp3: 'http://nprdmp.ic.llnwd.net/stream/nprdmp_live01_mp3'
}).jPlayer('pause');
},
swfPath: 'js/lib',
supplied: 'mp3',
loop: false,
});
}
var onStatePickerSubmit = function(e) {
e.preventDefault();
state = $('.state-selector').val();
$.cookie('state', state);
$statePickerScreen.hide();
$stack.show();
getStack();
$('body').on('mousemove', onMouseMove);
$headerControls.hover(onControlsHover, offControlsHover);
$audioPlayer.jPlayer("play");
}
$(document).ready(function() {
$welcomeScreen = $('.welcome');
resizeSlide($welcomeScreen);
$welcomeButton = $('.welcome-button')
$audioPlayer = $('#pop-audio');
$statePickerScreen = $('.state-picker');
$welcomeSubmitButton = $('.state-picker-submit');
$statePickerForm = $('form.state-picker-form');
$stack = $('.stack');
$header = $('.results-header');
$headerControls = $('.header-controls');
$fullScreenButton = $('.fullscreen p');
$(window).resize(function() {
var thisSlide = $('.slide');
resizeSlide(thisSlide);
});
$welcomeButton.on('click', onWelcomeButtonClick);
$statePickerForm.submit(onStatePickerSubmit);
$fullScreenButton.on('click', onFullScreenButtonClick);
setUpAudio();
});
| JavaScript | 0.000022 | @@ -3788,24 +3788,113 @@
or').val();%0A
+%0A if (!(state)) %7B%0A alert(%22Please pick a state!%22);%0A return false;%0A %7D%0A%0A
$.cookie
|
3d6aaf0e1fc68d17211a82d0f8a2daeba42cae2a | Fix a bug with theme.js | www/js/theme.js | www/js/theme.js | (function () {
var c = document.cookie.split(";").map(function (s) {
return s.trim();
});
var theme = "/css/themes/slate.css";
for (var i = 0; i < c.length; i++) {
if (c[i].indexOf("cytube-theme=") === 0) {
theme = c[i].split("=")[1];
break;
}
}
if (theme == null || !theme.match(/^\/css\/themes\/\w+.css$/)) {
return;
}
if (theme !== "/css/themes/slate.css") {
console.log("THEME COOKIE:", theme);
var cur = document.getElementById("usertheme");
cur.parentNode.removeChild(cur);
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", theme);
css.setAttribute("id", "usertheme");
document.head.appendChild(css);
}
})();
| JavaScript | 0.000012 | @@ -332,11 +332,11 @@
es%5C/
-%5Cw+
+.+?
.css
|
6e9f49c8fc4ef2a23fe78b9f66322fabe1b0bc3a | add correct order of nitnem baanies | js/baanies.js | js/baanies.js | module.exports = [
'Japji'
,'Jaap Sahib'
,'Anand Sahib'
,'Tva Prasad Svaye'
,'Kabyo Bach Baynti Chaupai'
,'Rehiras'
,'Kirtan Sohila'
,'Ardas'
,'Arti'
,'Asa Di Var'
,'Baareh Maahaa'
,'Basant Ki Var'
,'Chandi Di Var'
,'Lawa'
,'Raag Mala'
,'Shabad Hazarai Patsahi 10'
,'Shabad Hazarey'
,'Slok Mahala 9'
,'Sukhmani Sahib'
];
| JavaScript | 0.999999 | @@ -42,25 +42,8 @@
ib'%0A
- ,'Anand Sahib'%0A
,'
@@ -91,16 +91,33 @@
haupai'%0A
+ ,'Anand Sahib'%0A
,'Rehi
|
25cfd4b07dd543d52a70dfad6b54ebc878edb572 | Convert Auth plugin to onCommand | src/plugins/Auth.js | src/plugins/Auth.js | import Plugin from "./../Plugin";
import Util from "./../Util";
import Auth from "./../helpers/Auth";
export default class AuthPlugin extends Plugin {
static get plugin() {
return {
name: "Auth",
description: "Plugin to handle authentication",
help: "",
visibility: Plugin.Visibility.VISIBLE,
type: Plugin.Type.SPECIAL
};
}
onText(message, reply) {
const author = message.from.id;
const chat = message.chat.id;
if (message.text === "/modlist") {
return reply({
type: "text",
text: JSON.stringify(Auth.getMods(chat))
});
}
if (message.text === "/adminlist") {
return reply({
type: "text",
text: JSON.stringify(Auth.getAdmins(chat))
});
}
// The code from here on is admin-only.
if (!Auth.isAdmin(author, chat)) return;
var args = Util.parseCommand(message.text, "addmod");
if (args) {
const modId = Number(args[1]);
Auth.addMod(modId, chat);
reply({
type: "text",
text: "Done."
});
return;
}
args = Util.parseCommand(message.text, "addadmin");
if (args) {
const adminId = Number(args[1]);
Auth.addAdmin(adminId, chat);
reply({
type: "text",
text: "Done."
});
return;
}
args = Util.parseCommand(message.text, "delmod");
if (args) {
const userId = Number(args[1]);
Auth.removeMod(userId, chat);
reply({
type: "text",
text: "Done."
});
return;
}
args = Util.parseCommand(message.text, "deladmin");
if (args) {
const userId = Number(args[1]);
Auth.removeAdmin(userId, chat);
reply({
type: "text",
text: "Done."
});
return;
}
}
} | JavaScript | 0.999247 | @@ -420,16 +420,17 @@
ext(
+%7B
message,
rep
@@ -425,16 +425,32 @@
message,
+ command, args%7D,
reply)
@@ -529,25 +529,24 @@
hat.id;%0A
-%0A
if (mess
@@ -541,39 +541,82 @@
-if (message.text ===
+let targetId = args%5B0%5D;%0A%0A switch (command) %7B%0A case
%22
-/
modlist%22
) %7B%0A
@@ -607,27 +607,25 @@
se %22modlist%22
-) %7B
+:
%0A
@@ -755,42 +755,14 @@
-%7D%0A%0A if (message.text ===
+case
%22
-/
admi
@@ -767,19 +767,17 @@
minlist%22
-) %7B
+:
%0A
@@ -901,27 +901,16 @@
%7D);%0A
- %7D%0A%0A
@@ -949,16 +949,43 @@
n-only.%0A
+ case %22addmod%22:%0A
@@ -1030,134 +1030,8 @@
n;%0A%0A
- var args = Util.parseCommand(message.text, %22addmod%22);%0A if (args) %7B%0A const modId = Number(args%5B1%5D);%0A%0A
@@ -1050,19 +1050,22 @@
.addMod(
-mod
+target
Id, chat
@@ -1072,32 +1072,39 @@
);%0A%0A
+return
reply(%7B%0A
@@ -1183,77 +1183,12 @@
- return;%0A %7D%0A%0A args = Util.parseCommand(message.text,
+case
%22ad
@@ -1190,26 +1190,25 @@
e %22addadmin%22
-);
+:
%0A if
@@ -1208,63 +1208,51 @@
-if (args) %7B%0A const adminId = Number(args%5B1%5D)
+ if (!Auth.isAdmin(author, chat)) return
;%0A%0A
@@ -1276,21 +1276,22 @@
ddAdmin(
-admin
+target
Id, chat
@@ -1298,32 +1298,39 @@
);%0A%0A
+return
reply(%7B%0A
@@ -1409,77 +1409,12 @@
- return;%0A %7D%0A%0A args = Util.parseCommand(message.text,
+case
%22de
@@ -1418,19 +1418,22 @@
%22delmod%22
-);%0A
+:%0A
@@ -1440,58 +1440,43 @@
if (
-args) %7B%0A const userId = Number(args%5B1%5D)
+!Auth.isAdmin(author, chat)) return
;%0A%0A
@@ -1501,20 +1501,22 @@
moveMod(
-user
+target
Id, chat
@@ -1523,32 +1523,39 @@
);%0A%0A
+return
reply(%7B%0A
@@ -1634,77 +1634,12 @@
- return;%0A %7D%0A%0A args = Util.parseCommand(message.text,
+case
%22de
@@ -1645,19 +1645,22 @@
eladmin%22
-);%0A
+:%0A
@@ -1667,58 +1667,43 @@
if (
-args) %7B%0A const userId = Number(args%5B1%5D)
+!Auth.isAdmin(author, chat)) return
;%0A%0A
@@ -1734,12 +1734,14 @@
min(
-user
+target
Id,
@@ -1760,16 +1760,23 @@
+return
reply(%7B%0A
@@ -1843,32 +1843,49 @@
%7D);%0A
+ default:%0A
retu
|
7ab812289206f994448522f733b6af5a0c679a14 | use forEach vs for loop | astrology.js | astrology.js | #!/usr/bin/env node
var github = require('octonode');
var client = github.client(process.argv[2]);
var ghme = client.me();
var ghsearch = client.search();
var repository = require('./repository.json');
if(process.argv.length < 3) {
return console.log('Please pass access token in argument');
}
for(var i = 0; i < repository.length; i++) {
ghsearch.repos({
q: 'repo:' + repository[i],
sort: 'created',
order: 'asc'
}, function(err, data) {
if(err) throw Error('Unable to get repository list', err);
if(data){
ghme.star(data.items[0].full_name);
}
});
}
| JavaScript | 0 | @@ -296,49 +296,40 @@
%0A%7D%0A%0A
-for(var i = 0; i %3C repository.length; i++
+repository.forEach(function(repo
) %7B%0A
@@ -372,17 +372,8 @@
repo
-sitory%5Bi%5D
,%0A
@@ -564,12 +564,13 @@
%7D%0A %7D)
-;
%0A%7D
+);
%0A
|
a826710b9c2edc2fd896614ae32b61c956f2278b | rename pixelHeight and pixelWidth to height and width | libs/ktx2image.js | libs/ktx2image.js | const VERSION = [ 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A ];
const VERSION_OFFSET = 0;
const VERSION_LENGTH = VERSION.length;
const HEADER_OFFSET = VERSION_OFFSET + VERSION_LENGTH;
const HEADER_LENGTH = 9 * 4; // 9 uint32s
const INDEX_OFFSET = HEADER_OFFSET + HEADER_LENGTH;
const INDEX_LENGTH = 4 * 4 + 2 * 8; // 4 uint32s and 2 uint64s
const LEVEL_INDEX_OFFSET = INDEX_OFFSET + INDEX_LENGTH;
class Ktx2Image
{
constructor()
{
this.vkFormat = 0;
this.typeSize = 0;
this.pixelWidth = 0;
this.pixelHeight = 0;
this.pixelDepth = 0;
this.layerCount = 0;
this.faceCount = 0;
this.levelCount = 0;
this.suporcompressionScheme = 0;
this.dfdByteOffset = 0;
this.dfdByteLength = 0;
this.kvdByteOffset = 0;
this.kvdByteLength = 0;
this.sgdByteOffset = 0;
this.sgdByteLength = 0;
this.levels = [];
}
initialize(arrayBuffer)
{
const version = new DataView(arrayBuffer, VERSION_OFFSET, VERSION_LENGTH);
if (! this.checkVersion(version))
{
console.error("Invalid KTX2 version identifier");
return;
}
const header = new DataView(arrayBuffer, HEADER_OFFSET, HEADER_LENGTH);
this.parseHeader(header);
const fileIndex = new DataView(arrayBuffer, INDEX_OFFSET, INDEX_LENGTH);
this.parseIndex(fileIndex);
const levelIndexLength = this.levelCount * 3 * 8; // 3 uint64s per level
const levelIndex = new DataView(arrayBuffer, LEVEL_INDEX_OFFSET, levelIndexLength);
this.parseLevelIndex(levelIndex);
this.parseLevelData(arrayBuffer);
}
checkVersion(version)
{
for (let i = 0; i < VERSION_LENGTH; i++)
{
if (version.getUint8(i) != VERSION[i])
{
return false;
}
}
return true;
}
parseHeader(header)
{
let offset = 0;
const getNext = () =>
{
const result = header.getUint32(offset, true);
offset += 4;
return result;
};
this.vkFormat = getNext();
this.typeSize = getNext();
this.pixelWidth = getNext();
this.pixelHeight = getNext();
this.pixelDepth = getNext();
this.layerCount = getNext();
this.faceCount = getNext();
this.levelCount = getNext();
this.suporcompressionScheme = getNext();
}
parseIndex(fileIndex)
{
let offset = 0;
const getNext32 = () =>
{
const result = fileIndex.getUint32(offset, true);
offset += 4;
return result;
};
const getNext64 = () =>
{
const result = this.getUint64(fileIndex, offset, true);
offset += 8;
return result;
};
this.dfdByteOffset = getNext32();
this.dfdByteLength = getNext32();
this.kvdByteOffset = getNext32();
this.kvdByteLength = getNext32();
this.sgdByteOffset = getNext64();
this.sgdByteLength = getNext64();
}
parseLevelIndex(levelIndex)
{
let offset = 0;
const getNext = () =>
{
const result = this.getUint64(levelIndex, offset, true);
offset += 8;
return result;
};
for (let i = 0; i < this.levelCount; i++)
{
const level = {};
level.byteOffset = getNext();
level.byteLength = getNext();
level.uncompressedByteLength = getNext();
this.levels.push(level);
}
}
parseLevelData(arrayBuffer)
{
let miplevel = 0;
for (let level of this.levels)
{
level.miplevel = miplevel++;
level.width = this.pixelWidth / (miplevel * miplevel);
level.height = this.pixelHeight / (miplevel * miplevel);
if (this.vkFormat == VK_FORMAT.R16G16B16A16_SFLOAT)
{
level.data = new Uint16Array(arrayBuffer, level.byteOffset, level.byteLength / this.typeSize);
}
}
}
// https://stackoverflow.com/questions/53103695
getUint64(view, byteOffset, littleEndian)
{
// we should actually be able to use BigInt, but we can't create a Uint8Array with BigInt offset/length
const left = view.getUint32(byteOffset, littleEndian);
const right = view.getUint32(byteOffset + 4, littleEndian);
const combined = littleEndian ? left + (2 ** 32 * right) : (2 ** 32 * left) + right;
if (! Number.isSafeInteger(combined))
{
console.warn("ktx2image: " + combined + " exceeds MAX_SAFE_INTEGER. Precision may be lost.");
}
return combined;
}
}
// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkFormat.html
const VK_FORMAT =
{
R16G16B16A16_SFLOAT: 97
};
export { Ktx2Image };
| JavaScript | 0.999849 | @@ -524,30 +524,25 @@
this.
-pixelW
+w
idth = 0;%0A
@@ -544,38 +544,33 @@
0;%0A this.
-pixelH
+h
eight = 0;%0A
@@ -2242,30 +2242,25 @@
this.
-pixelW
+w
idth = getNe
@@ -2274,30 +2274,25 @@
this.
-pixelH
+h
eight = getN
@@ -3864,14 +3864,9 @@
his.
-pixelW
+w
idth
@@ -3927,14 +3927,9 @@
his.
-pixelH
+h
eigh
|
b0a04f0b605c2df741c981aa443ad989e223dd22 | DEbug stuff | gameCode.js | gameCode.js | 'use strict';
const mongoURI = process.env.MONGODB_URI;
var fs = require('fs'),
readline = require('readline'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
dict = "dict",
codeCounter = "codeCounter";
function init() {
MongoClient.connect(mongoURI, function(err, db) {
if (err) {
console.log("GET CURRCODE: OPENING", err);
}
else {
var collection = db.collection('codeCounter');
collection.find().toArray(function(err, res) {
if (err) {
console.log("GET CURRCODE: READING", err);
}
else {
console.log(res[0]);
codeCounter = JSON.parse(JSON.stringify(res[0].codeCounter));
//
}
})
}
});
fs.readFile('dict.json', 'utf8', function(err, data) {
if (err) throw err;
console.log(JSON.parse(data));
dict = JSON.parse(data);
});
}
init();
var dict = (function() {
fs.readFile('dict.json', 'utf8', function(err, data) {
if (err) throw err;
console.log(JSON.parse(data));
return JSON.parse(data);
});
})();
/*limitation, if codeCounter exceeds [n,n,n,n], where n
is dictSize, counter does not change*/
var makeNewCode = function() {
//I wonder if there is going to be any async issues, if u run two of these at the same time hmm
var isFinished = false;
var curr = codeCounter.length - 1;
console.log("makeNewCode");
console.log(codeCounter);
codeCounter[curr]++;
while (!isFinished && curr > 0) {
console.log((Number(codeCounter[curr]) > (Object.keys(dict).length - 1)));
console.log(Number(codeCounter[curr]));
console.log(dict);
console.log(Object.keys(dict) - 1);
if (Number(codeCounter[curr]) > (Object.keys(dict).length - 1)) {
codeCounter[curr] = 0;
curr--;
if (curr < 0) {
throw "Code Counter Overflowed, I.E Game Limit Reached";
}
else {
codeCounter[curr]++;
}
}
else {
isFinished = true;
}
}
MongoClient.connect(mongoURI, function(err, db) {
if (err) {
console.log("WRITING CURRCODE TO DB: ", err);
}
else {
var collection = db.collection('codeCounter');
collection.updateOne({}, {
"codeCounter": codeCounter
}, function(err, res) {
if (err) {
console.log("WRITING CURRCODE TO DB: ", err);
}
else {
console.log("WRITING CURRCODE TO DB: Success");
}
})
}
});
var retv = dict[codeCounter[0]] + dict[codeCounter[1]] + dict[codeCounter[2]] + dict[codeCounter[3]];
return retv;
}
module.exports.genCode = function() {
console.log("genCode");
console.log("fs: " + fs);
console.log("codeCounter: " + codeCounter);
return makeNewCode();
};
module.exports.acceptGame = function (code) {
MongoClient.connect(mongoURI, function(err, db) {
if (err) {
console.log("Opening GameDB acceptGame: ", err);
}
else {
var collection = db.collection('game');
collection.find({"GameCode": code}).toArray(function(err, res) {
if (err) {
console.log("acceptGame: Finding game", err);
}
else {
console.log(res[0]);
if (res[0].length == 0){
throw "Game Not Found";
}
return;
//
}
})
}
});
} | JavaScript | 0 | @@ -2795,17 +2795,17 @@
.find(%7B%22
-G
+g
ameCode%22
@@ -2964,19 +2964,16 @@
%09if (res
-%5B0%5D
.length
@@ -3012,24 +3012,75 @@
nd%22;%0A%09%09%09%09%09%7D%0A
+%09%09%09%09%09//Check game is init or not and then do stuff%0A
%09%09%09%09%09return;
|
709dd04d8395d7c6de39f653cec9e01717c24edf | Add comments and reformat coding style | src/qUnitScraper.js | src/qUnitScraper.js | var qUnitScraper = {
init: function() {
// validate page here
var failedMessages = this._readResults();
console.log( failedMessages );
},
_readResults: function( ) {
var failedModules = jQuery("#qunit-tests .fail[id^=qunit-test-output]");
var failedMessages = [];
var numFailedModules = failedModules.length;
for( var moduleNumber=0; moduleNumber < numFailedModules; moduleNumber++ )
{
var thisModule = failedModules[moduleNumber];
failedMessages["module " + this._getModuleNumber(jQuery(thisModule))] = this._readModule( thisModule );
}
return failedMessages;
},
_readModule: function( failedModule ) {
var failedTests = jQuery(".qunit-assert-list .fail", failedModule);
var failedMessages = [];
failedMessages["name"] = jQuery(".module-name", failedModule).html() + ": " + jQuery(".test-name", failedModule).html();
failedMessages["tests"] = [];
var numFailedTests = failedTests.length;
for( var testNumber=0; testNumber < numFailedTests; testNumber++ )
{
var thisTest = failedTests[testNumber];
failedMessages["tests"].push({
"message": jQuery(".test-message", thisTest).html(),
"source" : jQuery(".test-source pre", thisTest).html()
});
}
return failedMessages;
},
/**
* This one take a jQuery object of the module we want to find the number.
* Performs a regex match over the id of the DOM which includes an index at the very end.
* Lastly, we add 1 to the number since the ID is 0-indexed vs the list display to user is 1-indexed.
*
* @params : (object) jQuery object of the module element
* @return : (int) module number as display to users
*/
_getModuleNumber: function(module) {
var id = module.attr("id");
var match = id.match(/\d+$/)[0];
return parseInt( match ) + 1 ;
}
} | JavaScript | 0 | @@ -1,182 +1,902 @@
-var qUnitScraper = %7B%0A init: function() %7B%0A // validate page here%0A %0A var failedMessages = this._readResults();%0A console.log( failedMessages );%0A %7D,
+/**%0A * qUnitScraper object%0A */%0Avar qUnitScraper = %7B%0A /**%0A * Start here!%0A * This is the first method to invoke to call other method. %0A * Currently it can only does the call to other methods and doesn't%0A * do any processing here. %0A */%0A init: function() %7B%0A // validate page here%0A %0A var failedMessages = this._readResults();%0A console.log( failedMessages );%0A %7D,%0A /**%0A * _readResults create a jQuery object, selecting output listing. %0A * Currently it's looking only for the failed modules, but could be %0A * extended to specify which to look for.%0A * It calls other methods to get the information it needs and returns an object%0A * listing each method indexed by the method number as displayed to user.%0A * %0A * @params : none%0A * @return : (object) listing all the failed modules along with their information.%0A */
%0A
@@ -1420,24 +1420,549 @@
ges;%0A %7D,%0A
+ /**%0A * This method takes jQuery object of the modules we want to read. %0A * It then searches for the assert list result, currently the failed ones.%0A * Like _readResults, it could be extended.%0A * The method puts together the list found, builds an object including the name, message and source%0A * and returns it.%0A * %0A * @params : (object) jQuery object of the module we want to read%0A * @return : (object) an object with 2 properties, name of test and another object listing the tests%0A */%0A
_readMod
@@ -2751,16 +2751,17 @@
one take
+s
a jQuer
@@ -3177,22 +3177,24 @@
unction(
+
module
+
) %7B%0A
@@ -3222,12 +3222,14 @@
ttr(
+
%22id%22
+
);%0A
@@ -3260,14 +3260,16 @@
tch(
+
/%5Cd+$/
+
)%5B0%5D
|
7d66838fe3137ca120ce4f731c8a293cfcf0b949 | Fix some brokenness in the block menu | autoinput.js | autoinput.js | import {Pos} from "../model"
import {defineOption} from "../edit"
import {Rule, addInputRules, removeInputRules} from "./inputrules"
defineOption("autoInput", false, function(pm, val, old) {
if (val && !old) addInputRules(pm, rules)
else if (!val && old) removeInputRules(pm, rules)
})
export var rules = [
new Rule("-", /--$/, "—"),
new Rule('"', /\s(")$/, "“"),
new Rule('"', /"$/, "”"),
new Rule("'", /\s(')$/, "‘"),
new Rule("'", /'$/, "’"),
new Rule(" ", /^\s*> $/, function(pm, _, pos) {
wrapAndJoin(pm, pos, "blockquote")
}),
new Rule(" ", /^(\d+)\. $/, function(pm, match, pos) {
let order = +match[1]
wrapAndJoin(pm, pos, "ordered_list", {order: order || null, tight: true},
node => node.content.length + (node.attrs.order || 1) == order)
}),
new Rule(" ", /^\s*([-+*]) $/, function(pm, match, pos) {
let bullet = match[1]
wrapAndJoin(pm, pos, "bullet_list", {bullet: bullet, tight: true},
node => node.attrs.bullet == bullet)
}),
new Rule("`", /^```$/, function(pm, _, pos) {
setAs(pm, pos, "code_block", {params: ""})
}),
new Rule(" ", /^(#{1,6}) $/, function(pm, match, pos) {
setAs(pm, pos, "heading", {level: match[1].length})
})
]
function wrapAndJoin(pm, pos, type, attrs = null, predicate = null) {
let parentOffset = pos.path[pos.path.length - 1]
let sibling = parentOffset > 0 && pm.doc.path(pos.shorten()).content[parentOffset - 1]
let join = sibling.type.name == type && (!predicate || predicate(sibling))
let tr = pm.tr.wrap(pos, pos, new Node(type, attrs))
let delPos = tr.mapSimple(pos)
tr.delete(new Pos(delPos.path, 0), delPos)
if (join) tr.join(tr.mapSimple(pos, -1))
pm.apply(tr)
}
function setAs(pm, pos, type, attrs) {
pm.apply(pm.tr.setType(pos, pos, new Node(type, attrs))
.delete(new Pos(pos.path, 0), pos))
}
| JavaScript | 0.000102 | @@ -1777,16 +1777,21 @@
m.tr.set
+Block
Type(pos
|
08722e7a74a5e6da91e6978f920d262ce9d2c668 | Fix query processing | src/rails-ranger.js | src/rails-ranger.js | import Axios from 'axios'
class RailsRanger {
constructor (configs = {}) {
// Falls back to Axios configurations
this.client = Axios.create(configs)
}
//
// Methods
//
get (path, params) {
// This will translate '/users/:id' to '/users/1'
let prepared = prepareArguments(path, params)
// This will inject excess params to the path like '/users/1?flag=true'
let querifiedPath = injectPathWithQuery(prepared.path, prepared.params)
return this.client.get(querifiedPath)
}
post (path, params) {
let prepared = prepareArguments(path, params)
return this.client.post(prepared.path, prepared.params)
}
delete (path, params) {
let prepared = prepareArguments(path, params)
return this.client.delete(prepared.path, prepared.params)
}
//
// RESTful Actions
//
index (...args) {
this.list(args)
}
list (resource, params) {
let path = resource
return this.get(path, params)
}
show (resource, params) {
let path = `${resource}/:id`
return this.get(path, params)
}
destroy (resource, params) {
let path = `${resource}/:id`
// TODO
// Make an option for switching to get for destroy actions
return this.delete(path, params)
}
create (resource, params) {
let path = resource
return this.post(path, params)
}
update (resource, params) {
let path = `${resource}/:id`
return this.patch(path, params)
}
new (resource, params) {
let path = `${resource}/:id/new`
return this.get(path, params)
}
edit (resource, params) {
let path = `${resource}/:id/edit`
return this.get(path, params)
}
}
const injectPathWithQuery = function (path, params) {
let keyValuePairs = Object.entries(params)
let stringParams = keyValuePairs.map((pair) => `${pair[0]}=${pair[1]}`)
let query = stringParams.join('&')
return query ? path + '?' + query : path
}
//
// Replaces incidencies of params in the path provided
// and return the processed path and the params left out
// of the path
//
const prepareArguments = function (path, params) {
let processedPath = deepClone(path)
let processedParams = deepClone(params)
for (let key in params) {
// Skipping inherited proprieties
if (!params.hasOwnProperty(key)) { continue }
// Skipping if the param wasn't found in the path
if (!processedPath.match(key)) { continue }
// Replaces the symbol in the path with the param value
processedPath = path.replace(':' + key, params[key])
// If the key was used in the path, it shouldn't be sent as
// a query parameter
delete processedParams[key]
}
return { path: processedPath, params: processedParams }
}
//
// Returns a deep clone from a given object
//
const deepClone = function (object) {
return JSON.parse(JSON.stringify(object))
}
export default RailsRanger
| JavaScript | 0.000321 | @@ -2070,32 +2070,37 @@
nction (path
+ = ''
, params
) %7B%0A let pr
@@ -2079,32 +2079,37 @@
ath = '', params
+ = %7B%7D
) %7B%0A let proces
@@ -2122,23 +2122,12 @@
h =
-deepClone(
path
-)
%0A l
|
56bc52e0b9781afe327d06f5d5cfc1a65f5b1f76 | support class prop | src/react/styled.js | src/react/styled.js | /* @flow */
const React = require('react'); // eslint-disable-line import/no-extraneous-dependencies
/* ::
type Options = {
name: string,
class: string,
vars?: { [string]: [string | number | ((props: *) => string | number), string | void] }
}
*/
function styled(tag /* : React.ComponentType<*> | string */) {
return (options /* : Options */) => {
if (process.env.NODE_ENV !== 'production') {
if (Array.isArray(options)) {
// We received a strings array since it's used as a tag
throw new Error(
'Using the "styled" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly.'
);
}
}
/* $FlowFixMe: Flow doesn't know about forwardRef */
const Result = React.forwardRef((props, ref) => {
const { as: component = tag, ...rest } = props;
const next = Object.assign(rest, {
ref,
className: props.className
? `${options.class} ${props.className}`
: options.class,
});
const { vars } = options;
if (vars) {
const style = {};
Object.keys(vars).forEach(name => {
const [value, unit = ''] = vars[name];
style[`--${name}`] = `${
typeof value === 'function' ? value(props) : value
}${unit}`;
});
next.style = Object.assign(style, next.style);
}
return React.createElement(component, next);
});
Result.displayName = options.name;
Result.className = options.class;
Result.extends = tag;
return Result;
};
}
if (process.env.NODE_ENV !== 'production') {
module.exports = new Proxy(styled, {
get(o, prop) {
return o(prop);
},
});
} else {
module.exports = styled;
}
/* ::
type StyledComponent<T> = React.ComponentType<T & { as?: React$ElementType }>;
type StyledTag<T> = (strings: string[], ...exprs: Array<string | number | {} | (T => string | number)>) => StyledComponent<T>;
declare module.exports: {|
<T>(T): StyledTag<React.ElementConfig<T>>,
[string]: StyledTag<{ children?: React.Node, [key: string]: any }>,
|};
*/
| JavaScript | 0 | @@ -94,16 +94,52 @@
ndencies
+%0Aconst %7B cx %7D = require('../index');
%0A%0A/* ::%0A
@@ -850,16 +850,34 @@
t = tag,
+ class: className,
...rest
@@ -892,158 +892,85 @@
ps;%0A
+%0A
-const next = Object.assign(rest, %7B%0A ref,%0A className: props.className%0A ? %60$%7Boptions.class%7D $%7Bprops.className%7D%60%0A :
+rest.ref = ref;%0A rest.className = cx(rest.className %7C%7C className,
opt
@@ -983,17 +983,8 @@
lass
-,%0A %7D
);%0A%0A
@@ -1294,19 +1294,19 @@
-nex
+res
t.style
@@ -1328,19 +1328,19 @@
(style,
-nex
+res
t.style)
@@ -1398,11 +1398,11 @@
nt,
-nex
+res
t);%0A
|
0b6eec7be285779554a67485a66af0c5b63f6651 | Make swiper update for virtual mode React.StrictMode compatible | src/react/swiper.js | src/react/swiper.js | import React, { useRef, useState, useEffect, forwardRef } from 'react';
import { getParams } from './get-params';
import { initSwiper, mountSwiper } from './init-swiper';
import { needsScrollbar, needsNavigation, needsPagination, uniqueClasses, extend } from './utils';
import { renderLoop, calcLoopedSlides } from './loop';
import { getChangedParams } from './get-changed-params';
import { getChildren } from './get-children';
import { updateSwiper } from './update-swiper';
import { renderVirtual, updateOnVirtualData } from './virtual';
import { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect';
const Swiper = forwardRef(
(
{
className,
tag: Tag = 'div',
wrapperTag: WrapperTag = 'div',
children,
onSwiper,
...rest
} = {},
externalElRef,
) => {
const [containerClasses, setContainerClasses] = useState('swiper-container');
const [virtualData, setVirtualData] = useState(null);
const [breakpointChanged, setBreakpointChanged] = useState(false);
const initializedRef = useRef(false);
const swiperElRef = useRef(null);
const swiperRef = useRef(null);
const oldPassedParamsRef = useRef(null);
const oldSlides = useRef(null);
const nextElRef = useRef(null);
const prevElRef = useRef(null);
const paginationElRef = useRef(null);
const scrollbarElRef = useRef(null);
const { params: swiperParams, passedParams, rest: restProps } = getParams(rest);
const { slides, slots } = getChildren(children);
const changedParams = getChangedParams(
passedParams,
oldPassedParamsRef.current,
slides,
oldSlides.current,
);
oldPassedParamsRef.current = passedParams;
oldSlides.current = slides;
const onBeforeBreakpoint = () => {
setBreakpointChanged(!breakpointChanged);
};
Object.assign(swiperParams.on, {
_containerClasses(swiper, classes) {
setContainerClasses(classes);
},
});
if (!swiperElRef.current) {
// init swiper
swiperRef.current = initSwiper(swiperParams);
swiperRef.current.loopCreate = () => {};
swiperRef.current.loopDestroy = () => {};
if (swiperParams.loop) {
swiperRef.current.loopedSlides = calcLoopedSlides(slides, swiperParams);
}
if (swiperRef.current.virtual && swiperRef.current.params.virtual.enabled) {
swiperRef.current.virtual.slides = slides;
const extendWith = {
cache: false,
renderExternal: setVirtualData,
renderExternalUpdate: false,
};
extend(swiperRef.current.params.virtual, extendWith);
extend(swiperRef.current.originalParams.virtual, extendWith);
}
}
// Listen for breakpoints change
if (swiperRef.current) {
swiperRef.current.on('_beforeBreakpoint', onBeforeBreakpoint);
}
useEffect(() => {
return () => {
if (swiperRef.current) swiperRef.current.off('_beforeBreakpoint', onBeforeBreakpoint);
};
});
// set initialized flag
useEffect(() => {
if (!initializedRef.current && swiperRef.current) {
swiperRef.current.emitSlidesClasses();
initializedRef.current = true;
}
});
// mount swiper
useIsomorphicLayoutEffect(() => {
if (externalElRef) {
externalElRef.current = swiperElRef.current;
}
if (!swiperElRef.current) return;
mountSwiper(
{
el: swiperElRef.current,
nextEl: nextElRef.current,
prevEl: prevElRef.current,
paginationEl: paginationElRef.current,
scrollbarEl: scrollbarElRef.current,
swiper: swiperRef.current,
},
swiperParams,
);
if (onSwiper) onSwiper(swiperRef.current);
// eslint-disable-next-line
return () => {
if (swiperRef.current && !swiperRef.current.destroyed) {
swiperRef.current.destroy(true, false);
}
};
}, []);
// watch for params change
useIsomorphicLayoutEffect(() => {
if (changedParams.length && swiperRef.current && !swiperRef.current.destroyed) {
updateSwiper(swiperRef.current, slides, passedParams, changedParams);
}
});
// update on virtual update
useIsomorphicLayoutEffect(() => {
updateOnVirtualData(swiperRef.current);
}, [virtualData]);
// bypass swiper instance to slides
function renderSlides() {
if (swiperParams.virtual) {
return renderVirtual(swiperRef.current, slides, virtualData);
}
if (!swiperParams.loop || (swiperRef.current && swiperRef.current.destroyed)) {
return slides.map((child) => {
return React.cloneElement(child, { swiper: swiperRef.current });
});
}
return renderLoop(swiperRef.current, slides, swiperParams);
}
return (
<Tag
ref={swiperElRef}
className={uniqueClasses(`${containerClasses}${className ? ` ${className}` : ''}`)}
{...restProps}
>
{slots['container-start']}
{needsNavigation(swiperParams) && (
<>
<div ref={prevElRef} className="swiper-button-prev" />
<div ref={nextElRef} className="swiper-button-next" />
</>
)}
{needsScrollbar(swiperParams) && <div ref={scrollbarElRef} className="swiper-scrollbar" />}
{needsPagination(swiperParams) && (
<div ref={paginationElRef} className="swiper-pagination" />
)}
<WrapperTag className="swiper-wrapper">
{slots['wrapper-start']}
{renderSlides()}
{slots['wrapper-end']}
</WrapperTag>
{slots['container-end']}
</Tag>
);
},
);
Swiper.displayName = 'Swiper';
export { Swiper };
| JavaScript | 0 | @@ -1521,233 +1521,8 @@
);%0A%0A
- const changedParams = getChangedParams(%0A passedParams,%0A oldPassedParamsRef.current,%0A slides,%0A oldSlides.current,%0A );%0A%0A oldPassedParamsRef.current = passedParams;%0A oldSlides.current = slides;%0A%0A
@@ -3815,32 +3815,271 @@
tEffect(() =%3E %7B%0A
+ const changedParams = getChangedParams(%0A passedParams,%0A oldPassedParamsRef.current,%0A slides,%0A oldSlides.current,%0A );%0A oldPassedParamsRef.current = passedParams;%0A oldSlides.current = slides;%0A
if (change
|
d7e7f526c5b9cc1c4c979d9e1c4091fd7cb8ceb1 | add plugin initializion | lib/doc-processor.js | lib/doc-processor.js | var _ = require('lodash');
var log = require('winston');
var extractTagsFactory = require('./utils/extract-tags');
/**
* Build a function to process the documents by running the given plugins
* @param {object} tagParser The thing that will parse the tags from the documents
* @param {object} tagDefs The definitions of how to extract tags info from the parsed tags
* @param {function} plugins The plugins to apply to the docs
* @return {function} The function that will process the docs
*/
module.exports = function docProcessorFactory(tagParser, tagDefs, plugins) {
var extractTags = extractTagsFactory(tagParser, tagDefs);
/**
* Process the docs
* @param {array} docs Collection of docs to process
* @return {array} The processed docs
*/
return function(docs) {
// Parse the tags from the docs
_.forEach(docs, function(doc) {
doc.tags = tagParser.parse(doc.content);
});
// Run the "before" plugins over the docs
_.forEach(plugins,function(plugin) {
if ( plugin.before ) {
docs = plugin.before(docs, tagParser) || docs;
}
});
// Process each of the docs in turn
_.forEach(docs, function(doc) {
// Extract meta-data from the tags
extractTags(doc);
// Run the "each" plugins over each of the doc
_.forEach(plugins,function(plugin) {
if ( plugin.each ) {
plugin.each(doc, tagParser);
}
});
});
// Run the "after" plugins over the docs
_.forEach(plugins,function(plugin) {
if ( plugin.after ) {
docs = plugin.after(docs, tagParser) || docs;
}
});
_.forEach(docs, function(doc) {
log.debug('Processed doc', doc.id);
});
return docs;
};
}; | JavaScript | 0 | @@ -53,66 +53,8 @@
n');
-%0Avar extractTagsFactory = require('./utils/extract-tags');
%0A%0A/*
@@ -495,98 +495,59 @@
ory(
-tagParser, tagDefs, plugins) %7B%0A%0A var extractTags = extractTagsFactory(tagParser, tagDefs)
+config) %7B%0A%0A var plugins = config.processor.plugins
;%0A%0A
@@ -710,22 +710,16 @@
) %7B%0A
-
%0A //
Pars
@@ -718,36 +718,62 @@
//
-Parse the tags from the docs
+Initialize the plugins, passing them the config object
%0A
@@ -775,35 +775,38 @@
t%0A _.forEach(
-doc
+plugin
s, function(doc)
@@ -804,62 +804,99 @@
tion
-(doc) %7B%0A doc.tags = tagParser.parse(doc.content);
+ initializePlugin(plugin) %7B%0A if ( plugin.init ) %7B%0A plugin.init(config);%0A %7D
%0A
|
30b1b73bf79a0f2ad6d010410435fc6d9a2697d8 | Change bubble messages and emojis | js/bubbles.js | js/bubbles.js | /*
* This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/.
* Copyright (c) 2016 Ivan Aracki
*/
window.onload = function() {
var messagesEl = document.querySelector('.messages');
var typingSpeed = 20;
var loadingText = '<b>•</b><b>•</b><b>•</b>';
var messageIndex = 0;
var getCurrentTime = function() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var current = hours + (minutes * .01);
if (current >= 5 && current < 19) return 'Have a nice day';
if (current >= 19 && current < 22) return 'Have a nice evening';
if (current >= 22 || current < 5) return 'Have a good night';
};
var messages = [
'Hey there 👋',
'I\'m software developer from Belgrade',
'You can contact me at aracki.ivan@gmail.com',
getCurrentTime(),
'⛵ I.A.'
];
var getFontSize = function() {
return parseInt(getComputedStyle(document.body).getPropertyValue('font-size'));
};
var pxToRem = function(px) {
return px / getFontSize() + 'rem';
};
var createBubbleElements = function(message, position) {
var bubbleEl = document.createElement('div');
var messageEl = document.createElement('span');
var loadingEl = document.createElement('span');
bubbleEl.classList.add('bubble');
bubbleEl.classList.add('is-loading');
bubbleEl.classList.add('cornered');
bubbleEl.classList.add(position === 'right' ? 'right' : 'left');
messageEl.classList.add('message');
loadingEl.classList.add('loading');
messageEl.innerHTML = message;
loadingEl.innerHTML = loadingText;
bubbleEl.appendChild(loadingEl);
bubbleEl.appendChild(messageEl);
bubbleEl.style.opacity = 0;
return {
bubble: bubbleEl,
message: messageEl,
loading: loadingEl
}
};
var getDimentions = function(elements) {
return dimensions = {
loading: {
w: '4rem',
h: '2.25rem'
},
bubble: {
w: pxToRem(elements.bubble.offsetWidth + 4),
h: pxToRem(elements.bubble.offsetHeight)
},
message: {
w: pxToRem(elements.message.offsetWidth + 4),
h: pxToRem(elements.message.offsetHeight)
}
}
};
var sendMessage = function(message, position) {
var loadingDuration = (message.replace(/<(?:.|\n)*?>/gm, '').length * typingSpeed) + 500;
var elements = createBubbleElements(message, position);
messagesEl.appendChild(elements.bubble);
messagesEl.appendChild(document.createElement('br'));
var dimensions = getDimentions(elements);
elements.bubble.style.width = '0rem';
elements.bubble.style.height = dimensions.loading.h;
elements.message.style.width = dimensions.message.w;
elements.message.style.height = dimensions.message.h;
elements.bubble.style.opacity = 1;
var bubbleOffset = elements.bubble.offsetTop + elements.bubble.offsetHeight;
if (bubbleOffset > messagesEl.offsetHeight) {
var scrollMessages = anime({
targets: messagesEl,
scrollTop: bubbleOffset,
duration: 750
});
}
var bubbleSize = anime({
targets: elements.bubble,
width: ['0rem', dimensions.loading.w],
marginTop: ['2.5rem', 0],
marginLeft: ['-2.5rem', 0],
duration: 800,
easing: 'easeOutElastic'
});
var loadingLoop = anime({
targets: elements.bubble,
scale: [1.05, .95],
duration: 1100,
loop: true,
direction: 'alternate',
easing: 'easeInOutQuad'
});
var dotsStart = anime({
targets: elements.loading,
translateX: ['-2rem', '0rem'],
scale: [.5, 1],
duration: 400,
delay: 25,
easing: 'easeOutElastic',
});
var dotsPulse = anime({
targets: elements.bubble.querySelectorAll('b'),
scale: [1, 1.25],
opacity: [.5, 1],
duration: 300,
loop: true,
direction: 'alternate',
delay: function(i) {return (i * 100) + 50}
});
setTimeout(function() {
loadingLoop.pause();
dotsPulse.restart({
opacity: 0,
scale: 0,
loop: false,
direction: 'forwards',
update: function(a) {
if (a.progress >= 65 && elements.bubble.classList.contains('is-loading')) {
elements.bubble.classList.remove('is-loading');
anime({
targets: elements.message,
opacity: [0, 1],
duration: 300,
});
}
}
});
bubbleSize.restart({
scale: 1,
width: [dimensions.loading.w, dimensions.bubble.w ],
height: [dimensions.loading.h, dimensions.bubble.h ],
marginTop: 0,
marginLeft: 0,
begin: function() {
if (messageIndex < messages.length) elements.bubble.classList.remove('cornered');
}
})
}, loadingDuration - 50);
};
var sendMessages = function() {
var message = messages[messageIndex];
if (!message) return;
sendMessage(message);
++messageIndex;
setTimeout(sendMessages, (message.replace(/<(?:.|\n)*?>/gm, '').length * typingSpeed) + anime.random(900, 1200));
};
sendMessages();
};
| JavaScript | 0.000001 | @@ -651,16 +651,18 @@
nice day
+ %F0%9F%8C%85
';%0A i
@@ -722,16 +722,18 @@
evening
+ %F0%9F%8C%87
';%0A i
@@ -790,16 +790,18 @@
od night
+ %F0%9F%8C%8C
';%0A %7D;%0A
@@ -966,10 +966,8 @@
'
-%E2%9B%B5
I.A.
@@ -1945,25 +1945,25 @@
var getDimen
-t
+s
ions = funct
@@ -2674,17 +2674,17 @@
getDimen
-t
+s
ions(ele
@@ -3826,17 +3826,16 @@
Elastic'
-,
%0A %7D);
@@ -4550,28 +4550,27 @@
duration:
-3
+1
00
-,
%0A
|
94e97712b47306dd72e1ff814a8708a080722be6 | Fix City. | js/capture.js | js/capture.js | var secs_to_capture = 3;
var makeAnimation = null;
var captureFrame = null;
var CAPTURE = window.location.href.indexOf('capture') != -1;
if (CAPTURE) {
// Load jquery, we only need it for AJAX requests for capturing PNGs.
var tag = document.createElement('script');
tag.src = "https://code.jquery.com/jquery-2.1.4.min.js";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Wait 3 seconds for jquery to load. Lame.
window.setTimeout(function() {
makeAnimation();
}, 3000);
var canvas = null;
captureFrame = function(frame, fps_ratio) {
canvas = canvas || document.getElementsByTagName('CANVAS')[0];
var img = canvas.toDataURL('image/png');
$.ajax('/capture', {
method: 'POST',
data: {
'frame': frame / fps_ratio,
'data': img
},
error: function() {
// If the server is unavailable, stop the capture process.
catpureFrame = null;
}
});
}
}
| JavaScript | 0 | @@ -44,16 +44,29 @@
= null;%0A
+var $ = null;
%0Avar cap
|
6c50648406daaa4fb1816c12c17f1cc4bf4c0bf7 | update to version 1.3.0 | lib/executeScalar.js | lib/executeScalar.js | /**
* Created by nuintun on 2014/4/2.
*/
'use strict';
var util = require('util'),
proxy = require('./proxy'),
eventemitter = require('events').EventEmitter;
function ExecuteScalar(connection, sql, scalar,encoding){
eventemitter.call(this);
this.encoding = encoding;
this.params = {
connection: connection,
sql: sql,
scalar: scalar
};
this.exec();
}
util.inherits(ExecuteScalar, eventemitter);
ExecuteScalar.prototype.exec = function (){
var that = this;
proxy.exec(
'executeScalar',
that.params,
function (data){
that.emit('done', data);
},
function (error){
that.emit('fail', error);
},
this.encoding
);
};
module.exports = ExecuteScalar; | JavaScript | 0 | @@ -30,16 +30,17 @@
2014/4/2
+0
.%0A */%0A%0A'
@@ -208,16 +208,17 @@
scalar,
+
encoding
|
11a2aa17b0c5ae6cde5e901a15fb15d90c89d1f1 | Update responseXlsx.js | src/responseXlsx.js | src/responseXlsx.js | import Promise from 'bluebird'
import httpRequest from 'request'
import toArray from 'stream-to-array'
const toArrayAsync = Promise.promisify(toArray)
const preview = (request, response, options) => {
return new Promise((resolve, reject) => {
const req = httpRequest.post(options.publicUriForPreview || 'http://jsreport.net/temp', (err, resp, body) => {
if (err) {
return reject(err)
}
response.content = new Buffer('<iframe style="height:100%;width:100%" src="https://view.officeapps.live.com/op/view.aspx?src=' +
encodeURIComponent((options.publicUriForPreview || 'http://jsreport.net/temp') + '/' + body) + '" />')
response.headers['Content-Type'] = 'text/html'
// sometimes files is not completely flushed and excel online cannot find it immediately
setTimeout(function () {
resolve()
}, 500)
})
var form = req.form()
form.append('file', response.stream)
response.headers['Content-Type'] = 'text/html'
})
}
export default function responseXlsx (request, response) {
let options = request.reporter.options.xlsx || {}
if (request.options.preview && options.previewInExcelOnline !== false) {
return preview(request, response, options)
}
response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheetf'
response.headers['Content-Disposition'] = 'inline; filename="report.xlsx"'
response.headers['File-Extension'] = 'xlsx'
return toArrayAsync(response.stream).then((buf) => {
response.content = Buffer.concat(buf)
})
} | JavaScript | 0 | @@ -1338,17 +1338,16 @@
ml.sheet
-f
'%0A resp
@@ -1563,12 +1563,13 @@
(buf)%0A %7D)%0A%7D
+%0A
|
b4cfc1aaa437d0ece34ecbbf7597d50cf2dfe373 | Update gruppoc.js | js/gruppoc.js | js/gruppoc.js | gruppo.innerHTML = "<p><iframe width="100%" height="400" src="https://www.youtube.com/embed/hJdG664iams" frameborder="0" allowfullscreen=""></iframe></p>";
| JavaScript | 0.000001 | @@ -18,11 +18,8 @@
= %22%3C
-p%3E%3C
ifra
@@ -31,14 +31,13 @@
dth=
-%22100%25%22
+'560'
hei
@@ -45,18 +45,18 @@
ht=%22
-400
+315
%22 src=
-%22
+'
http
@@ -86,19 +86,19 @@
ed/h
-JdG664iams%22
+fRKsYbt4S0'
fra
@@ -110,11 +110,11 @@
der=
-%220%22
+'0'
all
@@ -129,11 +129,8 @@
reen
-=%22%22
%3E%3C/i
@@ -139,11 +139,6 @@
ame%3E
-%3C/p%3E%22;
+%22
%0A
|
c14c9321a5d7b0b02c67bf866d1b31cd47f8d998 | Use node's crypto when available | git-sha1.js | git-sha1.js | "use strict";
// Input chunks must be either arrays of bytes or "raw" encoded strings
module.exports = function sha1(buffer) {
if (buffer === undefined) return create();
var shasum = create();
shasum.update(buffer);
return shasum.digest();
};
// A streaming interface for when nothing is passed in.
function create() {
var h0 = 0x67452301;
var h1 = 0xEFCDAB89;
var h2 = 0x98BADCFE;
var h3 = 0x10325476;
var h4 = 0xC3D2E1F0;
// The first 64 bytes (16 words) is the data chunk
var block = new Uint32Array(80), offset = 0, shift = 24;
var totalLength = 0;
return { update: update, digest: digest };
// The user gave us more data. Store it!
function update(chunk) {
if (typeof chunk === "string") return updateString(chunk);
var length = chunk.length;
totalLength += length * 8;
for (var i = 0; i < length; i++) {
write(chunk[i]);
}
}
function updateString(string) {
var length = string.length;
totalLength += length * 8;
for (var i = 0; i < length; i++) {
write(string.charCodeAt(i));
}
}
function write(byte) {
block[offset] |= (byte & 0xff) << shift;
if (shift) {
shift -= 8;
}
else {
offset++;
shift = 24;
}
if (offset === 16) processBlock();
}
// No more data will come, pad the block, process and return the result.
function digest() {
// Pad
write(0x80);
if (offset > 14 || (offset === 14 && shift < 24)) {
processBlock();
}
offset = 14;
shift = 24;
// 64-bit length big-endian
write(0x00); // numbers this big aren't accurate in javascript anyway
write(0x00); // ..So just hard-code to zero.
write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00);
write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00);
for (var s = 24; s >= 0; s -= 8) {
write(totalLength >> s);
}
// At this point one last processBlock() should trigger and we can pull out the result.
return toHex(h0) +
toHex(h1) +
toHex(h2) +
toHex(h3) +
toHex(h4);
}
// We have a full block to process. Let's do it!
function processBlock() {
// Extend the sixteen 32-bit words into eighty 32-bit words:
for (var i = 16; i < 80; i++) {
var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16];
block[i] = (w << 1) | (w >>> 31);
}
// log(block);
// Initialize hash value for this chunk:
var a = h0;
var b = h1;
var c = h2;
var d = h3;
var e = h4;
var f, k;
// Main loop:
for (i = 0; i < 80; i++) {
if (i < 20) {
f = d ^ (b & (c ^ d));
k = 0x5A827999;
}
else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if (i < 60) {
f = (b & c) | (d & (b | c));
k = 0x8F1BBCDC;
}
else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
var temp = (a << 5 | a >>> 27) + f + e + k + (block[i]|0);
e = d;
d = c;
c = (b << 30 | b >>> 2);
b = a;
a = temp;
}
// Add this chunk's hash to result so far:
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
// The block is now reusable.
offset = 0;
for (i = 0; i < 16; i++) {
block[i] = 0;
}
}
function toHex(word) {
var hex = "";
for (var i = 28; i >= 0; i -= 4) {
hex += ((word >> i) & 0xf).toString(16);
}
return hex;
}
}
| JavaScript | 0 | @@ -12,300 +12,863 @@
%22;%0A%0A
-// Input chunks must be either arrays of bytes or %22raw%22 encoded strings%0Amodule.exports = function sha1(buffer) %7B%0A if (buffer === undefined) return create();%0A var shasum = create();%0A shasum.update(buffer);%0A return shasum.digest();%0A%7D;%0A%0A// A streaming interface for when nothing is passed in
+var create, crypto;%0Aif (typeof process === 'object' && typeof process.versions === 'object' && process.versions.node) %7B%0A var nodeRequire = require; // Prevent mine.js from seeing this require%0A crypto = nodeRequire('crypto');%0A create = createNode;%0A%7D%0Aelse %7B%0A create = createJs;%0A%7D%0A%0A// Input chunks must be either arrays of bytes or %22raw%22 encoded strings%0Amodule.exports = function sha1(buffer) %7B%0A if (buffer === undefined) return create();%0A var shasum = create();%0A shasum.update(buffer);%0A return shasum.digest();%0A%7D;%0A%0A// Use node's openssl bindings when available%0Afunction createNode() %7B%0A var shasum = crypto.createHash('sha1');%0A return %7B%0A update: function (buffer) %7B%0A return shasum.update(buffer);%0A %7D,%0A digest: function () %7B%0A return shasum.digest('hex');%0A %7D%0A %7D;%0A%7D%0A%0A// A pure JS implementation of sha1 for non-node environments
.%0Afu
@@ -880,16 +880,18 @@
n create
+Js
() %7B%0A v
|
dc52dff8b80e6f5e2718296a09a16d0b268c6502 | Repair the navigate function | src/router.react.js | src/router.react.js | import ReactDOM from 'react-dom';
/**
* React Router, done slim
*/
class Router
{
/**
* Binds the event that listens for URL changes
*/
constructor(viewport)
{
this.routes = [];
this.defineRoutes();
this.viewport = viewport;
}
/**
* Defines the default route
* @returns {*}
*/
getDefaultRoute()
{
throw new TypeError('getDefaultRoute must be of a childclass of router, and should not be called directly.')
}
/**
* Keeps an array of all available routes
*/
defineRoutes()
{
throw new TypeError('defineRoutes must be of a childclass of Router, and should not be called directly.')
}
/**
* Returns the route for a given url
* @param name
* @returns {*}
*/
getRoute(name)
{
return this.routes[name];
}
/**
* Returns the url the user has requested
* @returns {string}
*/
getRequestedRoute()
{
return window.location.hash.substr(1).split('?')[0];
}
/**
* Returns if the user wants to access the default route
* @returns {boolean}
*/
isDefaultRoute()
{
return this.getRequestedRoute() == 0 ? true : false;
}
/**
* Returns the ID for the viewport
* @returns {*}
*/
getViewport()
{
return this.viewport;
}
/**
* Gets the query params
* @param name
*/
getQueryParams()
{
var result = [];
var rawQueries = this.getQueryString().split('&');
for (let queryblob in rawQueries) {
var essence = queryblob.split('=', 2);
result[essence[0]] = (essence[1] !== undefined) ? essence[1] : true;
}
return result;
}
/**
* Returns the query string after #
* @returns {string}
*/
getQueryString()
{
var request = window.location.hash.substr(1).split('?', 2);
return (request[1] !== undefined) ? request[1] : '';
}
/**
* Navigates to the requested url
* @returns {*}
*/
navigate()
{
var target = this.getRoute(this.getRequestedRoute());
var targetDOM = this.getApplicationTarget();
if (this.isDefaultRoute()) {
target = this.getDefaultRoute();
}
if (target == undefined) {
target = this.getDefaultRoute();
}
ReactDOM.render(
target,
document.getElementById(this.getViewport())
);
}
/**
* Initiates the router
*/
boot()
{
var redirect = this.getDefaultRoute();
if (this.getRequestedRoute().length > 0) {
redirect = this.getRoute(this.getRequestedRoute());
}
ReactDOM.render(redirect, document.getElementById(this.getViewport()));
}
}
export default Router; | JavaScript | 0.000003 | @@ -2182,61 +2182,8 @@
());
-%0A var targetDOM = this.getApplicationTarget();
%0A%0A
|
4e285d9d4c0c01c9701498aa9dfd38afe0fa318c | Fix unexpected bracket | src/routes/pizza.js | src/routes/pizza.js | const express = require('express');
const router = express.Router();
const Pizza = require('../models/pizzas');
const debug = require('debug')('route:pizza');
const responder = require('../modules/responder');
router.get('/pizza', (req, res, next) => {
let {id} = req.query;
let query = {};
let labels = {};
if (!id) {
labels = { _id: 1, name: 1, price: 1 };
else {
query = { _id: id };
labels = { __v: 0 };
}
Pizza.find(query, labels).exec()
.then(pizzas => {
return res.json(pizzas);
})
});
router.post('/pizza', (req, res, next) => {
let {name, price, ingredients} = req.body;
if (!(name && price && ingredients))
return res.status(400).json(responder(400, 1, 'All fields are required!'));
if (isNaN(price))
return res.status(400).json(responder(400, 2, 'Price must be a number!'));
if (!ingredients.length)
return res.status(400).json(responder(400, 3, 'You must provide at least one ingredient!'));
Pizza.count({ name: name }).exec()
.then(count => {
if (count != 0) {
debug('err', name, 'in use!');
throw `${name} already exists!`;
}
let model = new Pizza({
name: name
, price: price
, ingredients: ingredients
})
model.save(e => {
if (e) throw e;
return res.json(responder(200, 0, `${name} has been created!`));
});
})
.catch(e => {
debug('error', e);
res.status(400).json(responder(400, 3, e));
})
});
router.put('/pizza', (req, res, next) => {
let {id, name, price, ingredients} = req.body;
if (!(id && name && price && ingredients))
return res.status(400).json(responder(400, 1, 'All fields are required!'));
if (id.length !== 24)
return res.status(400).json(responder(400, 2, 'Invalid id!'));
if (isNaN(price))
return res.status(400).json(responder(400, 3, 'Price must be a number!'));
if (!ingredients.length)
return res.status(400).json(responder(400, 4, 'You must provide at least one ingredient!'));
Pizza.update({ _id: id }, { name: name, price: price, ingredients: ingredients }).exec()
.then(r => {
return res.json(r);
});
});
router.delete('/pizza', (req, res, next) => {
let {id} = req.body;
if (!id)
return res.status(400).json(responder(400, 1, 'You must provide an id!'));
if (id.length !== 24)
return res.status(400).json(responder(400, 2, 'Invalid id!'));
Pizza.remove({ _id: id }).exec()
.then(r => {
return res.json(responder(200, 0, r));
});
});
module.exports = router;
| JavaScript | 0.000005 | @@ -318,18 +318,16 @@
if (!id)
- %7B
%0A lab
|
0e6e9fb8d6c10f76119798df182199e9ac3eed72 | Update compat.js (#305) | src/rules/compat.js | src/rules/compat.js | // @flow
import memoize from 'lodash.memoize';
import {
lintCallExpression,
lintMemberExpression,
lintNewExpression
} from '../Lint';
import DetermineTargetsFromConfig, { Versioning } from '../Versioning';
import type { ESLintNode, Node, BrowserListConfig } from '../LintTypes';
import { rules } from '../providers';
type ESLint = {
[astNodeTypeName: string]: (node: ESLintNode) => void
};
type Context = {
node: ESLintNode,
options: Array<string>,
settings: {
browsers: Array<string>,
polyfills: Array<string>
},
getFilename: () => string,
report: () => void
};
function getName(node: ESLintNode): string {
switch (node.type) {
case 'NewExpression': {
return node.callee.name;
}
case 'MemberExpression': {
return node.object.name;
}
case 'CallExpression': {
return node.callee.name;
}
default:
throw new Error('not found');
}
}
function generateErrorName(rule: Node): string {
if (rule.name) return rule.name;
if (rule.property) return `${rule.object}.${rule.property}()`;
return rule.object;
}
const getPolyfillSet = memoize(
(polyfillArrayJSON: string): Set<String> =>
new Set(JSON.parse(polyfillArrayJSON))
);
function isPolyfilled(context: Context, rule: Node): boolean {
if (!context.settings.polyfills) return false;
const polyfills = getPolyfillSet(JSON.stringify(context.settings.polyfills));
return (
// v2 allowed users to select polyfills based off their caniuseId. This is
// no longer supported. Keeping this here to avoid breaking changes.
polyfills.has(rule.id) ||
// Check if polyfill is provided (ex. `Promise.all`)
polyfills.has(rule.protoChainId) ||
// Check if entire API is polyfilled (ex. `Promise`)
polyfills.has(rule.protoChain[0])
);
}
const getRulesForTargets = memoize((targetsJSON: string): Object => {
const targets = JSON.parse(targetsJSON);
const result = {
CallExpression: [],
NewExpression: [],
MemberExpression: []
};
rules.forEach(rule => {
if (rule.getUnsupportedTargets(rule, targets).length === 0) return;
result[rule.astNodeType].push(rule);
});
return result;
});
export default {
meta: {
docs: {
description: 'Ensure cross-browser API compatibility',
category: 'Compatibility',
url:
'https://github.com/amilajack/eslint-plugin-compat/blob/master/docs/rules/compat.md',
recommended: true
},
fixable: 'code',
schema: [{ type: 'string' }]
},
create(context: Context): ESLint {
// Determine lowest targets from browserslist config, which reads user's
// package.json config section. Use config from eslintrc for testing purposes
const browserslistConfig: BrowserListConfig =
context.settings.browsers ||
context.settings.targets ||
context.options[0];
const browserslistTargets = Versioning(
DetermineTargetsFromConfig(context.getFilename(), browserslistConfig)
);
// Stringify to support memoization; browserslistConfig is always an array of new objects.
const targetedRules = getRulesForTargets(
JSON.stringify(browserslistTargets)
);
const errors = [];
function handleFailingRule(rule: Node, node: ESLintNode) {
if (isPolyfilled(context, rule)) return;
errors.push({
node,
message: [
generateErrorName(rule),
'is not supported in',
rule.getUnsupportedTargets(rule, browserslistTargets).join(', ')
].join(' ')
});
}
const identifiers = new Set();
return {
CallExpression: lintCallExpression.bind(
null,
handleFailingRule,
targetedRules.CallExpression
),
NewExpression: lintNewExpression.bind(
null,
handleFailingRule,
targetedRules.NewExpression
),
MemberExpression: lintMemberExpression.bind(
null,
handleFailingRule,
targetedRules.MemberExpression
),
// Keep track of all the defined variables. Do not report errors for nodes that are not defined
Identifier(node: ESLintNode) {
if (node.parent) {
const { type } = node.parent;
if (
// ex. const { Set } = require('immutable');
type === 'Property' ||
// ex. function Set() {}
type === 'FunctionDeclaration' ||
// ex. const Set = () => {}
type === 'VariableDeclarator' ||
// ex. class Set {}
type === 'ClassDeclaration' ||
// ex. import Set from 'set';
type === 'ImportDefaultSpecifier' ||
// ex. import {Set} from 'set';
type === 'ImportSpecifier' ||
// ex. import {Set} from 'set';
type === 'ImportDeclaration'
) {
identifiers.add(node.name);
}
}
},
'Program:exit': () => {
// Get a map of all the variables defined in the root scope (not the global scope)
// const variablesMap = context.getScope().childScopes.map(e => e.set)[0];
errors
.filter(error => !identifiers.has(getName(error.node)))
.forEach(node => context.report(node));
}
};
}
};
| JavaScript | 0.000001 | @@ -2447,22 +2447,22 @@
-fixable: 'code
+type: 'problem
',%0A
|
398dd5f2e7949066800b0dae2b874472e2ffafe4 | Bump Version | js/osg/osg.js | js/osg/osg.js | /** -*- compile-command: "jslint-cli osg.js" -*- */
var osg = {};
osg.version = '0.0.7';
osg.copyright = 'Cedric Pinson - cedric.pinson@plopbyte.com';
osg.instance = 0;
osg.version = 0;
osg.log = function (str) {
if (window.console !== undefined) {
window.console.log(str);
}
};
osg.info = function (str) { osg.log(str); };
osg.debug = function (str) { osg.log(str); };
osg.DEBUG = 0;
osg.INFO = 1;
osg.NOTICE = 2;
osg.setNotifyLevel = function (level) {
var log = function (str) {
if (window.console !== undefined) {
window.console.log(str);
}
};
var dummy = function () {};
osg.debug = dummy;
osg.info = dummy;
osg.log = dummy;
if (level <= osg.DEBUG) {
osg.debug = log;
}
if (level <= osg.INFO) {
osg.info = log;
}
if (level <= osg.NOTICE) {
osg.log = log;
}
};
osg.reportErrorGL = false;
osg.ReportWebGLError = false;
osg.init = function () {
osg.setNotifyLevel(osg.NOTICE);
};
osg.checkError = function (error) {
if (error === 0) {
return;
}
if (error === 0x0500) {
osg.log("detected error INVALID_ENUM");
} else if (error === 0x0501) {
osg.log("detected error INVALID_VALUE");
} else if (error === 0x0502) {
osg.log("detected error INVALID_OPERATION");
} else if (error === 0x0505) {
osg.log("detected error OUT_OF_MEMORY");
} else if (error === 0x0506) {
osg.log("detected error INVALID_FRAMEBUFFER_OPERATION");
} else {
osg.log("detected error UNKNOWN");
}
};
// from jquery
osg.isArray = function ( obj ) {
return toString.call(obj) === "[object Array]";
};
osg.extend = function () {
// Save a reference to some core methods
var toString = Object.prototype.toString,
hasOwnPropertyFunc = Object.prototype.hasOwnProperty;
var isFunction = function (obj) {
return toString.call(obj) === "[object Function]";
};
var isArray = osg.isArray;
var isPlainObject = function ( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwnPropertyFunc.call(obj, "constructor") &&
!hasOwnPropertyFunc.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwnPropertyFunc.call( obj, key );
};
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction (target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) !== null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging object literal values or arrays
if ( deep && copy && ( isPlainObject(copy) || isArray(copy) ) ) {
var clone = src && ( isPlainObject(src) || isArray(src) ) ? src
: isArray(copy) ? [] : {};
// Never move original objects, clone them
target[ name ] = osg.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
osg.objectInehrit = function (base, extras) {
function F(){}
F.prototype = base;
var obj = new F();
if(extras) {osg.objectMix(obj, extras, false); }
return obj;
};
osg.objectMix = function (obj, properties, test){
for (var key in properties) {
if(!(test && obj[key])) { obj[key] = properties[key]; }
}
return obj;
};
osg.objectType = {};
osg.objectType.type = 0;
osg.objectType.generate = function (arg) {
var t = osg.objectType.type;
osg.objectType[t] = arg;
osg.objectType[arg] = t;
osg.objectType.type += 1;
return t;
};
osg.Float32Array = Float32Array;
osg.Int32Array = Int32Array;
osg.Uint16Array = Uint16Array;
| JavaScript | 0 | @@ -83,9 +83,9 @@
0.0.
-7
+8
';%0Ao
|
1823d644979590fc172eb7b777d8c0786b52626d | Update the converter | src/sass-to-scss.js | src/sass-to-scss.js | import _ from 'lodash';
import p from 'prelude-ls';
var mixin_alias_regex = /(^\s*)=(\s*)/;
var include_alias_regex = /(^\s*)\+(\s*)/;
var warnOnEmptyFile = function (path) {
console.log('Destination (' + path + ') not written because compiled files were empty.');
};
var replaceIncludeAlias = function(line){
return line.replace(include_alias_regex, function(match, spacesBefore, spacesAfter){
return spacesBefore + '@include' + (spacesAfter !== '' ? spacesAfter : ' ');
});
};
var replaceMixinAlias = function(line){
return line.replace(mixin_alias_regex, function(match, spacesBefore, spacesAfter){
return spacesBefore + '@mixin' + (spacesAfter !== '' ? spacesAfter : ' ');
});
};
var insertBeforeComment = function(inserted, text){
var index = text.indexOf('//');
if(index > -1) {
return text.slice(0, index) + inserted + text.substr(index);
} else {
return text + inserted;
}
};
var splitBefore = function(before, text){
var index = text.indexOf(before);
if(index > -1) {
return [text.slice(0, index), text.substr(index)];
} else {
return [text];
}
};
var insertBeforeClosingBrackets = function(inserted, text){
var match = text.match(/.*(#{([*+\-\$\w\s\d])*})/);
var start = '';
var end = text;
if(match){
start = match[0];
end = text.substr(start.length);
}
var splittedBeforeComments = splitBefore('//', end);
var beforeComments = splittedBeforeComments[0];
var splittedBeforeBrackets = splitBefore('}', beforeComments);
var beforeBrackets = splittedBeforeBrackets[0];
var value = beforeBrackets + inserted;
if (splittedBeforeBrackets[1]) {
value += splittedBeforeBrackets[1];
}
if (splittedBeforeComments[1]) {
value += splittedBeforeComments[1];
}
return start + value;
};
var convertSassToScss = function(input){
var lines, lastBlockLineIndex, braces, bracesString;
function fn$(it){
return lines.indexOf(it);
}
function fn1$(it){
return it.indentation > lines[idx].indentation;
}
if (input != null) {
var raw_lines = _.reject(
input.split('\n'), // split every lines
function(line){
// reject empty or \* *\ comment only lines
return line.match(/^\s*(\/\*.*\*\/.*)?(\/{2}.*)?$/);
}
);
// Cleanup lines and add indentation information
lines = _.map(raw_lines, function(line){
line = replaceIncludeAlias(line);
line = replaceMixinAlias(line);
var match = line.match(/^\s+/);
return {
indentation: match != null ? match[0].length : 0,
text: line
};
});
for (var idx in lines) {
idx = parseInt(idx, 10);
var line = lines[idx];
if (line.text.match(/[a-z>~*]+/)) {
lastBlockLineIndex = p.last(
p.map(fn$)(
p.takeWhile(fn1$)(
p.drop(idx + 1)( lines))));
if (lastBlockLineIndex != null) {
lines[idx].text = insertBeforeComment('{', lines[idx].text);
lines[lastBlockLineIndex].text = insertBeforeComment('}', lines[lastBlockLineIndex].text);
} else {
lines[idx].text = insertBeforeClosingBrackets(';', lines[idx].text );
}
}
}
// Return lines content joined in a single string
return _.map(lines, function(it){
return it.text;
}).join('\n');
}
};
export default convertSassToScss; | JavaScript | 0.000002 | @@ -42,16 +42,26 @@
elude-ls
+/lib/index
';%0A%0Avar
|
646d18032ed9a8ce8771c8ad426a3fa160ff7140 | changed pi_times_two to tau | js/qjnyyap.js | js/qjnyyap.js | function draw(){
buffer.clearRect(
0,
0,
width,
height
);
buffer.save();
buffer.translate(
x,
y
);
for(var vertex in vertices){
buffer.fillStyle = vertices[vertex]['color'];
buffer.fillRect(
vertices[vertex]['x'],
vertices[vertex]['y'],
10,
10
);
}
buffer.restore();
canvas.clearRect(
0,
0,
width,
height
);
canvas.drawImage(
document.getElementById('buffer'),
0,
0
);
window.requestAnimationFrame(draw);
}
function logic(){
for(var vertex in vertices){
vertices[vertex]['rotation'] += rotation_rate * (25 - vertices[vertex]['layer']);
if(vertices[vertex]['rotation'] >= pi_times_two){
vertices[vertex]['rotation'] -= pi_times_two;
}else if(vertices[vertex]['rotation'] < 0){
vertices[vertex]['rotation'] += pi_times_two;
}
vertices[vertex]['x'] = vertices[vertex]['layer'] * 10 * Math.cos(vertices[vertex]['rotation']) - 5;
vertices[vertex]['y'] = vertices[vertex]['layer'] * 10 * Math.sin(vertices[vertex]['rotation']) - 5;
}
}
function resize(){
height = window.innerHeight;
document.getElementById('buffer').height = height;
document.getElementById('canvas').height = height;
y = height / 2;
width = window.innerWidth;
document.getElementById('buffer').width = width;
document.getElementById('canvas').width = width;
x = width / 2;
}
var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var height = 0;
var pi_times_two = Math.PI * 2;
var rotation_rate = .005;
var vertices = [];
var width = 0;
var x = 0;
var y = 0;
window.onkeydown = function(e){
var key = e.keyCode || e.which;
// +: rotation_rate += 0.001;
if(key == 187){
rotation_rate += 0.001;
// -: rotation_rate -= 0.001;
}else if(key == 189){
rotation_rate -= 0.001;
// ESC: rotation_rate = 0;
}else if(key == 27){
rotation_rate = 0;
}
};
window.onload = function(e){
resize();
var loop_counter = 23;
do{
var inner_counter = loop_counter;
do{
vertices.push({
'color': '#fff',
'layer': loop_counter + 1,
'rotation': inner_counter,
'x': 0,
'y': 0,
});
}while(inner_counter--);
}while(loop_counter--);
window.requestAnimationFrame(draw);
window.setInterval(
'logic()',
30
);
};
window.onresize = resize;
| JavaScript | 0.998693 | @@ -785,28 +785,19 @@
on'%5D %3E=
-pi_times_two
+tau
)%7B%0A
@@ -835,28 +835,19 @@
on'%5D -=
-pi_times_two
+tau
;%0A
@@ -936,28 +936,19 @@
on'%5D +=
-pi_times_two
+tau
;%0A
@@ -1675,60 +1675,51 @@
var
-pi_times_two = Math.PI * 2;%0Avar rotation_rate = .005
+rotation_rate = .005;%0Avar tau = Math.PI * 2
;%0Ava
|
b153a1a269b12dc2c53f97265c25b3006b30b57e | refactor game | src/scripts/game.js | src/scripts/game.js | // Description:
// 遊ぶ
// Commands:
// attack {user} - attack
// cure {user} - cure
// raise {user} - ふっかつ
//
"use strict"
const Cron = require("cron").CronJob;
const NodeQuest = require("node-quest");
const UserStates = NodeQuest.UserStates;
const Game = NodeQuest.Game;
const SpellRepository = require("../game/SpellRepository.js");
const UserRepository = require("../game/UserRepository.js");
const NegativeWordsRepository = require("../game/NegativeWordsRepository.js");
const MonsterRepository = require("../game/MonsterRepository.js");
const NegativeWords = require("../game/NegativeWords.js");
const negativeWordsRepository = new NegativeWordsRepository("http://yamiga.waka.ru.com/json/darkbot.json");
const negativeWords = new NegativeWords(negativeWordsRepository, console);
const spellRepository = new SpellRepository();
const monsterRepository = new MonsterRepository();
const game = new Game();
const lang = require("../game/lang/Ja.js");
const hubotSlack = require("hubot-slack");
const SlackTextMessage = hubotSlack.SlackTextMessage;
const isSlackTextMessage = (message) => (message instanceof SlackTextMessage);
new Cron("0 0 * * 1", () => {
game.users.forEach((u) => {
u.cured(Infinity);
});
}, null, true, "Asia/Tokyo");
new Cron("0 0 * * *", () => {
game.users.forEach((u) => {
u.magicPoint.changed(Infinity);
});
}, null, true, "Asia/Tokyo");
module.exports = (robot) => {
const userRepository = new UserRepository(robot.brain, robot.adapter.client ? robot.adapter.client.users : {});
const shakai = monsterRepository.getByName("社会");
robot.brain.once("loaded", (data) => {
const users = userRepository.get().concat(monsterRepository.get());
users.forEach((u) => {
u.spells = spellRepository.get();
u.hitPoint.on("changed", (data) => {
userRepository.save(game.users);
});
u.magicPoint.on("changed", (data) => {
userRepository.save(game.users);
});
});
game.setUsers(users);
});
robot.hear(/^attack (.+)/i, (res) => {
const actor = game.findUser(res.message.user.name);
if (!actor) {
return
}
const target = game.findUser(res.match[1]);
if (!target) {
return res.send(lang.actor.notarget(actor));
}
const result = actor.attack(target)
switch (result) {
case UserStates.TargetDead:
return res.send(lang.target.dead(target));
case UserStates.ActorDead:
return res.send(lang.actor.dead(target));
}
const hit = result.attack.hit;
const point = result.attack.value;
hit ?
res.send(lang.attack.default(actor, target, point)):
res.send(lang.attack.miss(target));
});
robot.hear(/^status (.+)/i, (res) => {
const target = game.findUser(res.match[1])
const message = target ?
lang.status.default(target) :
lang.actor.notarget(target);
res.send(message)
res.send(`使える魔法: ${target.spells.map((s) => s.name).join(",")}`);
});
robot.hear(/.*/, (res) => {
if ( shakai === null ) {
return;
}
const target = game.findUser(res.message.user.name)
if ( !target || target.isDead() ) {
return;
}
const tokens = (res.message.tokenized || []).map((t) => {
return t.basic_form;
});
const count = negativeWords.countNegativeWords(tokens);
if(count <= 0) {
return
}
const results = Array(n).map((i) => actor.attack(target))
const attackedResults = results.filter((r) => typeof r !== 'symbol').filter((r) => r.attack.hit);
const point = attackedResults.reduce((pre, cur) => pre + cur.attack.value, 0);
if( attackedResults.length > 0 ) {
n === 1 ?
res.send(lang.attack.default(shakai, target, point)):
res.send(lang.attack.multiple(shakai, target, point, n));
target.isDead() && res.send(lang.target.dead(target));
} else {
res.send(lang.attack.miss(target));
}
});
robot.hear(/(.+)/, (res) => {
if(!isSlackTextMessage(res.message)) {
return;
}
const messages = res.message.rawText.split(" ")
if(messages.length < 2) {
return;
}
const spellName = messages[0];
const actor = game.findUser(res.message.user.name);
const target = messages.splice(1).map(
(name) => game.findUser(name)
).filter(
(user) => user !== null
).pop();
if (actor.spells.filter((s) => s.name === spellName).length <= 0) {
return;
} else if (!target) {
return res.send(lang.actor.notarget(actor));
}
const result = actor.cast(spellName, target);
switch (result) {
case UserStates.NoTargetSpell:
return;
case UserStates.NotEnoughMagicPoint:
return res.send(lang.actor.nomagicpoint(actor));
case UserStates.TargetDead:
return res.send(lang.target.dead(target));
case UserStates.ActorDead:
return res.send(lang.actor.dead(actor));
}
res.send(lang.spell.cast(actor, spellName));
if( result.effects.attack !== null ) {
res.send(lang.target.damaged(result.target, result.effects.attack));
result.target.isDead() && res.send(lang.attack.dead(result.target));
}
const statusEffectResult = result.effects.status.filter((e) => e.effective)
if(result.effects.status.length > 0) {
(statusEffectResult.length > 0) ?
res.send(lang.raise.default(result.target)):
res.send(lang.actor.noeffect(result.actor));
} else if( result.effects.cure !== null) {
res.send(lang.cure.default(result.target));
}
});
}
| JavaScript | 0.000019 | @@ -1578,62 +1578,8 @@
%7B%7D);
-%0A const shakai = monsterRepository.getByName(%22%E7%A4%BE%E4%BC%9A%22);
%0A%0A
@@ -3194,32 +3194,90 @@
.*/, (res) =%3E %7B%0A
+ const shakai = monsterRepository.getByName(%22%E7%A4%BE%E4%BC%9A%22);%0A
if ( sha
@@ -3285,32 +3285,32 @@
ai === null ) %7B%0A
-
retu
@@ -3717,17 +3717,39 @@
lts
-= Array(n
+ = Array(count).fill(1
).ma
@@ -3757,21 +3757,22 @@
((i) =%3E
-actor
+shakai
.attack(
@@ -3810,16 +3810,18 @@
Results
+
= result
@@ -3908,16 +3908,28 @@
t point
+
= attack
@@ -4042,17 +4042,21 @@
-n
+count
=== 1 ?
@@ -4195,17 +4195,21 @@
point,
-n
+count
));%0A
|
1ee0865acdec369267b64faa3b39c784f51ebf1d | Allow open rowlink with ctrl/middle-mouse click (fixes #422) | js/rowlink.js | js/rowlink.js | /* ============================================================
* Bootstrap: rowlink.js v3.1.3
* http://jasny.github.io/bootstrap/javascript/#rowlink
* ============================================================
* Copyright 2012-2014 Arnold Daniels
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
+function ($) { "use strict";
var Rowlink = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Rowlink.DEFAULTS, options)
this.$element.on('click.bs.rowlink', 'td:not(.rowlink-skip)', $.proxy(this.click, this))
}
Rowlink.DEFAULTS = {
target: "a"
}
Rowlink.prototype.click = function(e) {
var target = $(e.currentTarget).closest('tr').find(this.options.target)[0]
if ($(e.target)[0] === target) return
e.preventDefault();
if (target.click) {
target.click()
} else if (document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
target.dispatchEvent(evt);
}
}
// ROWLINK PLUGIN DEFINITION
// ===========================
var old = $.fn.rowlink
$.fn.rowlink = function (options) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.rowlink')
if (!data) $this.data('bs.rowlink', (data = new Rowlink(this, options)))
})
}
$.fn.rowlink.Constructor = Rowlink
// ROWLINK NO CONFLICT
// ====================
$.fn.rowlink.noConflict = function () {
$.fn.rowlink = old
return this
}
// ROWLINK DATA-API
// ==================
$(document).on('click.bs.rowlink.data-api', '[data-link="row"]', function (e) {
if ($(e.target).closest('.rowlink-skip').length !== 0) return
var $this = $(this)
if ($this.data('bs.rowlink')) return
$this.rowlink($this.data())
$(e.target).trigger('click.bs.rowlink')
})
}(window.jQuery);
| JavaScript | 0 | @@ -1075,16 +1075,35 @@
.rowlink
+ mouseup.bs.rowlink
', 'td:n
@@ -1236,16 +1236,25 @@
nction(e
+, ctrlKey
) %7B%0A
@@ -1328,16 +1328,17 @@
get)%5B0%5D%0A
+%0A
if (
@@ -1375,42 +1375,186 @@
urn%0A
-%0A e.preventDefault();%0A%0A if (
+ if (e.type === 'mouseup' && e.which !== 2) return%0A%0A e.preventDefault();%0A ctrlKey = ctrlKey %7C%7C e.ctrlKey %7C%7C (e.type === 'mouseup' && e.which === 2)%0A%0A if (!ctrlKey &&
targ
@@ -1747,21 +1747,23 @@
, 0, 0,
-false
+ctrlKey
, false,
@@ -2423,16 +2423,44 @@
data-api
+ mouseup.bs.rowlink.data-api
', '%5Bdat
@@ -2486,24 +2486,78 @@
ction (e) %7B%0A
+ if (e.type === 'mouseup' && e.which !== 2) return%0A
if ($(e.
@@ -2707,16 +2707,62 @@
.data())
+%0A%0A var ctrlKey = e.ctrlKey %7C%7C e.which === 2
%0A $(e
@@ -2792,24 +2792,35 @@
.bs.rowlink'
+, %5BctrlKey%5D
)%0A %7D)%0A%0A%7D(wi
|
e689162e6e7c582b280e3441554759e30f8432f9 | Fix import paths. | src/scripts/main.js | src/scripts/main.js | import Boot from './states/Boot';
import Preload from './states/Preload';
import Logo from './states/Logo';
import Title from './states/Title';
import StageSelect from './states/StageSelect';
import CreditsAI from './states/CreditsAI';
import CreditsRB from './states/CreditsRB';
import Game from './states/Game';
export default {
start () {
var game = new Phaser.Game(240, 160, Phaser.WEBGL, 'game');
game.state.add('Boot', Boot);
game.state.add('Preload', Preload);
game.state.add('Logo', Logo);
game.state.add('Title', Title);
game.state.add('StageSelect', StageSelect);
game.state.add('CreditsAI', CreditsAI);
game.state.add('CreditsRB', CreditsRB);
game.state.add('Game', Game);
game.state.start('Boot');
return game;
}
};
| JavaScript | 0 | @@ -14,26 +14,24 @@
from '
-./
states/Boot'
@@ -53,26 +53,24 @@
d from '
-./
states/Prelo
@@ -95,26 +95,24 @@
from '
-./
states/Logo'
@@ -134,26 +134,24 @@
from '
-./
states/Title
@@ -174,26 +174,24 @@
elect from '
-./
states/Stage
@@ -216,34 +216,32 @@
editsAI from '
-./
states/CreditsAI
@@ -264,26 +264,24 @@
sRB from '
-./
states/Credi
@@ -316,10 +316,8 @@
om '
-./
stat
|
c790af12b667d4dc7656703b5d32bb0896aa4da9 | Remove defaults on main query builder call | src/search/index.js | src/search/index.js | import QueryBuilder from './query-builder'
import * as index from './search-index'
import mapResultsToPouchDocs from './map-search-to-pouch'
/**
* Results should always contain a `document` key containing the indexed doc.
* In some special cases (if something is being removed, but t hasn't finished yet),
* this could be `undefined`. May add more filters here if any other cases are encountered.
*/
const filterBadlyStructuredResults = results =>
results.filter(result => result.document != null)
export default async function indexSearch({
query,
startDate,
endDate,
skip,
limit = 10,
getTotalCount = false,
}) {
query = query.trim() // Don't count whitespace searches
// Create SI query
const indexQuery = new QueryBuilder()
.searchTerm(query || '*') // Search by wildcard by default
.startDate(startDate)
.endDate(endDate)
.skipUntil(skip || undefined)
.limit(limit || 10)
.get()
// Get index results, filtering out any unexpectedly structured results
let results = await index.search(indexQuery)
results = filterBadlyStructuredResults(results)
// Short-circuit if no results
if (!results.length) {
return {
docs: [],
resultsExhausted: true,
totalCount: getTotalCount ? 0 : undefined,
}
}
// Match the index results to data docs available in Pouch, consolidating meta docs
const docs = await mapResultsToPouchDocs(results, { startDate, endDate })
return {
docs,
resultsExhausted: false,
totalCount: getTotalCount ? await index.count(indexQuery) : undefined,
}
}
| JavaScript | 0 | @@ -797,49 +797,9 @@
uery
- %7C%7C '*') // Search by wildcard by default
+)
%0A
@@ -878,21 +878,8 @@
skip
- %7C%7C undefined
)%0A
@@ -900,14 +900,8 @@
imit
- %7C%7C 10
)%0A
|
c0f132ff1554e7359bf02c1c81d98f2d9e273896 | Update UDPefef | benchmark.js | benchmark.js | //
/**
* Created by tungtouch on 2/9/15.
*/
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var colors = require('colors');
var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');
var max = 1000;
var numCluster = 50;
var arr = [];
for (var i = 0; i < max; i++) {
arr.push(i);
}
var a = 0;
//[2GB]128.199.126.250 [8GB]128.199.109.202
if (cluster.isMaster) {
// Keep track of http requests
var numReqs = 0;
var totalReqs = 0;
var second = 0;
setInterval(function() {
console.log(
colors.red("Gói tin/s: ", numReqs), " | ",
colors.yellow("Tổng gói tin: ", totalReqs), " | ",
colors.blue("Thời gian: ", second++ +"s"));
numReqs = 0;
if(totalReqs == (max * numCluster)) {
console.log(colors.cyan("\n-------------------------------"));
console.log("Tổng thời gian: ", second-1 + "s", " | Tổng số gói tin:", totalReqs);
console.log(colors.cyan("Kết quả hệ thống: ", colors.bold(totalReqs / second)), " Thiết bị/giây ! \n");
//process.exit(1);
}
}, 1000);
// Count requestes
function messageHandler(msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1;
totalReqs +=1;
}
}
// Start workers and listen for messages containing notifyRequest
for (var i = 0; i < numCluster; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message', messageHandler);
});
} else {
var q = async.queue(function(index, cb){
//console.log("Index: ", index);
setTimeout(function () {
client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
//console.log("Request : ", a++);
process.send({ cmd: 'notifyRequest' });
if(err){
console.log('ERROR :', err);
}
cb(err);
});
}, 20);
});
q.push(arr);
} | JavaScript | 0 | @@ -1223,18 +1223,16 @@
-//
process.
|
3b7551dff9449a7729c0262b065b0a6120910a37 | read only mode | js/toolbar.js | js/toolbar.js | define(['jquery','underscore','events','mustache','mybackbone','conf', "text!../templates/toolbar.html", "qtip", "editor"],
function ($,_,events,mustache,mybackbone,conf,toolbartpl, qtip, ed) {
"use strict";
// handle keyboard shortcuts also
var keyboardShortcuts = {};
var widgets = {};
var buttons = {};
var editors = {};
var colors = [];
function randColor() {
return "#"+Math.floor(Math.random()*16777215).toString(16);
}
function itemSort(a,b) {
if ( ( a.index === undefined ) && (b.index === undefined) ) return 0;
if ( ( a.index !== undefined ) && (b.index === undefined) ) return 1;
if ( ( a.index === undefined ) && (b.index !== undefined) ) return -1;
return a.index - b.index;
}
function registerWidget(data) {
// widget is a backbone view that renders widget
// modes is an array of modes in which this widget is active
// toolbar takes care that widget.el exists when widget.render
// is called
var id = data.id;
if (id in widgets) {
throw "Trying to reregister widget " + id;
}
widgets [id] = data;
}
$('body').on('keydown',function(ev) {
var key = view.mode+'-'+ev.which;
var event = keyboardShortcuts[key];
if (event) {
events.trigger(event);
}
});
function ping(){
var re = new RegExp("[0-9a-f]{32}");
var uidarr = re.exec(document.URL);
var uid = uidarr[0]
var options = {
type:'GET',
url: "/api/id/"+uid+"/ping",
statusCode: {
401: function() {events.trigger("saveFailed401", 'pinging the backend')},
403: function() {events.trigger("saveFailed", 'Forbidden')},
}
}
var readonly = false;
$.ajax(options)
.done(function(data){
console.log(data)
if(data.code == 13){
console.log("ReadOnly");
readonly = true;
}
editors = data.users;
for(var editor in editors){
if(colors[editor] == null) {
colors[editor] = randColor();
}
}
view.render(readonly);
})
}
var View = mybackbone.View.extend({
initialize: function() {
// we must wait for editor before firing initial cbs
// BUG: race condition if user clicks between toolbar render
// and editor render
this._editorRendered = $.Deferred();
conf.buttons.map(_.bind(this.registerButton,this));
conf.shortcuts.map(_.bind(this.registerKeyboardShortcut,this));
(function(view){
window.setInterval(function(){
ping();
}, 30000);
})(this)
},
el : '#toolbar',
myEvents: {
'changeMode': 'changeMode',
'editorRendered': 'editorRendered'
},
events: {
'click button': 'handleClick'
},
myModes: ['page','document'],
setViewActive: function (mode) {
this.render();
},
handleTag: function(event){
var ch = event.currentTarget.getAttribute('data-character');
console.log(ch)
events.trigger("tagWord")
},
editorRendered: function () {
this._editorRendered.resolve();
},
registerKeyboardShortcut: function (shortcut) {
if (shortcut.which in keyboardShortcuts) {
throw "Trying to reregister shortcut for " + shortcut.code;
}
for (var i in shortcut.modes) {
var mode = shortcut.modes[i];
var key = mode+'-'+shortcut.code;
keyboardShortcuts [key] = shortcut.event;
// console.log(shortcut)
}
},
registerButton: function (data) {
var id = data.id;
if (data.index === undefined) {
throw 'Sort index must be given for buttons.';
}
if (id in buttons) {
throw "Trying to reregister button " + id;
}
buttons [id] = data;
if (data.toggle && (!data.suppressInitialCB)) {
this._editorRendered.done( function () {
events.trigger(data.event,data.active);
});
}
},
handleClick: function (ev) {
var id = ev.currentTarget.id;
var b = buttons[id];
if (b === undefined) return;
if (b.modes.indexOf(this.currentMode()) == -1) return;
if (b.toggle) {
var toggled = !($(ev.currentTarget).hasClass("active"));
events.trigger(b.event,toggled);
} else {
events.trigger(b.event, ev);
}
events.trigger('refocus');
var myEvent = 'button-'+id+'-clicked';
events.trigger(myEvent);
},
render: function(opt) {
var that = this;
var buttonArray = buttons;
if(opt){
buttonArray = _.filter(buttons, function(obj){
return obj.id != "save";
});
}
var context = {
widgets: _.map(widgets, function (w) {
return w;
}),
buttons: _.map(buttonArray, function (b) {
return {
id: b.id,
index: b.index,
classes: 'btn' +
(b.active ? ' active' : '') +
(b.modes.indexOf(that.mode) != -1 ?
'' :
' disabled'),
extra: b.toggle && 'data-toggle="button"' || '',
icon: b.icon,
title: b.title,
text: b.text
};
}),
userbox: _.map(editors, function (e, key) {
return {
user: key,
color: colors[key]
};
})
};
context.widgets.sort(itemSort);
context.buttons.sort(itemSort);
console.log(context);
this.$el.html(mustache.render(toolbartpl,context));
for (var i in widgets) {
//if (widgets[i].modes)
var view = widgets[i].view;
view.setElement('#' + i);
view.render();
}
$(".userbox").qtip({
content:{
attr: 'data-tooltip'
}
});
//this.$el.button(); // enable bootstrap button code
}
});
var view = new View();
return {
view : view,
registerWidget : registerWidget
};
});
| JavaScript | 0.000001 | @@ -2366,18 +2366,16 @@
donly);%0A
-%0A%0A
@@ -2376,24 +2376,25 @@
%7D)
+;
%0A %7D%0A v
@@ -2624,32 +2624,52 @@
d editor render%0A
+ ping();%0A
this
@@ -2837,25 +2837,24 @@
cut,this));%0A
-%0A
|
5b262c2a6f44cf5932b18db007becd12293f93f0 | Change server listen port | src/server/index.js | src/server/index.js | import "babel-polyfill";
import InfernoServer from "inferno-server";
import createMemoryHistory from "history/createMemoryHistory";
import favicon from "koa-favicon";
import handlebars from "koa-handlebars";
import koa from "koa";
import mount from "koa-mount";
import route from "koa-route";
import serve from "koa-static";
import sqlite3 from "sqlite3";
import {ArgumentParser} from "argparse";
import App from "../shared/components/app";
import {State} from "../shared/state";
import {createRoutes} from "../shared/routes";
function initServer() {
let args = (function() {
let parser = new ArgumentParser();
parser.addArgument(["-d", "--db"], {
required: true,
help: "path to scrape-fcc sqlite database",
});
return parser.parseArgs();
})();
let db = new sqlite3.Database(args.db, sqlite3.OPEN_READONLY);
let app = koa();
app.use(handlebars());
app.use(favicon("static/favicon.ico"));
app.use(mount("/static", serve("static")));
app.use(route.get("/api/records", createRecordFetcher(db)));
app.use(function*() {
let hist = createMemoryHistory();
let state = new State(hist);
let router = createRoutes(state);
hist.push(this.request.url);
router.handlePath(hist.location);
let sidebar = InfernoServer.renderToString(App(state, hist));
yield this.render("index", {state, sidebar});
});
app.listen(3000);
}
function createRecordFetcher(db) {
const QUERY = `
select records.rkey, callsign, title, eligibility,
locations.lkey, latitude, longitude,
frequencies.fkey, frequency, power,
emission
from records, recordDetails, frequencies, locations, emissions
where recordDetails.rkey = records.rkey and
locations.rkey = records.rkey and
frequencies.rkey = records.rkey and
frequencies.lkey = locations.lkey and
emissions.rkey = records.rkey and
emissions.fkey = frequencies.fkey
order by records.rkey, locations.lkey, frequencies.fkey
`;
return function*() {
this.body = yield new Promise((resolve, reject) => {
let locs = [];
let prevLoc = null;
let prevFreq = null;
let prevEmission = null;
let loc = null;
let freq = null;
db.each(QUERY, (err, row) => {
if (err) {
return reject(err);
}
let {rkey, lkey, fkey} = row;
if (lkey !== prevLoc) {
prevLoc = lkey;
prevFreq = null;
let csIdx = row.title.indexOf(row.callsign);
let dashIdx = row.title.slice(csIdx).indexOf("-");
if (locs[lkey] && locs[lkey].rkey !== rkey) {
throw new Error("lkey clash");
}
loc = {
rkey: rkey,
lkey: lkey,
callsign: row.callsign,
desc: row.title.slice(csIdx + dashIdx + 2),
elig: row.eligibility || "",
lat: row.latitude,
lng: row.longitude,
freqs: [],
};
locs.push(loc);
}
if (fkey !== prevFreq) {
prevFreq = fkey;
prevEmission = null;
freq = {
fkey: fkey,
power: row.power,
freq: row.frequency,
emissions: [],
};
loc.freqs.push(freq);
}
if (row.emission !== prevEmission) {
prevEmission = row.emission;
freq.emissions.push(row.emission);
}
}, err => {
if (err) {
reject(err);
} else {
resolve(locs);
}
});
});
};
}
if (process.env.NODE_ENV !== "test") {
initServer();
}
| JavaScript | 0.000001 | @@ -1467,12 +1467,12 @@
ten(
-3000
+9428
);%0A%7D
|
ddc5af1ef249f50ebfd0a6eeab36eb0980981839 | add multi view handler supports | src/server/index.js | src/server/index.js | import Koa from 'koa';
import serve from 'koa-static';
import dotenv from 'dotenv';
import path from 'path';
import winston from 'winston';
import config from './config';
import bootstrap from './apps';
dotenv.config();
const server = new Koa();
winston.level = config.debug ? 'debug' : 'info';
if (config.env === 'staging') {
const dist = path.resolve(process.cwd(), config.static.root);
server.use(serve(dist));
}
bootstrap(server);
server.listen(config.port, () => {
winston.info(`Server started at port ${config.port}`);
});
export default server;
| JavaScript | 0 | @@ -52,37 +52,8 @@
c';%0A
-import dotenv from 'dotenv';%0A
impo
@@ -173,25 +173,8 @@
';%0A%0A
-dotenv.config();%0A
cons
|
dcf3b88a466c82c06715badb541e09f3c9d64f1b | Add single player wrapper div | src/singlePlayer.js | src/singlePlayer.js | import React, { Component } from 'react'
import { propTypes, defaultProps } from './props'
import Player from './Player'
import { isEqual, getConfig } from './utils'
export default function createSinglePlayer (activePlayer) {
return class SinglePlayer extends Component {
static displayName = `${activePlayer.displayName}Player`
static propTypes = propTypes
static defaultProps = defaultProps
static canPlay = activePlayer.canPlay
shouldComponentUpdate (nextProps) {
return !isEqual(this.props, nextProps)
}
componentWillUpdate (nextProps) {
this.config = getConfig(nextProps, defaultProps)
}
render () {
if (!activePlayer.canPlay(this.props.url)) {
return null
}
return (
<Player
{...this.props}
activePlayer={activePlayer}
config={getConfig(this.props, defaultProps)}
/>
)
}
}
}
| JavaScript | 0 | @@ -71,100 +71,179 @@
rops
- %7D from './props'%0Aimport Player from './Player'%0Aimport %7B isEqual, getConfig %7D from './utils'
+, DEPRECATED_CONFIG_PROPS %7D from './props'%0Aimport %7B getConfig, omit, isEqual %7D from './utils'%0Aimport Player from './Player'%0A%0Aconst SUPPORTED_PROPS = Object.keys(propTypes)
%0A%0Aex
@@ -710,24 +710,79 @@
rops)%0A %7D%0A
+ ref = player =%3E %7B%0A this.player = player%0A %7D%0A
render (
@@ -874,17 +874,241 @@
-return (%0A
+const %7B style, width, height, wrapper: Wrapper %7D = this.props%0A const otherProps = omit(this.props, SUPPORTED_PROPS, DEPRECATED_CONFIG_PROPS)%0A return (%0A %3CWrapper style=%7B%7B ...style, width, height %7D%7D %7B...otherProps%7D%3E%0A
@@ -1115,24 +1115,26 @@
%3CPlayer%0A
+
%7B.
@@ -1147,16 +1147,45 @@
.props%7D%0A
+ ref=%7Bthis.ref%7D%0A
@@ -1214,16 +1214,18 @@
Player%7D%0A
+
@@ -1279,17 +1279,38 @@
-/
+ /%3E%0A %3C/Wrapper
%3E%0A
|
618fb80a5efd8d16c57cf916d07a112ab9de4742 | tidy up benchmark | benchmark.js | benchmark.js | require('web-audio-test-api');
/* global WebAudioTestAPI*/
WebAudioTestAPI.setState('AudioContext#createStereoPanner', 'enabled');
const Benchmark = require('benchmark');
const PublishedVirtualAudioGraph = require('virtual-audio-graph');
const DevelopmentVirtualAudioGraph = require('./dist/index');
const pingPongDelayParamsFactory = require('./spec/tools/pingPongDelayParamsFactory');
const runBenchmarkCode = function (virtualAudioGraph) {
const quietpingPongDelayParamsFactory = () => ({
0: ['gain', 'output'],
1: ['pingPongDelay', 0],
2: ['oscillator', 1],
});
virtualAudioGraph.defineNode(pingPongDelayParamsFactory, 'pingPongDelay');
virtualAudioGraph.defineNode(quietpingPongDelayParamsFactory, 'quietPingPongDelay');
virtualAudioGraph.update({
0: ['gain', 'output'],
});
virtualAudioGraph.update({
0: ['gain', 'output', {gain: 0.5}],
1: ['quietPingPongDelay', 0],
2: ['pingPongDelay', 1],
3: ['oscillator', 2],
});
virtualAudioGraph.update({
0: ['gain', 'output'],
});
virtualAudioGraph.update({
0: ['gain', 'output', {gain: 0.5}],
1: ['oscillator', 0, {type: 'triangle',
frequency: 1720,
detune: 14}],
2: ['oscillator', 0, {type: 'square',
frequency: 880,
detune: -2}],
3: ['oscillator', 0, {type: 'sine',
frequency: 440,
detune: 1}],
4: ['oscillator', 0, {type: 'sawtooth',
frequency: 220,
detune: -20}],
});
virtualAudioGraph.update({
0: ['gain', 'output'],
});
virtualAudioGraph.update({
0: ['gain', 'output', {gain: 0.5}],
1: ['pingPongDelay', 0],
2: ['oscillator', 1, {type: 'triangle',
frequency: 1720,
detune: 14}],
3: ['oscillator', 1, {type: 'square',
frequency: 880,
detune: -2}],
4: ['oscillator', 1, {type: 'sine',
frequency: 440,
detune: 1}],
5: ['oscillator', 1, {type: 'sawtooth',
frequency: 220,
detune: -20}],
});
virtualAudioGraph.update({
0: ['gain', 'output'],
});
};
new Benchmark.Suite()
.add('PublishedVirtualAudioGraph', function () {
runBenchmarkCode(new PublishedVirtualAudioGraph());
})
.add('DevelopmentVirtualAudioGraph', function() {
runBenchmarkCode(new DevelopmentVirtualAudioGraph());
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run({'async': true});
| JavaScript | 0.000001 | @@ -2404,25 +2404,13 @@
h',
-function () %7B%0A
+() =%3E
run
@@ -2452,29 +2452,24 @@
udioGraph())
-;%0A %7D
)%0A .add('De
@@ -2497,32 +2497,21 @@
Graph',
-function() %7B%0A
+() =%3E
runBenc
@@ -2555,21 +2555,16 @@
Graph())
-;%0A %7D
)%0A .on(
@@ -2576,29 +2576,16 @@
e',
-function(event) %7B%0A
+event =%3E
con
@@ -2614,21 +2614,16 @@
target))
-;%0A %7D
)%0A .on(
@@ -2638,24 +2638,13 @@
e',
-function() %7B%0A
+() =%3E
con
@@ -2652,17 +2652,17 @@
ole.log(
-'
+%60
Fastest
@@ -2668,12 +2668,10 @@
is
-' +
+$%7B
this
@@ -2706,14 +2706,11 @@
me')
-);%0A %7D
+%7D%60)
)%0A
@@ -2719,15 +2719,13 @@
un(%7B
-'
async
-'
: tr
|
8e05651d55171e48caf2cf77922a9e66f37b82e9 | Fix weird movement | src/sprites/Ship.js | src/sprites/Ship.js | import Phaser from 'phaser'
export default class extends Phaser.Sprite {
constructor ({ game, x, y, asset }) {
super(game, x, y, asset)
this.anchor.setTo(0.5)
// Set up the physics for this ship.
game.physics.enable(this, Phaser.Physics.ARCADE)
this.body.drag.set(100)
this.body.maxVelocity.set(200)
}
update () {
if (game.cursors.up.isDown) {
game.physics.arcade.accelerationFromRotation(this.rotation, 2000, this.body.acceleration)
} else {
this.body.acceleration.set(0)
}
if (game.cursors.left.isDown) {
this.body.angularVelocity = -300
} else if (game.cursors.right.isDown) {
this.body.angularVelocity = 300
} else {
this.body.angularVelocity = 0
}
if (game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
// shoot
}
}
}
| JavaScript | 0.000017 | @@ -22,16 +22,43 @@
haser'%0A%0A
+const movementSpeed = 500%0A%0A
export d
@@ -343,19 +343,29 @@
ity.set(
-200
+movementSpeed
)%0A %7D%0A%0A
@@ -481,12 +481,21 @@
on,
-2000
+movementSpeed
, th
|
61b6b65a8aff238fc4b5ed887ba005e3500d7f5c | fix config heroku file | src/startup/boot.js | src/startup/boot.js | let fs = require("fs");
let https = require("https");
let sequelize = require("./start-sequelize");
let logger = require('../logger.js');
module.exports = app => {
if (process.env.NODE_ENV !== "test") {
const configuration = app.configuration.server;
app.sequelize.sync().done(() => {
const port = configuration.port || 3000;
console.log(configuration);
app.listen(port, () => {
logger.info(`#### project-manager ####`);
logger.info(`Application worker ${process.pid} started...`);
logger.info(`listen in ${ip}:${port}`);
});
});
}
};
| JavaScript | 0 | @@ -559,14 +559,8 @@
in
-$%7Bip%7D:
$%7Bpo
|
66c40eaa8b4301902ddd0bd7a491ece90457d2af | Fix octal literal error | bin/build.js | bin/build.js | #!/usr/bin/env node --use_strict
const broccoli = require('broccoli')
const ncp = require('ncp')
const path = require('path')
const chalk = require('chalk')
const program = require('commander')
const utils = require('../lib/utils')
program
.option('-w, --watch', 'Rebuild site if files change')
.parse(process.argv)
if (!utils.isSite()) {
utils.log(chalk.red('No site in here!'))
process.exit(1)
}
const tree = broccoli.loadBrocfile()
const builder = new broccoli.Builder(tree)
function startWatching () {
const Watcher = require('broccoli-sane-watcher')
const watch = new Watcher(builder)
process.on('SIGINT', () => {
watch.close()
process.exit(0)
})
watch.on('change', results => {
if (!results.filePath) return
console.log(results)
})
watch.on('error', err => utils.log(err))
}
builder.build().then(results => {
const dir = typeof results === 'string' ? results : results.directory
const buildTime = results.totalTime
// Copy files from tmp folder to the destination directory
// And make sure to follow symlinks while doing so
ncp(dir, process.cwd() + '/dist', {dereference: true}, err => {
if (err) throw err
if (buildTime) {
// The original built time is in nanoseconds, so we need to convert it to milliseconds
utils.log(chalk.green(`Finished building after ${Math.floor(buildTime / 1e6)}ms.`))
} else {
utils.log(chalk.green('Finished building.'))
}
if (program.watch) {
return startWatching()
}
builder.cleanup().catch(err => utils.log(err))
})
}).catch(err => {
throw err
})
| JavaScript | 0.999187 | @@ -19,18 +19,15 @@
e --
-use_strict
+harmony
%0A%0Aco
|
49b02a4b7155057a5d7ca9a6b8017ab0c94b6c8b | update focus style | src/style/select.js | src/style/select.js | "use strict";
var selectStyle = {
style: {
borderBottom: '1px #ccc solid',
boxSizing: 'border-box',
cursor: 'pointer',
height: 34,
padding: '7px 0 5px 0',
position: 'relative'
},
focusStyle: {
borderBottom: '1px #53C7F2 solid',
boxSizing: 'border-box',
cursor: 'pointer',
height: 34,
padding: '7px 0 5px 0',
position: 'relative'
},
hoverStyle: {
borderBottom: '1px #92D6EF solid',
boxSizing: 'border-box',
cursor: 'pointer',
padding: '7px 0 5px 0',
position: 'relative'
},
wrapperStyle: {
outline: 0, // to avoid default focus behaviour
boxSizing: 'border-box',
position: 'relative'
},
optionsAreaStyle: {
display: 'block',
listStyleType: 'none',
background: '#FFF',
padding: '6px 0',
margin: 0,
position: 'absolute',
width: '100%',
zIndex: 10000,
boxSizing: 'border-box',
borderRadius: 2,
boxShadow: '0 1px 1px rgba(0, 0, 0, 0.2)',
borderTop: '1px solid #f2f2f2',
top: 0
},
caretToOpenStyle: {
height: 0,
width: 0,
content: ' ',
position: 'absolute',
top: 15,
right: 8,
borderTop: '6px solid #666',
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent'
},
caretToCloseStyle: {
height: 0,
width: 0,
content: ' ',
position: 'absolute',
top: 15,
right: 8,
borderBottom: '6px solid #666',
borderLeft: '5px solid transparent',
borderRight: '5px solid transparent'
}
};
export default selectStyle;
| JavaScript | 0.000002 | @@ -67,18 +67,18 @@
1px
-#ccc
solid
+ #CCC
',%0A
@@ -246,21 +246,21 @@
1px
-#53C7F2 solid
+solid #6EB8D4
',%0A
@@ -428,21 +428,21 @@
1px
+solid
#92D6EF
- solid
',%0A
|
57bc8c1f631f914c12534ccc91c61976b1deb643 | fix hook registration #9 | src/trigger/Hook.js | src/trigger/Hook.js | const compare = function (a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
const types = [
{
id: '/hubs/hooks/hub_incoming_message_hook',
name: '/hubs/hooks/hub_incoming_message_hook'
}
, {
id: '/hubs/hooks/hub_outgoing_message_hook',
name: '/hubs/hooks/hub_outgoing_message_hook'
}
, {
id: '/private_chat/hooks/private_chat_incoming_message_hook',
name: '/private_chat/hooks/private_chat_incoming_message_hook'
}
, {
id: '/private_chat/hooks/private_chat_outgoing_message_hook',
name: '/private_chat/hooks/private_chat_outgoing_message_hook'
}
, {
id: '/queue/hooks/queue_file_finished_hook',
name: '/queue/hooks/queue_file_finished_hook'
}
, {
id: '/queue/hooks/queue_bundle_finished_hook',
name: '/queue/hooks/queue_bundle_finished_hook'
}
, {
id: '/share/hooks/share_file_validation_hook',
name: '/share/hooks/share_file_validation_hook'
}
, {
id: '/share/hooks/share_directory_validation_hook',
name: '/share/hooks/share_directory_validation_hook'
}
, {
id: '/share/hooks/new_share_file_validation_hook',
name: '/share/hooks/new_share_file_validation_hook'
}
, {
id: '/share/hooks/new_share_directory_validation_hook',
name: '/share/hooks/new_share_directory_validation_hook'
}
].sort(compare);
const settings = [
{
key: 'path',
title: 'Path',
type: 'string',
description: 'Event the script should be executed for.',
optional: false,
default_value: types[0].id,
options: types
}
];
const parameter = ['message', 'accept', 'reject'];
const register = async(socket, config, callback)=>{
return await socket.addHook(config.path.split('/')[1], config.path.split('/')[3], scriptFunction);
};
const id = 'hook';
const name = 'Hook';
const description = 'Executes a script based on validation hooks.';
export default {
settings,
parameter,
register,
id,
name,
description
} | JavaScript | 0 | @@ -1943,22 +1943,16 @@
3%5D,
-scriptFunction
+callback
);%0A%7D
@@ -2158,8 +2158,9 @@
iption%0A%7D
+%0A
|
93537c78eb1b1ccc033409b558e3057b79e978b3 | fix detect orientation bug, close #91 | src/util/browser.js | src/util/browser.js | /**
* Hilo
* Copyright 2015 alibaba.com
* Licensed under the MIT License
*/
/**
* @language=en
* @class Browser feature set
* @static
* @module hilo/util/browser
*/
/**
* @language=zh
* @class 浏览器特性集合
* @static
* @module hilo/util/browser
*/
var browser = (function(){
var ua = navigator.userAgent;
var doc = document;
var win = window;
var docElem = doc.documentElement;
var data = /** @lends browser */ {
/**
* 是否是iphone
* @type {Boolean}
*/
iphone: /iphone/i.test(ua),
/**
* 是否是ipad
* @type {Boolean}
*/
ipad: /ipad/i.test(ua),
/**
* 是否是ipod
* @type {Boolean}
*/
ipod: /ipod/i.test(ua),
/**
* 是否是ios
* @type {Boolean}
*/
ios: /iphone|ipad|ipod/i.test(ua),
/**
* 是否是android
* @type {Boolean}
*/
android: /android/i.test(ua),
/**
* 是否是webkit
* @type {Boolean}
*/
webkit: /webkit/i.test(ua),
/**
* 是否是chrome
* @type {Boolean}
*/
chrome: /chrome/i.test(ua),
/**
* 是否是safari
* @type {Boolean}
*/
safari: /safari/i.test(ua),
/**
* 是否是firefox
* @type {Boolean}
*/
firefox: /firefox/i.test(ua),
/**
* 是否是ie
* @type {Boolean}
*/
ie: /msie/i.test(ua),
/**
* 是否是opera
* @type {Boolean}
*/
opera: /opera/i.test(ua),
/**
* 是否支持触碰事件。
* @type {String}
*/
supportTouch: 'ontouchstart' in win,
/**
* 是否支持canvas元素。
* @type {Boolean}
*/
supportCanvas: doc.createElement('canvas').getContext != null,
/**
* 是否支持本地存储localStorage。
* @type {Boolean}
*/
supportStorage: false,
/**
* 是否支持检测设备方向orientation。
* @type {Boolean}
*/
supportOrientation: 'orientation' in win,
/**
* 是否支持检测加速度devicemotion。
* @type {Boolean}
*/
supportDeviceMotion: 'ondevicemotion' in win
};
//`localStorage` is null or `localStorage.setItem` throws error in some cases (e.g. localStorage is disabled)
try{
var value = 'hilo';
localStorage.setItem(value, value);
localStorage.removeItem(value);
data.supportStorage = true;
}catch(e){}
/**
* 浏览器厂商CSS前缀的js值。比如:webkit。
* @type {String}
*/
var jsVendor = data.jsVendor = data.webkit ? 'webkit' : data.firefox ? 'webkit' : data.opera ? 'o' : data.ie ? 'ms' : '';
/**
* 浏览器厂商CSS前缀的css值。比如:-webkit-。
* @type {String}
*/
var cssVendor = data.cssVendor = '-' + jsVendor + '-';
//css transform/3d feature dectection
var testElem = doc.createElement('div'), style = testElem.style;
/**
* 是否支持CSS Transform变换。
* @type {Boolean}
*/
var supportTransform = style[jsVendor + 'Transform'] != undefined;
/**
* 是否支持CSS Transform 3D变换。
* @type {Boolean}
*/
var supportTransform3D = style[jsVendor + 'Perspective'] != undefined;
if(supportTransform3D){
testElem.id = 'test3d';
style = doc.createElement('style');
style.textContent = '@media ('+ cssVendor +'transform-3d){#test3d{height:3px}}';
doc.head.appendChild(style);
docElem.appendChild(testElem);
supportTransform3D = testElem.offsetHeight == 3;
doc.head.removeChild(style);
docElem.removeChild(testElem);
}
data.supportTransform = supportTransform;
data.supportTransform3D = supportTransform3D;
return data;
})(); | JavaScript | 0 | @@ -2124,32 +2124,63 @@
entation' in win
+ %7C%7C 'orientation' in win.screen
,%0A%0A /**%0A
|
9bfac6be01684cc9335ee6d7312232eaa120c634 | Remove domain name, that isnt necessary | static/js/common.js | static/js/common.js | /*!
* Author: Pierre-Henry Soria <hello@ph7cms.com>
* Copyright: (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved.
* License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
*/
/**
* Allows you to include a JavaScript file in an HTML page.
*
*
* @example
* // With some files
* var aFiles['foo.js', 'bar.js', 'foobar.js'];
* pH7Include(aFiles);
*
*
* @example
* // With a file
* pH7Include('foobar.js');
*
*
* @param mixed ({String} | {Array}) JS file(s).
* @return {Void}
*/
function pH7Include(mFile) {
// Verify that the method isArray is available in the JavaScript version of the web browser (e.g., IE8).
if (!Array.isArray) {
Array.isArray = function (mArg) {
return Object.prototype.toString.call(mArg) === '[object Array]';
};
}
if (Array.isArray(mFile)) {
for (iF in mFile) pH7Include(mFile[iF]);
}
else {
var sHead = document.getElementsByTagName('head')[0];
var sFoorer = document.getElementsByTagName('footer')[0]; // Only with HTML 5, more this tag must be present in the HTML document, but allows faster loading of the page because the files are loaded last.
var mContainer = (sFoorer ? sFoorer : (sHead ? sHead : false));
if (mContainer) {
var oScript = document.createElement('script');
oScript.src = mFile;
/*
// With HTML5 this is no longer necessary.
oScript.type = 'text/javascript';
*/
mContainer.appendChild(oScript);
}
else {
alert('"pH7Include()" function must be included in a valid HTML code.');
}
}
}
/**
* For target_blank with window.open JavaScript method.
*/
(function () {
$('a').click(function () {
var href = $(this).attr('href');
if (-1 == href.indexOf('ph7cms.com') && -1 == href.indexOf('hizup.com') && -1 == href.indexOf('youtube.com') && -1 == href.indexOf('youtu.be') && -1 == href.indexOf('vimeo.com') && -1 == href.indexOf('dailymotion.com') && -1 == href.indexOf('metacafe.com') && -1 == href.indexOf('gravatar.com') && -1 == href.indexOf('softaculous.com') && (-1 != href.indexOf('http://') || -1 != href.indexOf('https://'))) {
var host = href.substr(href.indexOf(':') + 3);
if (-1 != host.indexOf('/')) {
host = host.substring(0, host.indexOf('/'));
}
if (host != window.location.host) {
window.open(href);
return false;
}
}
})
})();
// Only if you hold a valid Pro License (http://ph7cms.com/pro), you can remove the following
console.log('This Web App has been made with http://pH7CMS.com | The Social App Builder'
+ "\r\n" + 'GitHub: http://github.com/pH7Software/pH7-Social-Dating-CMS');
| JavaScript | 0 | @@ -1963,43 +1963,8 @@
1 ==
- href.indexOf('hizup.com') && -1 ==
hre
|
342b0bf2df6819c7b08ac9990044a689d96f2313 | disable archive post-processing | tasks/after-pack.js | tasks/after-pack.js | const handlers = [
require('./after-pack/register-archive-hook'),
require('./after-pack/add-version'),
require('./after-pack/add-platform-files')
];
async function afterPack(context) {
return await handlers.map(h => h(context));
}
module.exports = afterPack; | JavaScript | 0.000001 | @@ -16,57 +16,8 @@
= %5B%0A
- require('./after-pack/register-archive-hook'),%0A
re
|
8b822368f2cbb981a69d356dd978bf930a27eff5 | Use winningCombinations for calculating current game result (score) | client/helpers.js | client/helpers.js | const getRandomEl = (arr) => (
arr[Math.floor(Math.random() * arr.length)]
);
export const flipPlayer = (player) => {
return player === 'o' ? 'x' : 'o';
}
export const isFieldFilled = (prevValue) => {
return typeof prevValue !== 'undefined' && prevValue !== '';
}
export const shouldComputerPlay = (nextPlayer, players) => {
return players[nextPlayer] === 'COMPUTER';
}
export const isGameOver = (checkboard, isFieldFilled) => {
return checkboard.every(isFieldFilled);
}
export const checkHorizontalResult = (checkboard) => {
for (let i = 0; i < 3; i++) {
let row = checkboard.slice(i * 3, i * 3 + 3);
if(
row[0] === row[1] &&
row[0] === row[2] &&
row[0] !== ''
)
return row[0];
}
return false;
}
export const checkVerticalResult = (checkboard) => {
for (let i = 0; i < 3; i++) {
let result;
if(
checkboard[i] === checkboard[i+3] &&
checkboard[i] === checkboard[i+6]
)
result = checkboard[i];
if(checkboard[i] === '')
result = false;
if(result)
return result;
}
return false;
}
export const checkDiagonalResult = (checkboard) => {
if(checkboard[4] === '') return false;
if((
checkboard[0] === checkboard[4] &&
checkboard[0] === checkboard[8]
) || (
checkboard[2] === checkboard[4] &&
checkboard[2] === checkboard[6]
)
)
return checkboard[4];
return false;
}
export const checkResult = (checkboard) => {
return checkHorizontalResult(checkboard) ||
checkVerticalResult(checkboard) ||
checkDiagonalResult(checkboard);
}
export const getAvailableMoves = (checkboard) => {
return checkboard.reduce((acc, item, i) => {
if(!isFieldFilled(item)) return [...acc, i];
return acc;
}, []);
}
export const getWinningCombinations = () => {
const horizontal = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
const vertical = [
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
]
const diagonal = [
[0, 4, 8],
[2, 4, 6]
]
return [...horizontal, ...vertical, ...diagonal];
}
export const calcStepsFromWin = (combinations, checkboard, player) => {
let moves = combinations.map((combination) => {
let steps = combination.reduce((acc, field) => {
//That move's already taken
if(checkboard[field] === flipPlayer(player))
return 9999;
if(checkboard[field] === player) acc--;
return acc;
}, 3);
return { combination, steps };
})
return moves;
}
export const getBestMoves = (calcedCombinations) => {
const sortedCombinations = calcedCombinations.sort((a, b) => {
return a.steps - b.steps;
})
return sortedCombinations.filter((comb) => (
comb.steps <= sortedCombinations[0].steps
));
}
export const getPossibleFieldsFromMove = (move, checkboard) => {
return move.combination.filter((field) => (
!isFieldFilled(checkboard[field])
)
);
}
export const playComputer = (dispatch, getState) => {
const { checkboard, status } = getState();
const availableMoves = getAvailableMoves(checkboard);
const winningCombinations = getWinningCombinations();
const calcedCombinations = calcStepsFromWin(winningCombinations, checkboard, status.currentPlayer);
const bestMoves = getBestMoves(calcedCombinations);
const randomBestMove = getRandomEl(bestMoves);
const possibleFields = getPossibleFieldsFromMove(randomBestMove, checkboard);
const fieldToConquer = getRandomEl(possibleFields);
console.log(randomBestMove, fieldToConquer);
return fieldToConquer;
}
| JavaScript | 0 | @@ -488,34 +488,24 @@
const check
-Horizontal
Result = (ch
@@ -524,306 +524,97 @@
%7B%0A%09
-for (let i = 0; i %3C 3; i++) %7B%0A%09%09let row = checkboard.slice(i * 3, i * 3 + 3);%0A%09%09if(%0A%09%09%09row%5B0%5D === row%5B1%5D &&%0A%09%09%09row%5B0%5D === row%5B2%5D &&%0A%09%09%09row%5B0%5D !== ''%0A%09%09)%0A%09%09%09return row%5B0%5D;%0A%09%7D%0A%09return false;%0A%7D%0A%0Aexport const checkVerticalResult = (checkboard) =%3E %7B%0A%09for (let i = 0; i %3C 3; i++) %7B%0A%09%09let result;%0A%0A%09%09if
+const combinations = getWinningCombinations();%0A%0A%09const isValue = (value) =%3E (field) =%3E
(%0A
-%09
%09%09ch
@@ -626,279 +626,138 @@
ard%5B
-i%5D === checkboard%5Bi+3%5D &&%0A%09%09%09checkboard%5Bi%5D === checkboard%5Bi+6%5D%0A%09%09)%0A%09%09%09result = checkboard%5Bi%5D;%0A%0A%09%09if(checkboard%5Bi%5D === '
+field%5D === value%0A%09);%0A%0A%09const isX = isValue('x
')
+;
%0A%09
-%09%09result = false;%0A%0A%09%09if(result)%0A%09%09%09return result;%0A%09%7D%0A%09return false;%0A%7D%0A%0Aexport const checkDiagonalResult = (checkboard
+const isO = isValue('o');%0A%0A%09return combinations.reduce((acc, comb
) =%3E %7B%0A
+%09
%09if(
-checkboard%5B4%5D === ''
+acc
) re
@@ -765,384 +765,94 @@
urn
-false;%0A%0A
+acc;%0A%09
%09if(
-(%0A%09%09%09checkboard%5B0%5D === checkboard%5B4%5D &&%0A%09%09%09checkboard%5B0%5D === checkboard%5B8%5D%0A%09%09) %7C%7C (%0A%09%09%09checkboard%5B2%5D === checkboard%5B4%5D &&%0A%09%09%09checkboard%5B2%5D === checkboard%5B6%5D%0A%09%09)%0A%09)%0A%09%09return checkboard%5B4%5D;%0A%0A%09return false;%0A%7D%0A%0Aexport const checkResult = (checkboard) =%3E %7B%0A%09return checkHorizontalResult(checkboard) %7C%7C%0A%09checkVerticalResult(checkboard) %7C%7C%0A%09checkDiagonalResult(checkboard
+comb.every((isX))) return 'x';%0A%09%09if(comb.every((isO))) return 'o';%0A%09%7D, false
);%0A%7D
|
71bdf6ed1d0bb316448145bb7df297d3ccf738eb | enforce service request ticket number counter prefix rev.2 | app/models/counter_model.js | app/models/counter_model.js | 'use strict';
/**
* @module Counter
* @name Counter
* @description A record of service request(issue) ticket number.
*
* Used to generate sequencial ticket number for
* service request(issue) based on jurisdiction, service and year.
*
* The format for the ticket number is as below:
* jurisdiction code - service code - year(2digits) - sequence(4digits)
* i.e ILLK170001
*
* At any time the above combo is ensured to be unique for better
* ticket number generation.
*
* @see {@link ServiceRequest}
* @see {@link Jurisdiction}
* @see {@link Service}
* @see {@link https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/}
* @see {@link https://momentjs.com/|moment}
* @author lally elias <lallyelias87@mail.com>
* @since 0.1.0
* @version 0.1.0
* @public
*/
//dependencies
const _ = require('lodash');
const moment = require('moment');
const config = require('config');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//default year digits to use
const YEAR_FORMAT = 'YY'; //TODO move this to configurations
const COUNTER_PREFIX = config.get('counter.prefix');
/**
* @name CounterSchema
* @type {Schema}
* @since 0.1.0
* @version 0.1.0
* @private
*/
const CounterSchema = new Schema({
/**
* @name area
* @description A jurisdiction code for the counter e.g if a jurisdiction
* called Ilala and has a code IL the IL will be used in
* generating next ticket number
*
* @type {Object}
* @see {@link Jurisdiction}
* @private
* @since 0.1.0
* @version 0.1.0
*/
jurisdiction: {
type: String,
required: true,
trim: true,
uppercase: true,
searchable: true
},
/**
* @name service
* @description A service code for the counter e.g if a service
* called Leakage and has a code LK the LK will be used in
* generating next ticket number.
*
* @type {Object}
* @see {@link Jurisdiction}
* @private
* @since 0.1.0
* @version 0.1.0
*/
service: {
type: String,
required: true,
trim: true,
uppercase: true,
searchable: true
},
/**
* @name year
* @description A 2-digit year used in generating next ticket number.
*
* So if year is 2017 the 17 will be used in generating ticket number.
*
* If not provide current year will be used as default year.
*
* @type {Object}
* @see {@link Jurisdiction}
* @private
* @since 0.1.0
* @version 0.1.0
*/
year: {
type: Number,
default: Number(moment(new Date()).format(YEAR_FORMAT)),
searchable: true
},
/**
* @name sequence
* @description Latest ticket number generated. It will be used as a suffix
* for the full ticke number i.e if the last sequence is 999 then
* a full ticket number will be formatted as below:
* jurisdction-service-year(2digit)-0999
*
* @type {Object}
* @private
* @since 0.1.0
* @version 0.1.0
*/
sequence: {
type: Number,
default: 1, //default to start point of the ticket sequences
searchable: true
}
}, { timestamps: true, emitIndexErrors: true });
/**
* force uniqueness of the ticket key per jurisdiction, per service per year
* and sequence
*/
CounterSchema.index({
jurisdiction: 1,
service: 1,
year: 1,
sequence: 1
}, { unique: true });
/**
* @name format
* @description format a counter to meaningful(human readable) ticket number
* @return {String} formatted ticket number
* @see {@link https://lodash.com/docs/4.17.4#padStart}
* @since 0.1.0
* @version 0.1.0
* @private
*/
CounterSchema.methods.format = function () {
//format ticket number to whole meaningful(human readable) number
//TODO move this to configurations
let padSize = 4; //we envision four digit sequence number
//format a sequence by padding 0's at the begin of it
const sequence = _.padStart(this.sequence, padSize, '0');
//format the ticket number as (jurisdiction code)(service code)(year)(sequence)
const ticketNumber = [
this.jurisdiction, this.service, this.year, sequence
].join('');
return ticketNumber;
};
/**
* @name generate
* @param {Object} options valid counter options
* @param {String} options.jurisdiction valid jurisdiction code
* @param {String} options.service valid service code
* @param {String} [options.year] optional year to be used. default to current
* year
* @param {Function} done a callback to invoke on success or error
* @return {String|Error} next ticket number or error
* @see {@link https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/}
* @since 0.1.0
* @version 0.1.0
* @public
* @type {Function}
*/
CounterSchema.statics.generate = function (options, done) {
//reference counter
const Counter = this;
//ensure options
options = _.merge({
year: Number(moment(new Date()).format(YEAR_FORMAT))
}, options);
//ensure jurisdiction code
if (!options.jurisdiction) {
let error = new Error('Missing Jurisdiction Code');
error.status = 400;
return done(error);
}
//ensure service code
if (!options.service) {
let error = new Error('Missing Service Code');
error.status = 400;
return done(error);
}
//ensure prefix on ticket number
options.jurisdiction =
(!_.isEmpty(COUNTER_PREFIX) ? [COUNTER_PREFIX, options.jurisdiction].jion(
'') : options.jurisdiction);
/**
*
* atomically upsert & increment sequence
* first start with counter collection by increment the sequent
* if we encounter error we loop till we succeed
*
* @see {@link https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/#counter-collection-implementation}
* @see {@link https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/#optimistic-loop}
*/
const criteria = _.pick(options, ['jurisdiction', 'service', 'year']);
Counter
.findOneAndUpdate(
criteria, {
$inc: {
sequence: 1 //increment sequence by one
}
}, {
upsert: true,
new: true,
setDefaultsOnInsert: true
})
.exec(function (error, counter) {
//generated formatted ticket number
let ticketNumber;
if (!error && counter) {
ticketNumber = counter.format();
//return
return done(null, ticketNumber, counter);
}
//loop till succeed
else {
return Counter.generate(options, done);
}
});
};
/**
* @name Counter
* @description register CounterSchema and initialize Counter
* model
* @type {Model}
* @since 0.1.0
* @version 0.1.0
* @public
*/
module.exports = mongoose.model('Counter', CounterSchema);
| JavaScript | 0.000002 | @@ -5687,18 +5687,18 @@
ction%5D.j
-i
o
+i
n(%0A
|
bf9975c7d3dbbb5d423f3ce42924a89e38847144 | Update libs.js | eln/libs.js | eln/libs.js | "use strict";
define([
'https://www.lactame.com/lib/openchemlib-extended/1.11.0/openchemlib-extended.js',
'https://www.lactame.com/lib/sdv/0.1.16/sdv.js',
'https://www.lactame.com/lib/chemcalc-extended/1.27.0/chemcalc-extended.js',
'https://www.lactame.com/lib/eln-plugin/0.0.2/eln-plugin.js',
'https://www.lactame.com/github/cheminfo-js/visualizer-helper/7f9c4d2c296389ed263a43826bafeba1164d13de/rest-on-couch/Roc.js'
], function (OCLE, SD, CCE, elnPlugin, Roc) {
return {
OCLE,
SD,
CCE,
elnPlugin,
Roc
}
});
| JavaScript | 0 | @@ -147,17 +147,17 @@
dv/0.1.1
-6
+7
/sdv.js'
|
596af700a604c89978caf393703994a5b8aa00a0 | Update Learnergroup Summary test | tests/integration/components/learnergroup-summary-test.js | tests/integration/components/learnergroup-summary-test.js | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import {
render,
click,
fillIn
} from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
module('Integration | Component | learnergroup summary', function(hooks) {
setupRenderingTest(hooks);
setupMirage(hooks);
test('renders with data', async function (assert) {
const user1 = this.server.create('user');
const user2 = this.server.create('user');
const user3 = this.server.create('user');
const user4 = this.server.create('user');
const user5 = this.server.create('user');
const user6 = this.server.create('user');
const cohort = this.server.create('cohort', {
title: 'this cohort',
users: [user1, user2, user3, user4],
});
const subGroup = this.server.create('learner-group', {
title: 'test sub-group',
});
const course = this.server.create('course');
const session = this.server.create('session', { course });
const offering = this.server.create('offering', { session });
const course2 = this.server.create('course');
const session2 = this.server.create('session', { course: course2 });
const ilm = this.server.create('ilm-session', { session: session2 });
const learnerGroup = this.server.create('learner-group', {
title: 'test group',
location: 'test location',
children: [subGroup],
instructors: [user5, user6],
users: [user1, user2],
offerings: [offering],
ilmSessions: [ilm],
cohort,
});
const learnerGroupModel = await this.owner.lookup('service:store').find('learner-group', learnerGroup.id);
this.set('learnerGroup', learnerGroupModel);
await render(hbs`<LearnergroupSummary
@setIsEditing={{noop}}
@setSortUsersBy={{noop}}
@setIsBulkAssigning={{noop}}
@sortUsersBy="firstName"
@learnerGroup={{learnerGroup}}
@isEditing={{false}}
@isBulkAssigning={{false}}
/>`);
const defaultLocation = '.learnergroup-overview .defaultlocation span:nth-of-type(1)';
const instructors = '.learnergroup-overview .defaultinstructors span';
const coursesList = '.learnergroup-overview .associatedcourses div';
assert.dom(defaultLocation).hasText('test location');
assert.dom(instructors).hasText('4 guy M. Mc4son; 5 guy M. Mc5son');
assert.dom(coursesList).hasText('course 0; course 1');
});
test('Update location', async function(assert) {
assert.expect(2);
const cohort = this.server.create('cohort');
const learnerGroup = this.server.create('learner-group', {
location: 'test location',
cohort,
});
const learnerGroupModel = await this.owner.lookup('service:store').find('learner-group', learnerGroup.id);
this.set('learnerGroup', learnerGroupModel);
await render(hbs`<LearnergroupSummary
@canUpdate={{true}}
@setIsEditing={{noop}}
@setSortUsersBy={{noop}}
@setIsBulkAssigning={{noop}}
@learnerGroup={{learnerGroup}}
@isEditing={{false}}
@isBulkAssigning={{false}}
/>`);
const defaultLocation = '.learnergroup-overview .defaultlocation span:nth-of-type(1)';
const editLocation = `${defaultLocation} .editable`;
const input = `${defaultLocation} input`;
const save = `${defaultLocation} .done`;
assert.dom(defaultLocation).hasText('test location');
await click(editLocation);
await fillIn(input, 'new location name');
await click(save);
assert.dom(defaultLocation).hasText('new location name');
});
});
| JavaScript | 0 | @@ -2083,37 +2083,34 @@
Location = '
-.learnergroup
+%5Bdata-test
-overview .d
@@ -2098,32 +2098,33 @@
ta-test-overview
+%5D
.defaultlocatio
@@ -2168,37 +2168,34 @@
tructors = '
-.learnergroup
+%5Bdata-test
-overview .d
@@ -2183,32 +2183,33 @@
ta-test-overview
+%5D
.defaultinstruc
@@ -2241,37 +2241,34 @@
rsesList = '
-.learnergroup
+%5Bdata-test
-overview .a
@@ -2264,16 +2264,17 @@
overview
+%5D
.associ
@@ -2289,11 +2289,10 @@
ses
-div
+ul
';%0A%0A
@@ -2418,24 +2418,24 @@
. Mc5son');%0A
+
assert.d
@@ -2467,17 +2467,16 @@
course 0
-;
course
@@ -3193,21 +3193,18 @@
= '
-.learnergroup
+%5Bdata-test
-ove
@@ -3208,16 +3208,17 @@
overview
+%5D
.defaul
|
d52055429b9aa7c698a490e6c772d66fc0a21be4 | fix rewing logic | lib/timelines/timelines.js | lib/timelines/timelines.js | 'use strict';
var EventHandler = require('./../utilities/event-handler');
var converter = require('best-timelineUI').converter;
var timelineHelper = require('./../helpers/helpers').timeline;
function Timelines(timelineGroups, states) {
EventHandler.apply(this);
this._timelineGroups = timelineGroups || {};
this._states = states;
this._currTimeline = null;
this._currName = null;
this._pausedTimelines = {};
this._startAutoTimelines();
}
Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;
Timelines.prototype._startAutoTimelines = function _startAutoTimelines() {
for (var timeline in this._timelineGroups) {
if (this._timelineGroups[timeline].auto) {
this.get(timeline).start();
}
}
}
Timelines.prototype.get = function get(timelineName) {
this._currTimeline = this._timelineGroups[timelineName];
this._currName = timelineName;
this._currStateName = '__' + timelineName + 'Time';
return this;
}
Timelines.prototype.start = function start() {
var duration = this._currTimeline.duration;
var convertedTimeline = converter.sweetToSalty(this._currTimeline);
var stateTimelines = convertedTimeline.states;
this._states.set(this._currStateName, 0);
this._states.set(this._currStateName, duration, { duration: duration});
this._setPaused(this._currName, false);
// loops through each individual state timeline
for (var state in stateTimelines) {
var timeline = stateTimelines[state];
var valueFunction = timelineHelper(timeline);
(function(state, valueFunction) {
this._states.subscribeTo(this._currStateName, function(key, time) {
this._states.set(state, valueFunction(time));
}.bind(this));
}.bind(this))(state, valueFunction);
}
}
Timelines.prototype.halt = function halt() {
var currTimelineTime = this._states.get(this._currStateName);
// duration is needed until all states are stored in Transitionables
this._states.set(this._currStateName, currTimelineTime, {duration:0});
this._setPaused(this._currName, true);
}
Timelines.prototype.resume = function resume() {
var time = this._timelineGroups[this._currName].duration;
var timeLeft = time - this._states.get(this._currStateName);
this._states.set(this._currStateName, time, {duration: timeLeft});
this._setPaused(this._currName, false);
}
Timelines.prototype.rewind = function rewind() {
var time = this._timelineGroups[this._currName].duration;
var timeElapsed = time - this._states.get(this._currStateName);
this._states.set(this._currStateName, 0, {duration: timeElapsed});
this._setPaused(this._currName, false);
}
Timelines.prototype.isPaused = function isPaused() {
return this._pausedTimelines[this._currName] || false;
}
Timelines.prototype._setPaused = function _setPaused(timelineName, bool) {
this._pausedTimelines[timelineName] = bool;
}
module.exports = Timelines; | JavaScript | 0.000057 | @@ -2539,70 +2539,8 @@
) %7B%0A
- var time = this._timelineGroups%5Bthis._currName%5D.duration;%0A
@@ -2556,23 +2556,16 @@
lapsed =
- time -
this._s
|
ffd8b19bca3235c4b65b754c03bfc7d5f58b3c57 | Fix for disabled checkboxes | FormFactory.Templates/Scripts/FormFactory/FormFactory.js | FormFactory.Templates/Scripts/FormFactory/FormFactory.js | //** Property.System.Object **//
var ff = {
behaviours: {},
transforms: {}
};
$(document).on("focus", ".ff-behaviour", function () {
var behaviour = $(this).data("ff-behaviour");
if (ff.behaviours[behaviour]) {
ff.behaviours[behaviour](this);
}
});
$(document).on("change", ".ff-choices input.ff-choice-selector", function () { //unchecked choice radios
var choiceArea = $(this).closest(".ff-choice");
var choices = choiceArea.closest(".ff-choices");
choices
.find("> .ff-choice")
.find(":input")
.not(choices.find(".ff-choice-selector")
.not(choices.find(".ff-choices .ff-choice-selector")))
.attr("disabled", "disabled").each(function () {
$("span[data-valmsg-for='" + $(this).attr("name") + "']").css("display", "none");
if ($.validator) {
$.validator.defaults.unhighlight(this);
}
});
var myInputs = choiceArea.find(":input").not(choiceArea.find(".ff-choice input"));
myInputs.attr("disabled", null).each(function () {
if ($("span[data-valmsg-for='" + $(this).attr("name") + "']").css("display", "").hasClass("field-validation-error")) {
if ($.validator) {
$.validator.defaults.highlight(this);
}
}
});
var childChoices = choiceArea.find(".ff-choice").not(choiceArea.find(".ff-choice .ff-choice"));
childChoices.find(".ff-choice-selector").not(childChoices.find(".ff-choices .ff-choice-selector"))
.attr("disabled", null).not("[checked!='checked']").trigger("change");
});
$(document).on("click", ".ff-choices .ff-choice", function (e) {
if ($(e.target).parents().index($(this)) >= 0) {
var option = $(this).find("> * > .ff-choice-selector[disabled!='disabled'][checked!='checked']");
if (option.length) {
var choicesArea = $(this).closest(".ff-choices-area");
var picker = choicesArea.find(".ff-choice-picker").not(choicesArea.find(".ff-choices-area .ff-choice-picker"));
if (picker.length) {
picker.find("option:eq(" + $(this).index() + ")").attr("selected", "selected").trigger("change");
} else {
option.attr("checked", "checked").trigger("change");
}
e.stopPropagation();
$(e.target).click();
}
}
});
$(document).on("change", ".ff-choice-picker", function () {
var choices = $(this).closest(".ff-choices-area").find("> .ff-choices");
var radios = choices.find(".ff-choice-selector")
.not(choices.find(".ff-choices .ff-choice-selector"));
radios.closest(".ff-choice").hide();
$(radios[$(this).val()]).attr("checked", "checked").trigger("change").closest(".ff-choice").show();
});
//** Property.System.DateTime ** //
$.extend(ff.behaviours, {},
{
datepicker: function (t) {
if (!$(t).hasClass("hasDatepicker") && $.datepicker) {
// TODO: a more comprehensive switch of .NET to jQuery formats. REF: http://docs.jquery.com/UI/Datepicker/formatDate
var format = $(t).data("ff-format");
switch (format) {
case "dd MMM yyyy":
format = "dd M yy";
break;
case "dd/MM/yyyy":
format = "dd/mm/yy";
break;
}
$(t).datepicker({ showOn: "focus", dateFormat: format }).focus();
return true;
}
return false;
},
datetimepicker: function (t) {
if (!$(t).hasClass("hasDatepicker") && $.datetimepicker) {
$(t).datetimepicker({ showOn: "focus" }).focus();
return true;
}
return false;
}
}
);
//Collections
$.extend(ff.transforms,
{ remove: function ($el) { $el.remove(); } },
{ swap: function ($el1, $el2) {
$el1.before($el2);
}
});
$(document).ready(function () {
function newId() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
$(document).on("click", ".ff-add-item", function (e) {
var $form = $($('<div/>').html($(this).closest("li").find("script[type='text/html']").html()).text());
var modelName = $(this).data("modelname");
var newObject = $('<li>').append($form.children().clone());
var newIndex = newId(); // $(this).closest("ul").children().length - 1;
var renumber = function (index, attr) {
if (!attr) return attr;
return modelName + "[" + newIndex + "]." + attr;
};
$(newObject).insertBefore($(this).closest(".ff-collection").find("> ul").children().last());
$(":input", newObject).attr("name", renumber).attr("id", renumber);
$("input[type='hidden']", newObject).first().attr("name", modelName + ".Index").val(newIndex);
$(newObject).find("[data-valmsg-for]").attr("data-valmsg-for", renumber);
$form.find(":input").val(null);
if ($.validator) {
if ($.validator.unobtrusive.parseDynamicContent) {
$.validator.unobtrusive.parseDynamicContent(newObject);
}
}
return false;
}); // end on click
$(document).on("click", ".ff-remove-parent", function () {
ff.transforms.remove($(this).closest("li"));
return false;
}); // live click
$(document).on("click", ".ff-move-up", function () {
ff.transforms.swap($(this).closest("li").prev(), $(this).closest("li"));
return false;
}); // live click
$(document).on("click", ".ff-move-down", function () {
ff.transforms.swap($(this).closest("li"), $(this).closest("li").next(":not(.ff-not-collection-item)"));
return false;
}); // live click
});
if ($.validator) {
$.validator.setDefaults({
highlight: function (element) {
$(element).closest(".control-group").addClass("error");
},
unhighlight: function (element) {
$(element).closest(".control-group").removeClass("error");
}
});
}
;
$(document).on("click", "keydown", "input[type='checkbox']", function () {
return !($(this).attr("readonly"));
});
$(document).on("click", "select", function () {
return !($(this).attr("readonly"));
});
| JavaScript | 0 | @@ -6408,20 +6408,17 @@
n(%22click
-%22, %22
+,
keydown%22
@@ -6507,96 +6507,5 @@
%7D);%0A
-$(document).on(%22click%22, %22select%22, function () %7B%0A return !($(this).attr(%22readonly%22));%0A%7D);%0A
+
|
16d183e67c3eb2710a6e90243372516b7a21881b | add ability to animate multiple behaviors on a single timeline | lib/timelines/timelines.js | lib/timelines/timelines.js | 'use strict';
var EventHandler = require('./../utilities/event-handler');
var converter = require('framework-utilities/converter');
var toSalty = converter.sweetToSalty;
var piecewise = require('./../helpers/helpers').piecewise;
function Timelines(timelineGroups, states) {
EventHandler.apply(this);
this._timelineGroups = timelineGroups || {};
this._states = states;
this._currName = null;
this._currTimeline = null;
this._pausedTimelines = {};
this._behaviorList = this._createBehaviors();
this._startAutoTimelines();
}
Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;
Timelines.prototype._createBehaviors = function _createBehaviors() {
var behaviors = {};
for (var timeline in this._timelineGroups) {
var behaviorGroup = this._timelineGroups[timeline];
var time = '__' + timeline + 'Time';
var saltyTimeline = toSalty(behaviorGroup);
var timeline = saltyTimeline[Object.keys(saltyTimeline)];
for (var selector in behaviorGroup) {
var selectorBehaviors = behaviorGroup[selector];
if (!behaviors[selector]) behaviors[selector] = {};
for (var key in selectorBehaviors) {
var valueFunction = 'BEST.helpers.piecewise(' + JSON.stringify(timeline) + ')';
behaviors[selector][key] = new Function(time,
'return ' + valueFunction + '(' + time + ')'
);
}
}
}
return behaviors;
}
Timelines.prototype.getBehaviors = function getBehaviors() {
return this._behaviorList || {};
}
Timelines.prototype._startAutoTimelines = function _startAutoTimelines() {
for (var timeline in this._timelineGroups) {
if (this._timelineGroups[timeline].auto) {
this.get(timeline).start();
}
}
};
Timelines.prototype.get = function get(timelineName) {
this._currTimeline = converter.sweetToSalty(this._timelineGroups[timelineName]);
this._currName = timelineName;
this._currStateName = '__' + timelineName + 'Time';
return this;
};
Timelines.prototype.start = function start(options) {
options = options || {};
var speed = options.speed || 1;
var duration = options.duration || 0;
var transition = {duration: duration / speed};
var behaviorTimeline = this._currTimeline;
this._states.set(this._currStateName, 0);
this._states.set(this._currStateName, duration, transition);
this._setPaused(this._currName, false);
// loops through each individual state timeline
for (var state in behaviorTimeline) {
var timeline = behaviorTimeline[state];
var valueFunction = piecewise(timeline);
(function(scopedState, scopedValueFunction) {
this._states.subscribeTo(this._currStateName, function(key, time) {
this._states.set(scopedState, scopedValueFunction(time));
}.bind(this));
}.bind(this))(state, valueFunction);
}
return this;
};
Timelines.prototype.halt = function halt() {
var timeElapsed = this._states.get(this._currStateName);
// duration is needed until all states are stored in Transitionables
this._states.set(this._currStateName, timeElapsed, {duration: 0});
this._setPaused(this._currName, true);
return this;
};
Timelines.prototype.resume = function resume() {
var speed = this._currSpeed;
var totalTime = this._currDuration;
var timeElapsed = this._states.get(this._currStateName);
var timeLeft = totalTime - timeElapsed;
this._states.set(this._currStateName, totalTime, {duration: timeLeft / speed});
this._setPaused(this._currName, false);
return this;
};
Timelines.prototype.rewind = function rewind() {
var speed = this._currSpeed;
var timeElapsed = this._states.get(this._currStateName);
var transition = {duration: timeElapsed / speed};
this._states.set(this._currStateName, 0, transition);
this._setPaused(this._currName, false);
return this;
};
Timelines.prototype.isPaused = function isPaused() {
return this._pausedTimelines[this._currName] || false;
};
Timelines.prototype._setPaused = function _setPaused(timelineName, bool) {
this._pausedTimelines[timelineName] = bool;
};
Timelines.mergeBehaviors = function(definitionBehaviors, timelineBehaviors) {
var behaviors = definitionBehaviors;
for (var selector in timelineBehaviors) {
var timelineSelector = timelineBehaviors[selector];
var definitionSelector = definitionBehaviors[selector];
if (definitionSelector) {
for (var behavior in timelineSelector) {
var timelineBehavior = timelineSelector[behavior];
var definitionBehavior = definitionSelector[behavior];
if (definitionBehavior) { /* decide on injected timelineArgument api */ }
else { behaviors[selector][behavior] = timelineBehavior; }
}
}
}
return behaviors;
};
module.exports = Timelines; | JavaScript | 0.000005 | @@ -770,32 +770,36 @@
or (var timeline
+Name
in this._timeli
@@ -867,16 +867,20 @@
timeline
+Name
%5D;%0A%0A
@@ -909,16 +909,20 @@
timeline
+Name
+ 'Time
@@ -976,24 +976,25 @@
Group);%0A
+%0A
var time
@@ -989,63 +989,111 @@
-var timeline = saltyTimeline%5BObject.keys(saltyTimeline)
+for (var selectorBehavior in saltyTimeline) %7B%0A var timeline = saltyTimeline%5BselectorBehavior
%5D;%0A%0A
@@ -1092,37 +1092,36 @@
vior%5D;%0A%0A
-for (
+
var selector in
@@ -1121,27 +1121,41 @@
tor
-in behaviorGroup) %7B
+= selectorBehavior.split('%7C')%5B0%5D;
%0A
@@ -1171,50 +1171,48 @@
var
-selectorB
+b
ehavior
-s
=
-behaviorGroup%5Bselector
+selectorBehavior.split('%7C')%5B1
%5D;%0A%0A
@@ -1280,61 +1280,8 @@
%7D;%0A%0A
- for (var key in selectorBehaviors) %7B%0A
@@ -1381,20 +1381,16 @@
-
-
behavior
@@ -1401,19 +1401,24 @@
lector%5D%5B
-key
+behavior
%5D = new
@@ -1432,20 +1432,16 @@
n(time,%0A
-
@@ -1509,28 +1509,10 @@
- );%0A %7D
+);
%0A
|
bb03359cfccfa8a1300435339ef91911e4b611af | Use unix fs-watch for OSX because of problems with OSX Lion | lib/fs-watch-tree.js | lib/fs-watch-tree.js | module.exports = process.platform === "linux" ?
require("./watch-tree-unix") :
require("./watch-tree-generic");
| JavaScript | 0.000001 | @@ -38,16 +38,49 @@
%22linux%22
+ %7C%7C process.platform === %22darwin%22
?%0A r
|
a151b7b9ae44d977f17d4b1bc2936b8d6d071ce4 | Fix list item styles | thingmenn-frontend/src/widgets/list-item-content/index.js | thingmenn-frontend/src/widgets/list-item-content/index.js | import React from 'react'
import './styles.css'
const ListItemContent = ({
title,
description,
}) => {
return (
<div className="ListItemContent">
<h2 className="ListItemContent-name">{title}</h2>
{description ?
<p className="ListItemContent-party">{description}</p>
: null}
</div>
)
}
ListItemContent.propTypes = {
title: React.PropTypes.string,
description: React.PropTypes.string,
}
export default ListItemContent
| JavaScript | 0.000001 | @@ -191,12 +191,15 @@
ent-
-name
+content
%22%3E%7Bt
@@ -272,13 +272,19 @@
ent-
-party
+description
%22%3E%7Bd
|
957a55c9276191a1a50ec621084141c5735ebb25 | Fix for geolocation.load | client/js/maps.js | client/js/maps.js | if (Meteor.isClient) {
Meteor.startup(function() {
GoogleMaps.load();
Geolocation.load();
Tracker.autorun(function () {
if (Geolocation.error() !== null) {
var center = new google.maps.LatLng(Geolocation.latLng().lat, Geolocation.latLng().lng);
GoogleMaps.maps.gmap.instance.panTo(center);
};
})
});
Template.page_map.helpers({
gmapOptions: function() {
// Make sure the maps API has loaded
if (GoogleMaps.loaded()) {
// We can use the `ready` callback to interact with the map API on3ce the map is ready.
GoogleMaps.ready('gmap', function(map) {
// Add a marker to the map once it's ready
var marker = new google.maps.Marker({
position: map.options.center,
map: map.instance
});
});
// Map initialization options
return {
center: new google.maps.LatLng(-37.8136, 144.9631),
zoom: 8
};
}
}
});
}
| JavaScript | 0.000002 | @@ -73,32 +73,8 @@
();%0A
- Geolocation.load();%0A
|
97062b82fbdefc04fc4c9fede9c68646d1dcd3aa | fix typo: docs mention Observable#forEach twice | lib/typedefs/Observable.js | lib/typedefs/Observable.js |
/**
* @constructor Observable
*/
/**
* The forEach method is a synonym for {@link Observable.prototype.subscribe} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object.
* @name forEach
* @memberof Observable.prototype
* @function
* @arg {?Observable~onNextCallback} onNext a callback that accepts the next value in the stream of values
* @arg {?Observable~onErrorCallback} onError a callback that accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream
* @arg {?Observable~onCompletedCallback} onCompleted a callback that is invoked when the {@link Observable} stream has ended, and the {@link Observable~onNextCallback} will not receive any more values
* @return {Subscription}
*/
/**
* The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. An Observable is like a pipe of water that is closed. When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object.
* @name forEach
* @memberof Observable.prototype
* @function
* @arg {?Observable~onNextCallback} onNext a callback that accepts the next value in the stream of values
* @arg {?Observable~onErrorCallback} onError a callback that accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream
* @arg {?Observable~onCompletedCallback} onCompleted a callback that is invoked when the {@link Observable} stream has ended, and the {@link Observable~onNextCallback} will not receive any more values
* @return {Subscription}
*/
/**
* This callback accepts a value that was emitted while evaluating the operation underlying the {@link Observable} stream.
* @callback Observable~onNextCallback
* @param {Object} value the value that was emitted while evaluating the operation underlying the {@link Observable}
*/
/**
* This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}.
* @callback Observable~onErrorCallback
* @param {Error} error the error that occurred while evaluating the operation underlying the {@link Observable}
*/
/**
* This callback is invoked when the {@link Observable} stream ends. When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values.
* @callback Observable~onCompletedCallback
*/
/**
* @constructor Subscription
* @see {@link https://github.com/Reactive-Extensions/RxJS/tree/master/doc}
*/
/**
* When this method is called on the Subscription, the Observable that created the Subscription will stop sending values to the callbacks passed when the Subscription was created.
* @name dispose
* @method
* @memberof Subscription.prototype
*/
| JavaScript | 0.000015 | @@ -1406,39 +1406,41 @@
bject.%0A * @name
-forEach
+subscribe
%0A * @memberof Ob
|
aa1a17d8bc79f8fca64fc9e1ca52f8beddd477c1 | Remove html reporters | karma.conf.js | karma.conf.js | // Karma configuration
// Generated on Fri Feb 12 2016 17:46:34 GMT+0900 (東京 (標準時))
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'test/*.html',
'src/*.js',
'test/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/*.html': 'html2js'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec', 'html'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
})
}
| JavaScript | 0.000003 | @@ -948,16 +948,8 @@
pec'
-, 'html'
%5D,%0A%0A
@@ -1617,19 +1617,20 @@
gleRun:
-tru
+fals
e,%0A%0A
@@ -1856,11 +1856,86 @@
%7D%0A %7D)
+;%0A if(process.env.TRAVIS)%7B%0A config.browsers = %5B'Chrome_travis_ci'%5D;%0A %7D
%0A%7D%0A
|
3967dcf899472af97570cf1d5b0b1e001479bebf | set default browser to instead of | karma.conf.js | karma.conf.js | // This setup is based on Julie Ralph's `ng2-test-seed` project.
// See https://github.com/juliemr/ng2-test-seed
// Hopefully Angular2 and Karma integration will be more seamless in the future.
// Unit tests are currently only implemented to run again the development target.
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
/** Paths loaded by Karma */
{ pattern: 'node_modules/traceur/bin/traceur.js', included: true, watched: true },
{ pattern: 'node_modules/systemjs/dist/system-polyfills.js', included: true, watched: true },
{ pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: true },
{ pattern: 'node_modules/angular2/bundles/angular2.dev.js', included: true, watched: true },
{ pattern: 'node_modules/angular2/bundles/testing.js', included: true, watched: true },
{ pattern: 'karma.shim.js', included: true, watched: true },
/** Paths loaded via module imports */
{ pattern: 'build/js/**/*.js', included: false, watched: true },
/** Paths to support debugging with source maps in dev tools */
{ pattern: 'src/**/*.ts', included: false, watched: false },
{ pattern: 'test/**/*.js', included: false, watched: false }
],
exclude: [
'node_modules/angular2/**/*_spec.js'
],
reporters: ['progress', 'coverage'],
preprocessors: {
/**
* Source files, that you want to generate coverage for.
* Do not include tests or libraries.
* These files will be instrumented by Istanbul.
*/
'build/**/*.js': ['coverage']
},
/** Optionally, configure the reporter */
coverageReporter: {
type: 'json',
subdir: './json',
file: 'coverage-js.json'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS2'],
autoWatch: false,
singleRun: true
});
};
| JavaScript | 0.000001 | @@ -1775,30 +1775,263 @@
%0A%0A%09%09
-browsers: %5B'PhantomJS2
+/**%0A%09%09 * @param browsers %7BArray%7D List of browsers for Karma to run the tests against.%0A%09%09 * We can use %60Chrome%60 or %60PhantomJS2%60 out-of-the-box here.%0A%09%09 * Unfortunately %60PhantomJS2%60 support is limited for Linux users or Travis CI.%0A%09%09 */%0A%09%09browsers: %5B'Chrome
'%5D,%0A
|
f95880580820d17c62d41834d2a9a714013813fa | fix issue #143 | lib/utils/cache-browser.js | lib/utils/cache-browser.js | import 'promise-polyfill/src/polyfill';
import 'whatwg-fetch';
import md5 from './md5';
import configDefault from '../config-default.js';
if (typeof self === 'undefined') {
throw 'IndexedDB is available only in Browser ENV';
}
const indexedDBAvailable = 'indexedDB' in self;
let cachingEnabled = true;
if (!indexedDBAvailable) {
// console.log("Your browser doesn't support a stable version of IndexedDB.");
cachingEnabled = false; // graceful degradation
}
let db;
let cacheConfig = {
...configDefault.cache
};
function initializeIndexedDb(requestCacheConfig = {}){
if (db) { return Promise.resolve(); }
if (!cachingEnabled) { return Promise.resolve(); }
cacheConfig = {
...cacheConfig,
...requestCacheConfig
};
return new Promise((resolve, reject) => {
const dbConnectionRequest = self.indexedDB.open(cacheConfig.dbName);
dbConnectionRequest.onerror = function(event) {
cachingEnabled = false;
resolve();
};
dbConnectionRequest.onupgradeneeded = function(event) {
const db = event.target.result;
const objectStore = db
.createObjectStore(cacheConfig.dbCollectionName,
{ keyPath: cacheConfig.dbCollectionKey });
objectStore.createIndex(
cacheConfig.dbCollectionKey,
cacheConfig.dbCollectionKey,
{ unique: true }
);
objectStore.createIndex('expiryTime', 'expiryTime', { unique: false });
};
dbConnectionRequest.onsuccess = function(event) {
db = event.target.result;
db.onerror = function(event) {
cachingEnabled = false; // graceful degradation
};
resolve(db);
};
});
}
export const saveToCache = (hash, configOptions = {}) => {
return initializeIndexedDb(configOptions).then(() => {
const transactionSave = db
.transaction(cacheConfig.dbCollectionName, "readwrite")
.objectStore(cacheConfig.dbCollectionName);
const requestSave = transactionSave.add({
hash,
expiryTime: Date.now() + cacheConfig.maxAge
});
requestSave.onsuccess = function(event) {
};
requestSave.onerror = function(event) {
cachingEnabled = false;
};
});
}
export const getFromCache = (hash, configOptions = {}) => {
return initializeIndexedDb(configOptions).then(() => {
return new Promise((resolve, reject) => {
if (!cachingEnabled) {
return resolve(null);
}
const transactionCleanUp = db
.transaction(cacheConfig.dbCollectionName, "readwrite")
.objectStore(cacheConfig.dbCollectionName);
const indexCleanUp = transactionCleanUp.index('expiryTime');
const upperBoundOpenKeyRange = IDBKeyRange.upperBound(Date.now(), true);
indexCleanUp.openCursor(upperBoundOpenKeyRange).onsuccess = function(event) {
let cursor = event.target.result;
if (cursor) {
let transactionDelete = db
.transaction(cacheConfig.dbCollectionName, "readwrite")
.objectStore(cacheConfig.dbCollectionName)
.delete(event.target.result.value[cacheConfig.dbCollectionKey]);
cursor.continue();
}
};
const transactionIndex = db
.transaction(cacheConfig.dbCollectionName, "readwrite")
.objectStore(cacheConfig.dbCollectionName);
const index = transactionIndex.index(cacheConfig.dbCollectionKey);
const responseFromCache = index.get(hash);
responseFromCache.onsuccess = function(event) {
if (!event.target.result ||
event.target.result.expiryTime < Date.now()
) {
if (event.target.result && event.target.result.expiryTime < Date.now()){
const transactionDelete = db
.transaction(cacheConfig.dbCollectionName, "readwrite")
.objectStore(cacheConfig.dbCollectionName)
.delete(event.target.result[cacheConfig.dbCollectionKey]);
transactionDelete.onsuccess = (event) => {
resolve(getFromCache(hash, configOptions));
};
transactionDelete.onerror = (event) => {
cachingEnabled = false;
resolve(getFromCache(hash, configOptions));
};
return resolve(null);
}
return resolve(null);
} else {
return resolve(event.target.result);
}
};
responseFromCache.onerror = function(event) {
cachingEnabled = false;
resolve(getFromCache(hash, configOptions));
};
});
});
}
| JavaScript | 0 | @@ -175,14 +175,20 @@
%7B%0A
-throw
+console.log(
'Ind
@@ -227,16 +227,17 @@
ser ENV'
+)
;%0A%7D%0A%0Acon
@@ -259,16 +259,47 @@
ilable =
+ typeof self !== 'undefined' &&
'indexe
@@ -310,17 +310,17 @@
in self
-;
+%0A
%0Alet cac
|
d2ee8f79e8725954968e5875f3e89be402ca951d | Remove outdated default options from CLI | bin/idyll.js | bin/idyll.js | #! /usr/bin/env node
const idyll = require('../src/');
var argv = require('yargs')
.usage('Usage: idyll index.idl')
.example('$0 index.idl', 'Turn index.idl into output')
.demandCommand(1)
.alias({
m: 'components',
c: 'css',
d: 'datasets',
q: 'defaultComponents',
f: 'inputFile',
s: 'inputString',
l: 'layout',
n: 'no-minify',
o: 'output',
k: 'spellcheck',
t: 'template',
e: 'theme',
w: 'watch'
})
.describe('components', 'Directory where components are located')
.default('components', 'components')
.describe('css', 'Custom CSS file to include in output')
.describe('datasets', 'Directory where data files are located')
.default('datasets', 'data')
.describe('defaultComponents', 'Directory where default set of components are located')
.default('defaultComponents', 'components/default')
.describe('inputFile', 'File containing Idyll source')
.describe('inputString', 'Idyll source as a string')
.describe('layout', 'Name of (or path to) the layout to use')
.default('layout', 'blog')
.boolean('no-minify')
.describe('no-minify', 'Skip JS minification')
.default('no-minify', true)
.describe('output', 'Directory where built files should be written')
.default('output', 'build')
.boolean('spellcheck')
.default('spellcheck', true)
.describe('spellcheck', 'Check spelling of Idyll source input')
.describe('template', 'Path to HTML template')
.default('template', '_index.html')
.array('transform')
.describe('transform', 'Custom browserify transforms to apply.')
.default('transform', [])
.describe('theme', 'Name of (or path to) the theme to use')
.default('theme', 'idyll')
.boolean('watch')
.describe('watch', 'Monitor input files and rebuild on changes')
.default('watch', false)
.alias('h', 'help')
.argv;
// inputFile can be passed as non-hypenated argument
if (argv._[0]) argv.f = argv.inputFile = argv._[0];
// API checks the inverse
argv.minify = !argv['no-minify'];
// move spellcheck down a level
argv.compilerOptions = {
spellcheck: argv.spellcheck
};
// delete stuff we don't need
delete argv._;
delete argv['$0'];
delete argv.n;
delete argv['no-minify'];
delete argv.k;
delete argv.spellcheck;
idyll(argv).build();
| JavaScript | 0.000001 | @@ -812,62 +812,8 @@
d')%0A
- .default('defaultComponents', 'components/default')%0A
.d
@@ -1392,46 +1392,8 @@
e')%0A
- .default('template', '_index.html')%0A
.a
@@ -2145,16 +2145,163 @@
check;%0A%0A
+// delete undefined keys so Object.assign won't use them%0AObject.keys(argv).forEach((key) =%3E %7B%0A if (argv%5Bkey%5D === undefined) delete argv%5Bkey%5D;%0A%7D)%0A%0A
idyll(ar
|
7e5da238ee869201fdb9027c27b79b0f76b440a8 | fix Windows perms regression | lib/utils/correct-mkdir.js | lib/utils/correct-mkdir.js | var chownr = require('chownr')
var dezalgo = require('dezalgo')
var fs = require('graceful-fs')
var inflight = require('inflight')
var log = require('npmlog')
var mkdirp = require('mkdirp')
// memoize the directories created by this step
var stats = {}
var effectiveOwner
module.exports = function correctMkdir (path, cb) {
cb = dezalgo(cb)
if (stats[path]) return cb(null, stats[path])
fs.stat(path, function (er, st) {
if (er) return makeDirectory(path, cb)
if (!st.isDirectory()) {
log.error('correctMkdir', 'invalid dir %s', path)
return cb(er)
}
var ownerStats = calculateOwner()
// there's always a chance the permissions could have been frobbed, so fix
if (st.uid !== ownerStats.uid) {
stats[path] = ownerStats
setPermissions(path, ownerStats, cb)
} else {
stats[path] = st
cb(null, stats[path])
}
})
}
function calculateOwner () {
if (!effectiveOwner) {
var uid = +process.getuid()
var gid = +process.getgid()
if (uid === 0) {
if (process.env.SUDO_UID) uid = +process.env.SUDO_UID
if (process.env.SUDO_GID) gid = +process.env.SUDO_GID
}
effectiveOwner = { uid: uid, gid: gid }
}
return effectiveOwner
}
function makeDirectory (path, cb) {
cb = inflight('makeDirectory:' + path, cb)
if (!cb) {
return log.verbose('makeDirectory', path, 'creation already in flight; waiting')
} else {
log.verbose('makeDirectory', path, 'creation not in flight; initializing')
}
if (!process.getuid) {
return mkdirp(path, function (er) {
log.verbose('makeCacheDir', 'UID & GID are irrelevant on', process.platform)
stats[path] = { uid: 0, gid: 0 }
return cb(er, stats[path])
})
}
var owner = calculateOwner()
if (owner.uid !== 0 || !process.env.HOME) {
log.silly(
'makeDirectory', path,
'uid:', owner.uid,
'gid:', owner.gid
)
stats[path] = owner
mkdirp(path, afterMkdir)
} else {
fs.stat(process.env.HOME, function (er, st) {
if (er) {
log.error('makeDirectory', 'homeless?')
return cb(er)
}
log.silly(
'makeDirectory', path,
'uid:', st.uid,
'gid:', st.gid
)
stats[path] = st
mkdirp(path, afterMkdir)
})
}
function afterMkdir (er, made) {
if (er || !stats[path] || isNaN(stats[path].uid) || isNaN(stats[path].gid)) {
return cb(er, stats[path])
}
if (!made) return cb(er, stats[path])
setPermissions(made, stats[path], cb)
}
}
function setPermissions (path, st, cb) {
chownr(path, st.uid, st.gid, function (er) {
return cb(er, st)
})
}
| JavaScript | 0.000001 | @@ -946,44 +946,147 @@
-var uid = +process.getuid()%0A var
+effectiveOwner = %7B uid: 0, gid: 0 %7D%0A%0A if (process.getuid) effectiveOwner.uid = +process.getuid()%0A if (process.getgid) effectiveOwner.
gid
@@ -1114,16 +1114,31 @@
if (
+effectiveOwner.
uid ===
@@ -1174,16 +1174,31 @@
DO_UID)
+effectiveOwner.
uid = +p
@@ -1249,16 +1249,31 @@
DO_GID)
+effectiveOwner.
gid = +p
@@ -1301,53 +1301,8 @@
%7D
-%0A%0A effectiveOwner = %7B uid: uid, gid: gid %7D
%0A %7D
@@ -1604,16 +1604,48 @@
')%0A %7D%0A%0A
+ var owner = calculateOwner()%0A%0A
if (!p
@@ -1805,34 +1805,21 @@
path%5D =
-%7B uid: 0, gid: 0 %7D
+owner
%0A r
@@ -1860,40 +1860,8 @@
%7D%0A%0A
- var owner = calculateOwner()%0A%0A
if
|
f1586476fadc8c0e55eb40ad4827de755759749f | add support for recursive option in cli | bin/index.js | bin/index.js | #! /usr/bin/env node
// sudo npm link
const colors = require('colors/safe');
const utils = require('../lib/utils');
const safeReportSync = require('../lib').safeReportSync;
const safe = require('../lib').safe;
const safeReport = require('../lib');
const help =
`
${colors.bgWhite.gray('----------------------------------------------- HELP -----------------------------------------------')}
${colors.red(`The command line tool for safe-regex module to detect
potentially catastrophic exponential-time regular expressions.`)}
- SAFE A REGEX
$ safe-regex string
${colors.gray(`example:
safe-regex '(a+){10}'`)}
- SAFE EACH FILE OF A DIRECTORY
$ safe-regex dir
${colors.gray(`example:
safe-regex src/js`)}
- SAFE ONE FILE
$ safe-regex file
${colors.gray(`example:
safe-regex src/js/app.js`)}
- SAFE WATCHING A FILE OR A DIRECTORY
$ safe-regex dir|file -w|-watch
${colors.gray(`examples:
safe-regex src/js/app.js -watch
safe-regex src/js/app.js -w`)}
- OPTION : number of allowed repetitions in the entire regular expressions found (default 25)
$ safe-regex dir|file -limit|-l number
${colors.gray(`examples:
safe-regex src/js/app.js -limit 50
safe-regex src/js/app.js -l 35 -w`)}
${colors.bgWhite.gray('--------------------------------------------- END HELP ---------------------------------------------')}
`;
var userArgs = process.argv.slice(2);
if (!userArgs[0] || ~userArgs.indexOf('-help') || ~userArgs.indexOf('--help') || ~userArgs.indexOf('-h')) {
console.log(help);
} else {
let dirorfile = userArgs[0],
limit = 25,
watch = false;
// get options
let index = 0;
// limit
if (~(index = userArgs.indexOf('-limit')) || ~(index = userArgs.indexOf('-l'))){
limit = utils.getInt(userArgs[index + 1], 1); // get at least 1
}
// watch
if (~userArgs.indexOf('-watch') || ~userArgs.indexOf('-w')){
watch = true;
}
// if dirorfile does not exist, it may be a regex
if (!utils.existsSync(dirorfile)) {
let isSafe = safe(dirorfile, {limit: limit});
if (isSafe) console.log(`'${dirorfile}' is ${colors.green('safe')}.`);
else console.log(`'${dirorfile}' is ${colors.red('not safe')}.`);
} else {
// now we have options, operate on file(s) to get a report from unsafe regexp
let safe = safeReportSync(dirorfile, limit, watch);
// if watch, safe = true so we can wait for file changes
// else if safe === false safeReportSync has found unsafe regex in file(s)
// else safe = true safeReportSync has found no unsafe regex
if (!safe) process.exit(1); // STOP PROCESS so we can chain command and this security issue will stop it : safe-regex src/js/ && eslint src/js/** && ...
}
}
| JavaScript | 0 | @@ -970,16 +970,22 @@
OPTION
+LIMIT
: number
@@ -1199,24 +1199,291 @@
l 35 -w%60)%7D%0A%0A
+- OPTION RECURSIVE : indicates whether all subdirectories should be tested or watched, or only the current directory (false by default)%0A%0A$ safe-regex dir%7Cfile -recursive%7C-r%0A$%7Bcolors.gray(%60examples:%0A safe-regex src/js/ -recursive%0A safe-regex src/js/ -r -l 50 -w%60)%7D%0A%0A
$%7Bcolors.bgW
@@ -1840,16 +1840,41 @@
watch =
+ false,%0A recursive =
false;%0A
@@ -1909,16 +1909,125 @@
x = 0;%0A%0A
+ // recursive%0A if (~userArgs.indexOf('-recursive') %7C%7C ~userArgs.indexOf('-r'))%7B%0A recursive = true;%0A %7D%0A%0A
// lim
@@ -2700,16 +2700,27 @@
rorfile,
+ recursive,
limit,
@@ -2733,17 +2733,17 @@
;%0A%0A /
-/
+*
if watc
@@ -2789,26 +2789,26 @@
changes%0A
+
-//
+
else if saf
@@ -2872,18 +2872,18 @@
(s)%0A
+
-//
+
else sa
@@ -2932,16 +2932,19 @@
fe regex
+ */
%0A if
@@ -3016,12 +3016,15 @@
and
-this
+a regex
sec
|
48c020916c56f379f840368d1b3a42f2c94c2c6f | Fix keyboard shortcuts | lib/views/world_toolbar.js | lib/views/world_toolbar.js | var _ = require('underscore')
, Backbone = require('backbone')
, getKey = require('../helpers/get_key')
module.exports = Backbone.View.extend({
initialize: function() {
this.initButtons()
this.initKeyboard()
},
initButtons: function() {
var robot = this.model.get('robot')
this.$('input[type=button]').live('click', function() {
robot[$(this).attr('data-method')]()
})
},
initKeyboard: function() {
var actions = {
left: 'linksDrehen',
right: 'rechtsDrehen',
up: 'schritt',
down: 'schrittRueckwaerts',
space: 'markeUmschalten',
enter: 'hinlegen',
backspace: 'aufheben',
'delete': 'entfernen',
h: 'hinlegen',
a: 'aufheben',
m: 'markeUmschalten',
q: 'quader',
e: 'entfernen'
}
$(document).keydown(_(function(evt) {
var key = getKey(evt)
console.log('key pressed: ' + key)
if (actions.hasOwnProperty(key)) {
this.model.get('robot')[actions[key]]()
}
}).bind(this))
}
})
| JavaScript | 0.999879 | @@ -475,27 +475,28 @@
+
left:
-
'
-linksDrehen
+turnLeft
',%0A
@@ -504,16 +504,20 @@
+
+
right: '
rech
@@ -516,44 +516,42 @@
t: '
-rechtsDrehen',%0A
+turnRight',%0A
+
up:
- 'schritt
+'move
',%0A
@@ -559,33 +559,32 @@
+
+
down:
-
'
-schrittRue
+moveBa
ckwa
-ert
+rd
s',%0A
@@ -593,35 +593,32 @@
+
space:
- 'markeUmschalten
+'toggleMarker
',%0A
@@ -626,28 +626,28 @@
+
enter:
- 'hinlegen
+'putBrick
',%0A
@@ -663,27 +663,31 @@
space: '
-aufheben
+removeBrick
',%0A
+
'd
@@ -698,80 +698,176 @@
e':
- 'entfernen',%0A h: 'hinlegen',%0A a: 'a
+'removeBlock',%0A h: 'putBrick', // Ziegel *h*inlegen%0A a: 'removeBrick', // Ziegel *a*
ufheben
-',%0A
+%0A
-m: 'm
+ m: 'toggleMarker', // *M*
arke
-U
+ u
msch
@@ -871,19 +871,25 @@
schalten
-',%0A
+%0A
q:
@@ -894,36 +894,100 @@
q: '
-quader',%0A e: 'e
+putBlock', // *Q*uader aufstellen%0A e: 'removeBlock' // Quader *e*
ntfernen
'%0A
@@ -982,17 +982,16 @@
ntfernen
-'
%0A %7D%0A
|
0e57d28336abfe9fb180c96e3f78f8d9214ffb8c | fix typo | karma.conf.js | karma.conf.js | // Karma configuration
// Generated on Tue Jul 18 2017 18:01:48 GMT+0800 (CST)
const path = require('path')
const webpack = require('webpack')
const coverage = String(process.env.COVERAGE) !== 'false'
const ci = String(process.env.CI).match(/^(1|true)$/gi)
const realBrowser = String(process.env.BROWSER).match(/^(1|true)$/gi)
const sauceLabs = realBrowser && ci
const sauceLabsLaunchers = {
sl_win_chrome: {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 10'
},
sl_mac_chrome: {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'macOS 10.12'
},
sl_firefox: {
base: 'SauceLabs',
browserName: 'firefox',
platform: 'Windows 10'
},
sl_mac_firfox: {
base: 'SauceLabs',
browserName: 'firefox',
platform: 'macOS 10.12'
},
sl_safari: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.12'
},
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10'
},
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11.103',
platform: 'Windows 10'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '10.0',
platform: 'Windows 7'
},
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9.0',
platform: 'Windows 7'
},
sl_ie_8: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '8.0',
platform: 'Windows 7'
}
}
const travisLaunchers = {
chrome_travis: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
const localBrowsers = realBrowser ? Object.keys(travisLaunchers) : ['Chrome']
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'./node_modules/es5-shim/dist/es5-shim.js',
'./node_modules/es5-shim/dist/es5-sham.js',
'test/spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/**/*.js': ['webpack', 'sourcemap']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec'].concat(
coverage ? 'coverage-istanbul' : [],
sauceLabs ? 'saucelabs' : []
),
coverageIstanbulReporter: {
dir: './coverage',
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true,
skipFilesWithNoCoverage: true,
'report-config': {
html: {
subdir: 'html'
},
'text-summary': {
subdir: 'text-summary'
},
lcovonly: {
subdir: '.',
file: 'lcov.info'
}
}
},
mochaReporter: {
showDiff: true
},
browserLogOptions: { terminal: true },
browserConsoleLogOptions: { terminal: true },
browserNoActivityTimeout: 5 * 60 * 1000,
browserDisconnectTimeout: 15 * 1000,
browserDisconnectTolerance: 2,
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: sauceLabs ? Object.keys(sauceLabsLaunchers) : localBrowsers,
customLaunchers: sauceLabs ? sauceLabsLaunchers : travisLaunchers,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 2,
webpack: {
devtool: 'inline-source-map',
resolve: {
extensions: ['.js', '.ts']
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['stage-0', 'es2015-loose']
}
},
{
test: /.js$/,
enforce: 'post',
loader: 'es3ify-loader'
},
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
transpileOnly: true,
compilerOptions: {
target: 'es3',
module: 'commonjs'
}
}
},
coverage ? {
enforce: 'post',
test: /\.ts$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
include: path.resolve('src/'),
exclude: /node_modules/
} : {}
]
},
plugins: [
new webpack.DefinePlugin({
coverage: coverage,
NODE_ENV: JSON.stringify(process.env.NODE_ENV || ''),
DISABLE_FLAKEY: !!String(process.env.FLAKEY).match(/^(0|false)$/gi)
})
]
},
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
}
})
}
| JavaScript | 0.999702 | @@ -2057,29 +2057,24 @@
es/es5-shim/
-dist/
es5-shim.js'
@@ -2110,13 +2110,8 @@
him/
-dist/
es5-
|
ff799d8ab5a30fd41176ec662720ff024ca46f8a | Enable Firefox for karma tests locally | karma.conf.js | karma.conf.js | // Karma configuration file
//
// For all available config options and default values, see:
// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54
module.exports = function (config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: [
'mocha'
],
// list of files / patterns to load in the browser
files: [
{pattern: 'demo.html', included: false, watched: false}, //demo can be accessed at http://localhost:9876/base/demo.html
'bower_components/jquery/jquery.js',
'bower_components/lodash/dist/lodash.js',
'bower_components/chai/chai.js',
'bower_components/sinon-chai/lib/sinon-chai.js',
'bower_components/sinonjs/sinon.js',
'carousel.js',
'test/**/*.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress', 'junit', 'teamcity'
// CLI --reporters progress
reporters: ['dots'],
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// start these browsers
// CLI --browsers Chrome,Firefox,Safari
browsers: [
'Chrome',
// 'Firefox'
],
// if browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
plugins: [
'karma-mocha',
'karma-requirejs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-safari-launcher'
]
});
};
| JavaScript | 0 | @@ -1280,19 +1280,16 @@
',%0A
- //
'Firefo
|
d9956aa2b8f08fabf7cb41554398d2167dfe6cee | fix karma coverage paths | karma.conf.js | karma.conf.js | // Karma configuration
// Generated on Sat Feb 01 2014 15:17:26 GMT-0800 (PST)
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [{
pattern: 'lib/random.js'
}, {
pattern: 'spec/**/*Spec.js'
}],
// list of files to exclude
exclude: [
],
preprocessors: {
'random.js': 'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
}; | JavaScript | 0.000044 | @@ -504,16 +504,20 @@
%0A '
+lib/
random.j
|
7193fb6dddfbba6e452c65b89145ebd5c0d058a2 | fix karma-coverage path | karma.conf.js | karma.conf.js | /*globals module*/
// Karma configuration
// Generated on Thu Aug 13 2015 23:57:08 GMT-0400 (EDT)
module.exports = function(config) {
"use strict";
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["mocha", "chai-as-promised", "chai"],
// list of files / patterns to load in the browser
files: [
"js/lib/async.js",
"test/*.js",
"test/**/*.js"
],
// list of files to exclude
exclude: [
"**/*.swp",
"*.swp",
".DS_Store"
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"js/*.js": ["coverage"],
"js/**/*.js": ["coverage"]
},
// test results reporter to use
// possible values: "dots", "progress"
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["progress", "coverage", "coveralls"],
coverageReporter: {
dir: "build/reports/coverage",
reporters: [
{type: "lcov", subdir: "lcov"},
{type: "html", subdir: "html"},
{type: "text", subdir: ".", file: "text.txt"},
{type: "text-summary", subdir: ".", file: "text-summary.txt"},
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ["FirefoxNightly"],
browserNoActivityTimeout: 10000,
browserDisconnectTimeout: 2000,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| JavaScript | 0.002723 | @@ -840,39 +840,8 @@
: %7B%0A
- %22js/*.js%22: %5B%22coverage%22%5D,%0A
|
59b1c5a57198214e86a79494b0c3d9bd29a48c86 | Fix test path | karma.conf.js | karma.conf.js | // Karma configuration
// Generated on Fri Feb 07 2014 08:31:06 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '.',
// frameworks to use
frameworks: ['mocha', 'chai-sinon'],
// list of files / patterns to load in the browser
files: [
'bower_components/jquery/dist/jquery.min.js',
'test/lib/angular.js',
'test/lib/angular-mocks.js',
'bower_components/tv4/tv4.js',
'bower_components/objectpath/lib/ObjectPath.js',
'src/module.js',
'src/sfPath.js',
'src/services/*.js',
'src/directives/*.js',
'src/directives/decorators/bootstrap/*.js',
'src/**/*.html',
'test/services/schema-form-test.js',
'test/decorator-factory-service-test.js',
'test/directive-test.js',
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress','coverage','growler'],
preprocessors: {
'src/**/*.js': ['coverage'],
'src/**/*.html': ['ng-html2js']
},
// optionally, configure the reporter
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
},
ngHtml2JsPreprocessor: {
cacheIdFromPath: function(filepath) {
return filepath.substr(4);
},
moduleName: 'templates'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| JavaScript | 0.00001 | @@ -789,33 +789,27 @@
est/
-decorator-factory-service
+services/decorators
-tes
|
301017373353443755665acf8f4494384c6c9725 | Disable hardware acceleration for unit tests | karma.conf.js | karma.conf.js | /* eslint camelcase: 0 */
module.exports = function(karma) {
var args = karma.args || {};
var config = {
browsers: ['Firefox'],
frameworks: ['browserify', 'jasmine'],
reporters: ['progress', 'kjhtml'],
preprocessors: {
'./test/jasmine.index.js': ['browserify'],
'./src/**/*.js': ['browserify']
},
browserify: {
debug: true
},
// These settings deal with browser disconnects. We had seen test flakiness from Firefox
// [Firefox 56.0.0 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
// https://github.com/jasmine/jasmine/issues/1327#issuecomment-332939551
browserDisconnectTolerance: 3
};
// https://swizec.com/blog/how-to-run-javascript-tests-in-chrome-on-travis/swizec/6647
if (process.env.TRAVIS) {
config.browsers.push('chrome_travis_ci');
config.customLaunchers = {
chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
};
} else {
config.browsers.push('Chrome');
}
if (args.coverage) {
config.reporters.push('coverage');
config.browserify.transform = ['browserify-istanbul'];
// https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
config.coverageReporter = {
dir: 'coverage/',
reporters: [
{type: 'html', subdir: 'report-html'},
{type: 'lcovonly', subdir: '.', file: 'lcov.info'}
]
};
}
karma.set(config);
};
| JavaScript | 0 | @@ -105,33 +105,8 @@
= %7B%0A
-%09%09browsers: %5B'Firefox'%5D,%0A
%09%09fr
@@ -178,16 +178,445 @@
jhtml'%5D,
+%0A%09%09browsers: %5B'chrome', 'firefox'%5D,%0A%0A%09%09// Explicitly disable hardware acceleration to make image%0A%09%09// diff more stable when ran on Travis and dev machine.%0A%09%09// https://github.com/chartjs/Chart.js/pull/5629%0A%09%09customLaunchers: %7B%0A%09%09%09chrome: %7B%0A%09%09%09%09base: 'Chrome',%0A%09%09%09%09flags: %5B%0A%09%09%09%09%09'--disable-accelerated-2d-canvas'%0A%09%09%09%09%5D%0A%09%09%09%7D,%0A%09%09%09firefox: %7B%0A%09%09%09%09base: 'Firefox',%0A%09%09%09%09prefs: %7B%0A%09%09%09%09%09'layers.acceleration.disabled': true%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D,
%0A%0A%09%09prep
@@ -1176,193 +1176,55 @@
fig.
-browsers.push('chrome_travis_ci');%0A%09%09config.customLaunchers = %7B%0A%09%09%09chrome_travis_ci: %7B%0A%09%09%09%09base: 'Chrome',%0A%09%09%09%09flags: %5B'--no-sandbox'%5D%0A%09%09%09%7D%0A%09%09%7D;%0A%09%7D else %7B%0A%09%09config.browsers.push('Chrome
+customLaunchers.chrome.flags.push('--no-sandbox
');%0A
|
f86ec1bb62cc85cbd84a718bb72c73a2112749ac | 添加input sizes of >500KB 的参数 compact | karma.conf.js | karma.conf.js | "use strict";
const path = require("path");
const webpackConfig = require("./webpack.config.js");
module.exports = function(config) {
config.set({
frameworks: ["mocha"],
files: ["test/*.js"],
plugins: [
"karma-babel-preprocessor",
"karma-webpack",
"karma-mocha",
"karma-phantomjs-launcher",
// "karma-chrome-launcher",
"karma-coverage-istanbul-reporter",
"karma-mocha-reporter"
],
resolve: {
extensions: ['.json', '.js','.png']
},
// browsers: ["Chrome", "PhantomJS"],
browsers: ["PhantomJS"],
preprocessors: {
"test/*.js": ["webpack", "babel"]
},
scssPreprocessor: {
options: {
sourceMap: true,
includePaths: ['bower_components']
}
},
reporters: ["coverage-istanbul", "mocha"],
coverageIstanbulReporter: {
reports: ['text-summary','html'],
fixWebpackSourcePaths: true
},
mochaReporter: {
colors: {
success: 'blue',
info: 'bgGreen',
warning: 'cyan',
error: 'bgRed'
},
symbols: {
success: '+',
info: '#',
warning: '!',
error: 'x'
}
},
webpack: {
module: {
rules: [{
test: /\.js$/i,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
},{
loader: 'istanbul-instrumenter-loader',
options: {
esModules: true
}
}]
}, {
test: /\.svg$/,
loaders: [
'babel-loader', {
loader: 'react-svg-loader',
query: {
jsx: true
}
}
]
}, {
test: /\.json$/,
loader: "json-loader"
}, {
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader',
exclude:'/images/'
// include: path.resolve('src/')
},
{
test: /\.(png|jpg|gif|woff|woff2|eot|ttf)$/,
loader: 'url-loader?limit=8192&name=images/[name]-[hash:8].[ext]'
}
]
},
externals: {
'jsdom': 'window',
'react/lib/ExecutionEnvironment': true,
'react/addons': true,
'react/lib/ReactContext': 'window',
'sinon': 'window.sinon'
}
},
webpackMiddleware: {
noInfo: true
},
singleRun: true,
concurrency: Infinity,
autoWatch: false
});
}; | JavaScript | 0 | @@ -696,16 +696,183 @@
%09%7D%0A%09%09%7D,%0A
+%09%09babelPreprocessor: %7B%0A%09%09%09options: %7B%0A%09%09%09%09// presets: %5B'es2015','react','stage-0'%5D,%0A%09%09%09%09// sourceMap: 'inline',%0A%09%09%09%09// input sizes of %3E500KB%0A%09%09%09%09compact:true%0A%09%09%09%7D%0A%09%09%7D,%0A
%09%09report
@@ -1774,32 +1774,8 @@
r',%0A
-%09%09%09%09%09exclude:'/images/'%0A
%09%09%09%09
|
80590108b318f201e410bf417e15b61847669d6f | use ChromeHeadless | karma.conf.js | karma.conf.js | var path = require('path');
module.exports = function(config) {
var options = {
files: ['test/index.spec.js'],
preprocessors: {
'test/index.spec.js': ['webpack']
},
webpack: {
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.js$/,
include: path.resolve('src/'),
loader: 'istanbul-instrumenter-loader'
}
]
}
},
webpackMiddleware: {
noInfo: true
},
reporters: ['spec', 'coverage'],
coverageReporter: {
type: 'lcov',
dir: 'coverage/',
subdir: '.'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
browsers: ['Chrome'],
customLaunchers: {
ChromeTravisCI: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
frameworks: ['mocha', 'chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-coverage',
'karma-webpack',
'karma-chrome-launcher',
'karma-spec-reporter'
],
captureTimeout: 60000,
autoWatch: false,
singleRun: true,
// tests on Travis were timing out
browserDisconnectTimeout: 60000,
browserNoActivityTimeout: 60000
};
if (process.env.TRAVIS) {
options.browsers = ['ChromeTravisCI'];
}
config.set(options);
};
| JavaScript | 0 | @@ -803,333 +803,53 @@
rome
-'%5D,%0A customLaunchers: %7B%0A ChromeTravisCI: %7B%0A base: 'Chrome',%0A flags: %5B'--no-sandbox'%5D%0A %7D%0A %7D,%0A%0A frameworks: %5B'mocha', 'chai'%5D,%0A%0A plugins: %5B%0A 'karma-mocha',%0A 'karma-chai',%0A 'karma-coverage',%0A 'karma-webpack',%0A 'karma-chrome-launcher',%0A 'karma-spec-reporter'%0A
+Headless'%5D,%0A%0A frameworks: %5B'mocha', 'chai'
%5D,%0A%0A
@@ -1042,84 +1042,8 @@
%7D;%0A%0A
- if (process.env.TRAVIS) %7B%0A options.browsers = %5B'ChromeTravisCI'%5D;%0A %7D%0A%0A
co
|
dcb1e484445be8b8eb3857b9618fb35ea7a62a8f | Reduce browser concurrency to 1 | karma.conf.js | karma.conf.js | 'use strict';
const path = require('path');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const nodeBuiltins = require('rollup-plugin-node-builtins');
const globals = require('rollup-plugin-node-globals');
const babel = require('rollup-plugin-babel');
const istanbul = require('rollup-plugin-istanbul');
const rollupConfig = require('./rollup.config');
let config;
const local = typeof process.env.CI === 'undefined' || process.env.CI === 'false';
const port = 9001;
if ( local ) {
config = {
browsers: ['Chrome'],
};
} else {
config = {
browserStack: {
startTunnel: true,
project: 'element-within-viewport',
name: 'Automated (Karma)',
build: 'Automated (Karma)'
},
customLaunchers: {
'BS-Chrome': {
base: 'BrowserStack',
browser: 'Chrome',
os: 'Windows',
'os_version': '7',
project: 'element-within-viewport',
build: 'Automated (Karma)',
name: 'Chrome'
},
'BS-Firefox': {
base: 'BrowserStack',
browser: 'Firefox',
os: 'Windows',
'os_version': '7',
project: 'element-within-viewport',
build: 'Automated (Karma)',
name: 'Firefox'
},
'BS-IE9': {
base: 'BrowserStack',
browser: 'IE',
'browser_version': '9',
os: 'Windows',
'os_version': '7',
project: 'element-within-viewport',
build: 'Automated (Karma)',
name: 'IE9'
},
},
browsers: ['BS-Chrome', 'BS-Firefox', 'BS-IE9']
};
}
module.exports = function ( baseConfig ) {
baseConfig.set(Object.assign({
basePath: '',
frameworks: ['mocha', 'viewport', 'fixture'],
files: [
'test/**/*.css',
'test/**/*.html',
{ pattern: 'test/**/*.js', watched: false }
],
exclude: [],
preprocessors: {
'test/**/*.html': ['html2js'],
'test/**/*.js': ['rollup', 'sourcemap']
},
reporters: ['mocha', 'coverage-istanbul'],
port: port,
colors: true,
logLevel: baseConfig.LOG_INFO,
autoWatch: false,
client: {
mocha: {
timeout: 20000
},
captureConsole: true
},
browserConsoleLogOptions: {
level: 'log',
format: '%b %T: %m',
terminal: true
},
browserNoActivityTimeout: 60000,
rollupPreprocessor: {
plugins: [
nodeBuiltins(),
babel({
exclude: 'node_modules/**',
runtimeHelpers: true
}),
resolve({
preferBuiltins: true
}),
commonjs(),
globals(),
...rollupConfig.plugins.filter(({ name }) => !['babel'].includes(name)),
istanbul({
exclude: ['test/**/*.js', 'node_modules/**/*']
})
],
output: {
format: 'iife',
name: 'elementWithinViewport',
sourcemap: 'inline',
intro: 'window.TYPED_ARRAY_SUPPORT = false;' // IE9
}
},
coverageIstanbulReporter: {
dir: path.join(__dirname, 'coverage/%browser%'),
fixWebpackSourcePaths: true,
reports: ['html', 'text'],
thresholds: {
global: {
statements: 50
}
}
},
singleRun: true,
concurrency: Infinity
}, config));
};
| JavaScript | 0.999993 | @@ -2943,16 +2943,9 @@
cy:
-Infinity
+1
%0A%09%7D,
|
cc5f9abfddc8bbee3e0a0d5801932cf282729a70 | Modify the port of karma conf and add a hostname into karma conf. | karma.conf.js | karma.conf.js | // Karma configuration
// Generated on Sat Nov 14 2015 08:16:16 GMT+0000 (UTC)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-as-promised', 'chai-dom', 'chai', 'sinon-chai'],
client: {
mocha: {
timeout: 5000
}
},
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'./angular-7segments.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'angular-7segments.js': 'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec', 'coverage'],
// web server port
port: process.env.PORT, // replace with your port
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
| JavaScript | 0 | @@ -1249,16 +1249,24 @@
env.PORT
+ %7C%7C 9876
, // rep
@@ -1286,16 +1286,70 @@
r port%0A%0A
+ hostname: process.env.IP %7C%7C 'localhost',%0A %0A
%0A //
|
0f04ab297258188e162fcd3439106f3aba6309a7 | fix sorting | controller/message.js | controller/message.js | 'use strict';
var log = require('log-to-file-and-console-node');
var Message = require('../model/message');
var moment = require('moment');
var _ = require('lodash');
exports.getAllGroupIds = function (callback) {
Message.find().distinct('chatId', callback);
};
exports.addMessage = function (msg, callback) {
var message = new Message();
message.chatId = msg.chat.id || '';
message.userId = msg.from.id || '';
message.username = msg.from.username || '';
/*jshint camelcase: false */
message.firstName = msg.from.first_name || '';
message.lastName = msg.from.last_name || '';
/*jshint camelcase: true */
message.save(callback);
};
var getJung = function(chatId, limit, callback) {
var greaterThanOrEqualToSevenDaysQuery = {
chatId: chatId.toString(),
dateCreated: {
$gte: new Date(moment().subtract(7, 'day').toISOString())
}
};
Message.count(greaterThanOrEqualToSevenDaysQuery, function (err, total) {
log.i('Number of messages: ' + total);
var query = [
{
$match: greaterThanOrEqualToSevenDaysQuery
},
{
$sort: {
count: -1
}
},
{
$group: {
_id: '$userId',
username: {$last: '$username'},
firstName: {$last: '$firstName'},
lastName: {$last: '$lastName'},
count: {$sum: 1}
}
}
];
if (limit && limit > 0) {
query.push({
$limit: limit
});
}
Message.aggregate(query, function (err, result) {
if (!err && result && _.isArray(result)) {
for (var i = 0, l = result.length; i < l; i++) {
result[i].total = total;
result[i].percent = ((result[i].count / total) * 100).toFixed(2) + '%';
}
}
callback(err, result);
});
});
};
exports.getAllJung = function (chatId, callback) {
getJung(chatId, null, callback);
};
exports.getTopTen = function (chatId, callback) {
getJung(chatId, 10, callback);
};
| JavaScript | 0.000011 | @@ -1085,72 +1085,8 @@
%7B%0A
- $sort: %7B%0A count: -1%0A %7D%0A %7D,%0A %7B%0A
@@ -1286,24 +1286,88 @@
%7D%0A %7D%0A
+ %7D,%0A %7B%0A $sort: %7B%0A count: -1%0A %7D%0A
%7D%0A
|
ffb2c7b798c6a70971b3fa09079ddbc58e773551 | Refactor Forgot controller | controllers/forgot.js | controllers/forgot.js | 'use strict';
/**
* Module dependencies.
*/
var async = require('async');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');
var nodemailer = require("nodemailer");
var User = require('../models/User');
var secrets = require('../config/secrets');
/**
* Forgot Controller
*/
/**
The general outline of the best practice is:
1) Identify the user is a valid account holder. Use as much information as practical.
- Email Address (*Bare Minimin*)
- Username
- Account Number
- Security Questions
- Etc.
2) Create a special one-time (nonce) token, with a expiration period, tied to the person's account.
In this example We will store this in the database on the user's record.
3) Send the user a link which contains the route ( /reset/:id/:token/ ) where the
user can change their password.
4) When the user clicks the link:
- Lookup the user/nonce token and check expiration. If any issues send a message
to the user: "this link is invalid".
- If all good then continue - render password reset form.
5) The user enters their new password (and possibly a second time for verification)
and posts this back.
6) Validate the password(s) meet complexity requirements and match. If so, hash the
password and save it to the database. Here we will also clear the reset token.
7) Email the user "Success, your password is reset". This is important in case the user
did not initiate the reset!
7) Redirect the user. Could be to the login page but since we know the users email and
password we can simply authenticate them and redirect to a logged in location - usually
home page.
*/
/**
* GET /forgot
* Forgot your password page.
*/
exports.getForgot = function(req, res) {
if (req.user) return res.redirect('/'); //user already logged in!
res.render('account/forgot', {
title: 'Forgot Password'
});
};
/**
* POST /forgot
* Reset Password.
* @param {string} email
*/
exports.postForgot = function(req, res) {
req.assert('email', 'Please enter a valid email address.').isEmail();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/forgot');
}
async.waterfall([
function(done) {
/**
* Generate a one-time token.
*/
crypto.randomBytes(32, function(err, buf) {
var token = buf.toString('base64');
done(err, token);
});
},
function(token, done) {
/**
* Save the token and token expiration.
*/
User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) {
if (!user) {
req.flash('errors', { msg: 'No account with that email address exists.' });
return res.redirect('/forgot');
}
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
/**
* Send the user an email with a reset link.
*/
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: {
user: secrets.sendgrid.user,
pass: secrets.sendgrid.password
}
});
var mailOptions = {
to: user.profile.name + ' <' + user.email + '>',
from: 'hackathon@starter.com',
subject: 'Hackathon Starter Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', { msg: 'We have sent an email to ' + user.email + ' for further instructions.' });
done(err, 'done');
res.redirect('/forgot');
});
}
]);
};
| JavaScript | 0 | @@ -1,1840 +1,343 @@
-'use strict';%0A%0A/**%0A * Module dependencies.%0A */%0Avar async = require('async');%0Avar bcrypt = require('bcrypt-nodejs');%0Avar crypto = require('crypto');%0Avar mongoose = require('mongoose');%0Avar nodemailer = require(%22nodemailer%22);%0Avar User = require('../models/User');%0Avar secrets = require('../config/secrets');%0A%0A/**%0A * Forgot Controller%0A */%0A%0A/**%0A%0A The general outline of the best practice is:%0A%0A 1) Identify the user is a valid account holder. Use as much information as practical.%0A - Email Address (*Bare Minimin*)%0A - Username%0A - Account Number%0A - Security Questions%0A - Etc.%0A%0A 2) Create a special one-time (nonce) token, with a expiration period, tied to the person's account.%0A In this example We will store this in the database on the user's record.%0A%0A 3) Send the user a link which contains the route ( /reset/:id/:token/ ) where the%0A user can change their password.%0A%0A 4) When the user clicks the link:%0A - Lookup the user/nonce token and check expiration. If any issues send a message%0A to the user: %22this link is invalid%22.%0A - If all good then continue - render password reset form.%0A%0A 5) The user enters their new password (and possibly a second time for verification)%0A and posts this back.%0A%0A 6) Validate the password(s) meet complexity requirements and match. If so, hash the%0A password and save it to the database. Here we will also clear the reset token.%0A%0A 7) Email the user %22Success, your password is reset%22. This is important in case the user%0A did not initiate the reset!%0A%0A 7) Redirect the user. Could be to the login page but since we know the users email and%0A password we can simply authenticate them and redirect to a logged in location - usually%0A home page.%0A%0A */%0A%0A%0A/**%0A * GET /forgot%0A * Forgot your password page.%0A */%0A%0Aexports.getForgot = function(req, res) %7B%0A if (req.user) return res.redirect('/'); //user already logged in!
+var async = require('async');%0Avar crypto = require('crypto');%0Avar nodemailer = require(%22nodemailer%22);%0Avar User = require('../models/User');%0Avar secrets = require('../config/secrets');%0A%0A/**%0A * GET /forgot%0A * Forgot Password page.%0A */%0A%0Aexports.getForgot = function(req, res) %7B%0A if (req.isAuthenticated()) %7B%0A return res.redirect('/');%0A %7D
%0A r
@@ -457,17 +457,8 @@
aram
- %7Bstring%7D
ema
@@ -755,64 +755,8 @@
) %7B%0A
- /**%0A * Generate a one-time token.%0A */%0A
@@ -920,74 +920,8 @@
) %7B%0A
- /**%0A * Save the token and token expiration.%0A */%0A
@@ -1403,79 +1403,8 @@
) %7B%0A
- /**%0A * Send the user an email with a reset link.%0A */%0A
|
d9c36b938008e9114e054f7452453fad6883fade | document inability to be run on a path below an URL with a hostname - as discussed in https://ghost.org/forum/installation/341-how-do-i-run-ghost-on-a-subdirectory | config.example.js | config.example.js | // # Ghost Configuration
// Setup your Ghost install for various environments
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://my-ghost-blog.com',
// Example mail config
// Visit http://docs.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://my-ghost-blog.com',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
},
// ### Travis
// Automated testing run through GitHub
'travis-sqlite3': {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-travis.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
},
// ### Travis
// Automated testing run through GitHub
'travis-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'travis',
password : '',
database : 'ghost_travis',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
}
}
};
// Export config
module.exports = config;
| JavaScript | 0.000001 | @@ -263,16 +263,115 @@
email.%0A
+ // must not contain a path suffix after the hostname - %22subdirs%22 are not (yet) supported! %0A
@@ -1462,32 +1462,131 @@
production: %7B%0A
+ // must not contain a path suffix after the hostname - %22subdirs%22 are not (yet) supported! %0A
url: 'ht
|
bee0cc7a0554c76fe4635b149c3d9a9d97156dd5 | tweak colours and numbers on tectonic sketch | tectonic2/sketch.js | tectonic2/sketch.js | let sketch = function(p) {
let THE_SEED;
let width = 500;
let resolution = 250;
let noise_zoom = 150;
let magnitude = 100;
let plate_padding = 0;
let number_of_blocks = 70;
let blocks = [];
let palette;
p.setup = function() {
p.createCanvas(1200, 1800);
p.noLoop();
p.strokeWeight(1);
palette = [
p.color(145, 172, 183),
p.color(182, 32, 36),
p.color(155, 80, 43),
p.color(81, 82, 111),
p.color(201, 179, 171),
p.color(221, 226, 222)
];
THE_SEED = p.floor(p.random(9999999));
p.noiseSeed(THE_SEED);
for (var i = 0; i < number_of_blocks; i++) {
blocks.push(create_block(p.random(1, 10), i));
}
};
p.draw = function() {
p.background('#e0e1db');
let current_height = 0;
p.translate(65, p.height - 65);
blocks.forEach(function(block, index) {
let block_height = p.abs(Math.min(...block[block.length - 1].points) - 60);
if (current_height + block_height < p.height - 200) {
display_block(block, index);
p.translate(0, -block_height);
current_height += block_height;
} else {
p.translate(570, current_height);
display_block(block, index);
p.translate(0, -block_height);
current_height = block_height;
}
}, this);
};
function create_block(number_of_plates, block_index) {
let plates = [];
for (var plate_index = 0; plate_index < number_of_plates; plate_index++) {
let points = [];
let plate_height = p.randomGaussian(0, 10);
if (plate_index > 0) {
for (let i = 0; i <= resolution; i++) {
points.push(
p.min(-plate_padding, get_noise(i, plate_index, block_index) - plate_height) +
plates[plate_index - 1].points[i]
);
}
} else {
for (let i = 0; i <= resolution; i++) {
points.push(p.min(-plate_padding, get_noise(i, plate_index, block_index) - plate_height));
}
}
plates.push({
points: points,
color: palette[p.floor(p.random(palette.length))]
});
}
return plates;
}
function display_block(block, block_index) {
block.forEach(function(plate, index) {
p.fill(plate.color);
p.beginShape();
if (index === 0) {
p.vertex(0, 0);
p.vertex(width, 0);
} else {
for (let i = 0; i <= resolution; i++) {
p.vertex(i * width / resolution, block[index - 1].points[i] - plate_padding);
}
}
for (let i = resolution; i >= 0; i--) {
p.vertex(i * width / resolution, block[index].points[i]);
}
p.endShape(p.CLOSE);
}, this);
}
function get_noise(x, y, z) {
return -magnitude * (p.noise(x / noise_zoom, y, z) - 0.4);
}
p.keyPressed = function() {
if (p.keyCode === 80) p.saveCanvas('tectonic_' + THE_SEED, 'jpeg');
};
};
new p5(sketch);
| JavaScript | 0 | @@ -101,17 +101,17 @@
zoom = 1
-5
+8
0;%0A let
@@ -352,21 +352,20 @@
lor(
-145, 172
+240, 204
, 18
-3
),%0A
@@ -381,19 +381,19 @@
lor(
-182, 32, 36
+236, 65, 38
),%0A
@@ -410,18 +410,19 @@
or(1
-55, 80, 43
+70, 132, 94
),%0A
@@ -438,18 +438,20 @@
lor(
-81, 82, 11
+244, 188, 19
1),%0A
@@ -468,21 +468,21 @@
lor(
-201, 179, 171
+118, 158, 190
),%0A
@@ -499,20 +499,20 @@
or(2
-21, 226, 222
+34, 235, 230
)%0A
@@ -2782,17 +2782,17 @@
z) - 0.
-4
+3
);%0A %7D%0A%0A
|
05d3d7ff6beff0cfdbc6c5229d0888ccb7c5694a | update example config to relevant format | config.example.js | config.example.js | module.exports = {
"appId" : "",
"appPassword" : ""
} | JavaScript | 0 | @@ -11,11 +11,11 @@
orts
- =
+%C2%A0=%C2%A0
%7B%0A
@@ -23,19 +23,18 @@
%22appId%22
- :
+:%C2%A0
%22%22,%0A
@@ -50,11 +50,130 @@
ord%22
- : %22%22%0A%7D
+:%C2%A0%22%22,%0A %22dbEndpoint%22:%C2%A0%22%22,%0A %22dbKey%22:%C2%A0%22%22,%0A %22dbSProc%22:%C2%A0%7B%0A %22getRandomWord%22:%C2%A0%22%22%0A %7D,%0A %22dictionaryApiKey%22:%C2%A0%22%22%0A%7D;
|
01c3baa8c43e976267c47934b99f7f4b210d36b6 | Disable async/await to run on v6 | tests/unit/core/randomGeneration.spec.js | tests/unit/core/randomGeneration.spec.js | import { expect } from 'chai';
import jsf from '../../../src';
/* global describe, it */
describe('Random Generation', () => {
it('should generate all the fields with alwaysFakeOptionals option and additionalProperties: true', async () => {
jsf.option({
alwaysFakeOptionals: true,
});
const schema = {
type: 'object',
properties: {
foo: { type: 'string' },
bar: { type: 'string' },
},
required: [],
additionalProperties: true,
};
const resolved = await jsf.resolve(schema);
expect(Object.keys(resolved).length).to.be.at.least(2);
});
it('should generate all the fields with alwaysFakeOptionals option and additionalProperties: false', async () => {
jsf.option({
alwaysFakeOptionals: true,
});
const schema = {
type: 'object',
properties: {
foo: { type: 'string' },
bar: { type: 'string' },
},
required: [],
additionalProperties: false,
};
const resolved = await jsf.resolve(schema);
expect(Object.keys(resolved).length).is.eql(2);
});
});
| JavaScript | 0 | @@ -223,22 +223,16 @@
: true',
- async
() =%3E %7B
@@ -499,53 +499,56 @@
-const resolved = await jsf.resolve(schema);%0A%0A
+return jsf.resolve(schema).then(resolved =%3E %7B%0A
@@ -599,24 +599,32 @@
t.least(2);%0A
+ %7D);%0A
%7D);%0A it('
@@ -723,14 +723,8 @@
se',
- async
()
@@ -996,53 +996,56 @@
-const resolved = await jsf.resolve(schema);%0A%0A
+return jsf.resolve(schema).then(resolved =%3E %7B%0A
@@ -1092,16 +1092,24 @@
eql(2);%0A
+ %7D);%0A
%7D);%0A%7D)
|
87f7450aaef32a85b47d3f742abca30c27310a41 | add temp filter on workflow completeness | src/reducers/workflows.js | src/reducers/workflows.js | import * as types from 'constants/actions';
const initialState = {
workflowsFetched: false,
allWorkflows: [],
activeWorkflows: [],
inactiveWorkflows: [],
};
export function workflows(state = initialState, action) {
switch (action.type) {
case types.WORKFLOWS_REQUESTED:
return Object.assign({}, state, { workflowsFetched: false });
case types.WORKFLOWS_RECEIVED:
return Object.assign({}, state, {
workflowsFetched: true,
allWorkflows: action.json.filter(w => !w.display_name.match(/Template/i)),
activeWorkflows: action.json.filter(w => w.active),
inactiveWorkflows: action.json.filter(w => !w.active && !w.display_name.match(/Template/i)),
});
default:
return state;
}
}
| JavaScript | 0 | @@ -689,32 +689,56 @@
tch(/Template/i)
+ && w.completeness === 1
),%0A %7D);%0A%0A
|
e67d77b6d5f1b640b7ac2401d3a553959d426fd1 | Fix deep-db RUM logging when used in deploy hooks | src/deep-db/lib/DB.js | src/deep-db/lib/DB.js | /**
* Created by AlexanderC on 6/15/15.
*/
'use strict';
import Kernel from 'deep-kernel';
import Vogels from 'vogels';
import {ExtendModel} from './Vogels/ExtendModel';
import {ModelNotFoundException} from './Exception/ModelNotFoundException';
import Validation from 'deep-validation';
import Utils from 'util';
import {FailedToCreateTableException} from './Exception/FailedToCreateTableException';
import {FailedToCreateTablesException} from './Exception/FailedToCreateTablesException';
import {AbstractDriver} from './Local/Driver/AbstractDriver';
/**
* Vogels wrapper
*/
export class DB extends Kernel.ContainerAware {
/**
* @param {Array} models
* @param {Object} tablesNames
*/
constructor(models = [], tablesNames = {}) {
super();
// @todo: set retries in a smarter way...
Vogels.AWS.config.maxRetries = 3;
this._tablesNames = tablesNames;
this._validation = new Validation(models);
this._models = this._rawModelsToVogels(models);
// @todo: remove?
this._localDbProcess = null;
}
/**
* @returns {Validation}
*/
get validation() {
return this._validation;
}
/**
* @returns {Vogels[]}
*/
get models() {
return this._models;
}
/**
* @param {String} modelName
* @returns {Boolean}
*/
has(modelName) {
return typeof this._models[modelName] !== 'undefined';
}
/**
* @param {String} modelName
* @returns {Vogels}
*/
get(modelName) {
if (!this.has(modelName)) {
throw new ModelNotFoundException(modelName);
}
let model = this._models[modelName];
// inject logService into extended model to log RUM events
model.logService = this.kernel.get('log');
return model;
}
/**
* @param {String} modelName
* @param {Function} callback
* @param {Object} options
* @returns {DB}
*/
assureTable(modelName, callback, options = {}) {
if (!this.has(modelName)) {
throw new ModelNotFoundException(modelName);
}
options = Utils._extend(DB.DEFAULT_TABLE_OPTIONS, options);
options[modelName] = options;
Vogels.createTables(options, (error) => {
if (error) {
throw new FailedToCreateTableException(modelName);
}
callback();
});
return this;
}
/**
* @param {Function} callback
* @param {Object} options
* @returns {DB}
*/
assureTables(callback, options = {}) {
let allModelsOptions = {};
let allModelNames = [];
for (let modelName in this._models) {
if (!this._models.hasOwnProperty(modelName)) {
continue;
}
allModelsOptions[modelName] = Utils._extend(DB.DEFAULT_TABLE_OPTIONS, options);
allModelNames.push(modelName);
}
Vogels.createTables(allModelsOptions, (error) => {
if (error) {
throw new FailedToCreateTablesException(allModelNames, error);
}
callback();
});
return this;
}
/**
* Booting a certain service
*
* @param {Kernel} kernel
* @param {Function} callback
*/
boot(kernel, callback) {
this._validation.boot(kernel, () => {
this._tablesNames = kernel.config.tablesNames;
this._models = this._rawModelsToVogels(kernel.config.models);
if (this._localBackend) {
this._enableLocalDB(callback);
} else {
callback();
}
});
}
/**
* @param {Object} driver
* @returns {DB}
* @private
*/
_setVogelsDriver(driver) {
Vogels.dynamoDriver(driver);
return this;
}
/**
* @param {Function} callback
* @param {String} driver
* @param {Number} tts
* @returns {AbstractDriver}
*/
static startLocalDynamoDBServer(callback, driver = 'LocalDynamo', tts = AbstractDriver.DEFAULT_TTS) {
let LocalDBServer = require('./Local/DBServer').DBServer;
let server = LocalDBServer.create(driver);
server.start(callback, tts);
return server;
}
/**
* @param {Function} callback
* @private
*/
_enableLocalDB(callback) {
this._setVogelsDriver(
new Vogels.AWS.DynamoDB({
endpoint: new Vogels.AWS.Endpoint(`http://localhost:${DB.LOCAL_DB_PORT}`),
accessKeyId: 'fake',
secretAccessKey: 'fake',
region: 'us-east-1',
})
);
this.assureTables(callback);
}
/**
* @returns {Object}
*/
static get DEFAULT_TABLE_OPTIONS() {
return {
readCapacity: 5,
writeCapacity: 5,
};
}
/**
* @param {Array} rawModels
* @returns {Object}
*/
_rawModelsToVogels(rawModels) {
let models = {};
for (let modelKey in rawModels) {
if (!rawModels.hasOwnProperty(modelKey)) {
continue;
}
let backendModels = rawModels[modelKey];
for (let modelName in backendModels) {
if (!backendModels.hasOwnProperty(modelName)) {
continue;
}
models[modelName] = new ExtendModel(Vogels.define(
modelName,
this._wrapModelSchema(modelName)
)).inject();
}
}
return models;
}
/**
* @param {String} name
* @returns {Object}
* @private
*/
_wrapModelSchema(name) {
return {
hashKey: 'Id',
timestamps: true,
tableName: this._tablesNames[name],
schema: this._validation.getSchema(name),
};
}
/**
* @returns {Number}
*/
static get LOCAL_DB_PORT() {
return AbstractDriver.DEFAULT_PORT;
}
}
| JavaScript | 0 | @@ -1579,24 +1579,67 @@
odelName%5D;%0A%0A
+ if (this.kernel instanceof Kernel) %7B%0A
// injec
@@ -1689,24 +1689,26 @@
events%0A
+
model.logSer
@@ -1737,16 +1737,22 @@
('log');
+%0A %7D
%0A%0A re
|
b16a5c02e39fd854dd3b6adcaa23aa030b9abcad | Handle the situation where there is a block re-arrangment after the block has been found and the transaction is now pending again. | blobstore.js | blobstore.js | var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var blobstoreAbi = require('./blobstore.abi.json');
var blobstoreContract = web3.eth.contract(blobstoreAbi);
var blobstoreAddress = '0x3c531591cb807e01404574076f429d205f5ee981';
var blobstore = blobstoreContract.at(blobstoreAddress);
// https://github.com/bluedroplet/blobstore-ethereum/blob/c65287e0ff249fec047834e7895cb46c0e090228/blobstore.sol
// Solidity version: 0.1.7-f86451cd/.-Emscripten/clang/int linked to libethereum-1.1.0-35b67881/.-Emscripten/clang/int
var getBlobHash = function(blob) {
return '0x' + web3.sha3(blob.toString('ascii'));
}
var getBlobBlock = function(hash) {
// Determine the block that includes the transaction for this blob.
return blobstore.getBlobBlock(hash, {}, 'latest').toFixed();
}
var storeBlob = function(blob) {
// Determine hash of blob.
var hash = getBlobHash(blob);
// Check if this blob is in a block yet.
if (getBlobBlock(hash) == 0) {
// Calculate maximum transaction gas.
var gas = 44800 + 78 * blob.length;
// Broadcast the transaction. If this blob is already in a pending
// transaction, or has just been mined, this will be handled by the
// contract.
blobstore.storeBlob('0x' + blob.toString('hex'), {gas: gas});
}
return hash;
}
var getBlob = function(hash, callback) {
var blobBlock = getBlobBlock(hash);
if (blobBlock == 0) {
// The blob isn't in a block yet. See if it is in a pending transaction.
var txids = web3.eth.getBlock('pending').transactions;
for (var i in txids) {
var tx = web3.eth.getTransaction(txids[i]);
if (tx.to != blobstoreAddress) {
continue;
}
// Extract the blob from the transaction.
var length = parseInt(tx.input.substr(74, 64), 16);
var blob = new Buffer(tx.input.substr(138, length * 2), 'hex');
// Does it have the correct hash?
if (getBlobHash(blob) == hash) {
callback(null, blob);
return;
}
}
// We didn't find the blob. Check in the blocks one more time in case it
// just got mined and we missed it.
blobBlock = getBlobBlock(hash);
if (blobBlock == 0) {
// We didn't find it. Report the Error.
callback('error');
return;
}
}
// If the blob is in a block that occured within the past hour, search from an
// hour ago until the latest block in case there has been a re-arragement
// since we got the block number (very conservative).
var fromBlock, toBlock;
if (blobBlock > web3.eth.blockNumber - 200) {
fromBlock = web3.eth.blockNumber - 200;
toBlock = 'latest';
}
else {
fromBlock = toBlock = blobBlock;
}
var filter = web3.eth.filter({fromBlock: fromBlock, toBlock: toBlock, address: blobstoreAddress, topics: [hash]});
filter.get(function(error, result) {
if (result.length != 0) {
var length = parseInt(result[0].data.substr(66, 64), 16);
callback(null, new Buffer(result[0].data.substr(130, length * 2), 'hex'));
}
else {
callback('error');
}
});
}
module.exports = {
storeBlob: storeBlob,
getBlobBlock: getBlobBlock,
getBlob: getBlob
};
| JavaScript | 0 | @@ -3078,32 +3078,176 @@
lse %7B%0A
+// There has just been a re-arrangement and the trasaction is now back to%0A // pending. Let's try again from the start.%0A getBlob(hash,
callback
('error');%0A
@@ -3230,32 +3230,24 @@
sh, callback
-('error'
);%0A %7D%0A %7D
|
8a2c4c46f0103bb2151d4d5226323126d89c67c7 | Add more tests | tests/unit/services/params-relay-test.js | tests/unit/services/params-relay-test.js | import { moduleFor, test } from 'ember-qunit';
moduleFor('service:params-relay', 'Unit | Service | params relay', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('setting a param', function(assert) {
let service = this.subject();
assert.notOk(service.getParam('name'));
service.setParam('name', 'bob');
assert.equal(service.getParam('name'), 'bob');
service.setParam('name', 'john');
assert.equal(service.getParam('name'), 'john');
});
| JavaScript | 0 | @@ -1,8 +1,35 @@
+import Ember from 'ember';%0A
import %7B
@@ -522,12 +522,692 @@
john');%0A%7D);%0A
+%0Atest('subscribe fired on set', function(assert) %7B%0A let service = this.subject();%0A%0A service.subscribe('test', (key, val) =%3E %7B%0A assert.equal(key, 'test');%0A assert.equal(val, 'blah');%0A %7D);%0A%0A assert.notOk(service.getParam('test'));%0A service.setParam('test', 'blah');%0A%7D);%0A%0Atest('autoSubscribe changes values', function(assert) %7B%0A let service = this.subject();%0A let target = Ember.Object.create(%7B%0A queryParams: %5B%0A 'hello',%0A %7B myName: 'name' %7D%0A %5D%0A %7D);%0A%0A service.autoSubscribe(target);%0A%0A service.setParam('hello', 'bob');%0A service.setParam('myName', 'john');%0A%0A assert.equal(target.get('hello'), 'bob');%0A assert.equal(target.get('myName'), 'john');%0A%7D);%0A
|
a2e7ac367e9053da9e3df6b468164f031d748c62 | fix adding attachments to slack inbound messages | lib/helpers/slack.js | lib/helpers/slack.js | 'use strict';
/**
* Slack helper
*/
module.exports = {
/**
* parseBody - parses properties out of the body of a Slack request
*
* @param {object} req
* @return {promise}
*/
parseBody: function parseBody(req) {
req.platform = 'slack';
req.platformUserId = req.body.slackId;
req.slackChannel = req.body.slackChannel;
req.platformMessageId = req.body.messageId;
req.mediaUrl = req.body.mediaUrl;
},
};
| JavaScript | 0 | @@ -8,16 +8,63 @@
rict';%0A%0A
+const attachments = require('./attachments');%0A%0A
/**%0A * S
@@ -442,45 +442,207 @@
Id;%0A
+%0A
-req.mediaUrl = req.body.mediaUrl;
+const attachmentObject = attachments.parseFromReq(req);%0A%0A if (attachmentObject.url) %7B%0A req.mediaUrl = attachmentObject.url;%0A attachments.add(req, attachmentObject, 'inbound');%0A %7D
%0A %7D
|
ff6d6cd0428c3c8334a7b85e573b54b145250397 | add weinre | biz/index.js | biz/index.js | var url = require('url');
var https = require('https');
var http = require('http');
var util = require('../util');
var config = util.config;
var FULL_WEINRE_HOST = config.WEINRE_HOST + ':' + config.weinreport;
function request(req, res, port) {
var options = url.parse(util.getFullUrl(req));
options.host = '127.0.0.1';
options.hostname = null;
if (port) {
options.port = port;
}
req.headers['x-forwarded-for'] = util.getClientIp(req);
options.headers = req.headers;
req.pipe(http.request(options, function(_res) {
res.writeHead(_res.statusCode || 0, _res.headers);
res.src(_res);
}));
}
module.exports = function(req, res, next) {
var host = req.headers.host;
if (host == config.localUIHost) {
request(req, res, config.uiport);
} else if (host == config.WEINRE_HOST || host == FULL_WEINRE_HOST) {
request(req, res, config.weinreport);
} else {
next();
}
};
| JavaScript | 0.000104 | @@ -316,16 +316,46 @@
0.0.1';%0A
+%09options.method = req.method;%0A
%09options
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.