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
|
---|---|---|---|---|---|---|---|
30617f0da1089248c5169313ee710f575af19973
|
Move the dot operator
|
js/jquery.imadaem.js
|
js/jquery.imadaem.js
|
/*! Imadaem v0.4.0 http://imadaem.penibelst.de/ */
(function($, window) {
'use strict';
$.fn.imadaem = (function(options) {
var
$elements = this,
settings = $.extend({
dataAttribute: 'imadaem',
timthumbPath: '/timthumb/timthumb.php',
verticalRhythm: null,
windowEvents: 'resize orientationchange'
}, options),
getNativeLength = (function(cssLength) {
var density = window.devicePixelRatio || 1;
return Math.round(cssLength * density);
}()),
lineHeight = (function($element) {
var lh = parseFloat($element.css('line-height'));
return isNaN(lh) ? 0 : lh;
}()),
adjustVerticalRhythm = (function($element, height) {
if (settings.verticalRhythm === 'line-height') {
var lh, l;
lh = lineHeight($element);
if (lh) {
l = Math.max(1, Math.round(height / lh));
height = lh * l;
}
}
return height;
}()),
getData = (function($element) {
var data = $element.data(settings.dataAttribute);
if ($.isPlainObject(data)) {
// ratio must be a number
data.ratio = parseFloat(data.ratio) || 0;
// ignore maxRatio if ratio is set
data.maxRatio = data.ratio ? 0 : parseFloat(data.maxRatio) || 0;
// gravity must be a combination of ['l', 'r', 't', 'b']
data.gravity = data.gravity ?
data.gravity.replace(/[^lrtb]/g, '').substr(0, 2) :
'';
} else {
data = {url: data};
}
return $.extend({
url: '',
gravity: '',
ratio: 0,
maxRatio: 0,
heightGuide: ''
}, data);
}()),
setSrc = (function($element, newSrc) {
var
oldSrc = $element.attr('src'),
errors = 0;
$element
.on('error', (function() {
// fall back to the previous src once
if (!errors) {
errors += 1;
$(this).attr('src', oldSrc);
}
}()))
.attr('src', newSrc);
}()),
scale = (function() {
var
$this,
data,
timthumbParams,
height,
minHeight,
width;
$elements.each(function() {
$this = $(this);
data = getData($this);
if (!data.url) {
return;
}
width = $this.innerWidth();
height = $this.innerHeight();
if (data.ratio) {
height = Math.round(width / data.ratio);
} else if ($(data.heightGuide).length) {
height = $(data.heightGuide).innerHeight();
}
if (data.maxRatio) {
minHeight = Math.round(width / data.maxRatio);
height = Math.max(minHeight, height);
}
height = adjustVerticalRhythm($this, height);
// prevent blinking effects
$this.height(height);
timthumbParams = {
src: data.url || '',
a: data.gravity || '',
w: getNativeLength(width),
h: getNativeLength(height)
};
setSrc($this, settings.timthumbPath + '?' +
$.param(timthumbParams));
});
}());
$(window)
.one('load', scale)
.on(settings.windowEvents, scale);
return this;
}());
}(jQuery, window));
|
JavaScript
| 0.00095 |
@@ -1899,16 +1899,17 @@
$element
+.
%0A
@@ -1911,17 +1911,16 @@
-.
on('erro
@@ -2113,16 +2113,17 @@
%7D()))
+.
%0A
@@ -2125,17 +2125,16 @@
-.
attr('sr
@@ -3352,24 +3352,24 @@
(window)
+.
%0A
-.
one('loa
@@ -3382,16 +3382,16 @@
ale)
+.
%0A
-.
on(s
|
ebe19fc0d51814487147dcb0c8243cc0189233ca
|
boost score of certain languages DEICH-750
|
redef/patron-client/src/backend/utils/queryConstants.js
|
redef/patron-client/src/backend/utils/queryConstants.js
|
const Constants = require('../../frontend/constants/Constants')
module.exports = {
queryDefaults: {
size: 0
},
defaultAggregates: {
facets: {
global: {},
aggs: {}
},
byWork: {
terms: {
field: 'workUri',
order: { top: 'desc' },
size: Constants.maxSearchResults
},
aggs: {
publications: {
top_hits: {
size: 1
}
},
top: {
max: {
script: {
lang: 'painless',
// values to tweak:
// 0.5 = gain (weight factor)
// 100 = scale (in days since catalogued)
inline: 'if (doc.created.value != null) { return _score * (1 + (0.5*100)/(100+(System.currentTimeMillis()-doc.created.date.getMillis())/86400000)); } return _score;'
}
}
}
}
},
workCount: {
cardinality: {
field: 'workUri'
}
}
},
defaultFields: [
'agents',
'author^50',
'bio',
'compType',
'country',
'desc',
'ean',
'format',
'genre',
'inst',
'isbn',
'ismn',
'language',
'litform',
'mainTitle^30',
'mt',
'partNumber',
'partTitle',
'publishedBy',
'recordId',
'series^10',
'subject^10',
'summary',
'title^20',
'workMainTitle',
'workPartNumber',
'workPartTitle',
'workSubtitle'
]
}
|
JavaScript
| 0.999999 |
@@ -502,59 +502,322 @@
-lang: 'painless',%0A // values to tweak:
+inline: %60%0A def langscores = %5B%0A %22nob%22: 1.5,%0A %22nno%22: 1.5,%0A %22nor%22: 1.5,%0A %22eng%22: 1.4,%0A %22swe%22: 1.3,%0A %22dan%22: 1.3,%0A %22ger%22: 1.2,%0A %22fre%22: 1.2,%0A %22spa%22: 1.1,
%0A
@@ -831,39 +831,150 @@
-// 0.5 = gain (weight factor)
+ %22ita%22: 1.1%0A %5D;%0A def langscore = langscores.get(doc.language.value);%0A if (langscore == null) %7B
%0A
@@ -988,51 +988,160 @@
-// 100
+ langscore = 1%0A %7D%0A def score
=
+_
sc
-ale (in days since catalogued)
+ore * langscore;%0A def age_gain=0.5;%0A def age_scale=100;
%0A
@@ -1155,17 +1155,10 @@
-inline: '
+
if (
@@ -1189,44 +1189,72 @@
l) %7B
- return _
+%0A
score *
+=
(1 + (
-0.5*100)/(100
+age_gain*age_scale)/(age_scale
+(Sy
@@ -1323,18 +1323,50 @@
0));
+%0A %7D%0A
-%7D
return
_sco
@@ -1365,15 +1365,64 @@
urn
-_
score;
+%60.replace('%5Cn', ''),%0A lang: 'painless
'%0A
|
8e23e794a17df6638f060284b272d6b99691f269
|
Stop checking server features to determine enterprise vs. standard
|
src/App/Body/Display/Summary/SummaryBody/summaryFunctions/isEnterprise.js
|
src/App/Body/Display/Summary/SummaryBody/summaryFunctions/isEnterprise.js
|
import { withName } from './shared';
import { FEATURES } from 'data/columns';
export default function isEnterprise(modules) {
const serverModule = modules.find(withName('SERVER'));
const hasFeatures = /[CDEFSW]/.test(serverModule[FEATURES]);
const hasModules = ['WSINPUT', 'WSOUTPUT', 'ECOPY'].some(name => (
modules.some(withName(name))
));
return hasFeatures || hasModules;
}
|
JavaScript
| 0 |
@@ -33,49 +33,8 @@
ed';
-%0Aimport %7B FEATURES %7D from 'data/columns';
%0A%0Aex
@@ -83,129 +83,8 @@
) %7B%0A
- const serverModule = modules.find(withName('SERVER'));%0A%0A const hasFeatures = /%5BCDEFSW%5D/.test(serverModule%5BFEATURES%5D);%0A
co
@@ -192,16 +192,16 @@
);%0A%0A
+
return
has
@@ -200,23 +200,8 @@
turn
- hasFeatures %7C%7C
has
|
827171cf2860843beaec68d5995608889d8b784e
|
Update menuController.js
|
js/menuController.js
|
js/menuController.js
|
var app = angular.module("ScarmaGames", []);
app.controller("menuController", ['$scope', function($scope) {
var linebreak="\n"
$scope.items = [{
label: "Warp bird",
link: "Warp bird",
desc : "A Bird Can Destroy"+linebreak+
"You are a cute little bird who can't fly. But you can collect bombs and hammers."+linebreak+
"Enter The Warp Zone!"+linebreak+
"The Warp Zone is useful for rest or trade with merchants."+linebreak+
"Infinite randomly generated levels!"+linebreak+
"Levels become more and more difficult. How far can you go without dying?"+linebreak+
"Play directly from your browser from any device!"+linebreak+
"You can play it using any browser with HTML5 support (Chrome recommended)."+linebreak+
"Now with online leaderboard!"+linebreak+
"Choose your username and password and when you die your score is automatically submitted online!"+linebreak+
"In-Game Controls"+linebreak+
"A / rotate left = Move left"+linebreak+
"D / rotate right = Move right"+linebreak+
"W / slide up = Jump"+linebreak+
"ESC = Restart level"+linebreak+
"Click / tap on a brick = Brick smash"+linebreak+
"Double click / tap = Drop a bomb",
img : "WarpBirdGif.gif"
}, {
label: "Star In Black",
link: "Star In Black",
desc : "2 stars controlled by one player."+linebreak+
"20+ awesome levels."+linebreak+
"2D Platformer."+linebreak+
"2 hard to complete."
,
img : "starinblack.png"
},{
label: "Rob - The Talking Robot",
link: "Rob",
desc : "Rob is a smart robot who can do different things such as:"+linebreak+
" - Read a text in many languages (tts)"+linebreak+
" - Repeat what you say"+linebreak+
" - Move along the screen"+linebreak+
" - Change colour"+linebreak+
" - Change sex"+linebreak+
" - Speak louder" ,
img : "rob.png"
},{
label: "Chat & Shoot",
link: "Chat & Shoot",
desc : "A simple online multiplayer game."+linebreak+
"Chat with your friends while shooting to evil Monsters."+linebreak+
"Have fun in endless matches with a forever looping amazing soundtrack."+linebreak+linebreak+
"In-Game Controls"+linebreak+
"Click: Shoot."+linebreak+
"WASD or Arrows: Move"+linebreak
,
img : "chat&shoot.png"
},{
label: "The Tutorial To Play This Game",
link: "The Tutorial To Play This Game",
desc : "What happens if the tutorial becomes the game?"+linebreak+
"The objective of the tutorial is to play this game."+linebreak+
"The game is quite a short game and is a little idea made concrete."+linebreak+
"Game made in less than 10 hours from scratch using Construct 2, Audacity and Photofiltre."+linebreak+
"Ending music generated with This Exquisite Music Engine."+linebreak+linebreak+linebreak+
"HINT: Words are meaningful."+linebreak,
img: "thetutorialtoplaythisgame.gif"
},{
label: "Webcam Effects",
link: "Webcam Effects",
desc : "A game about using a webcam",
img : "webcameffects.png"
}
];
}]);
|
JavaScript
| 0.000001 |
@@ -2854,34 +2854,79 @@
: %22A
- game about using a webcam
+dd many effects to your webcam and take picture of your beautiful face.
%22,%0A%09
|
42356c3836eb3dff8527921510f36a923002c0fc
|
add init handler for server call
|
src/aura/BDI_ManageAdvancedMapping/BDI_ManageAdvancedMappingController.js
|
src/aura/BDI_ManageAdvancedMapping/BDI_ManageAdvancedMappingController.js
|
({
handleDeploymentNotification: function (component, event) {
let deploymentId = event.getParam('deploymentId');
component.find("platformEventListener").registerDeploymentId(deploymentId);
}
})
|
JavaScript
| 0 |
@@ -1,11 +1,107 @@
(%7B%0A
+ doInit : function(component, event, helper) %7B%0A helper.isSysAdmin(component);%0A %7D,%0A%0A
hand
@@ -134,17 +134,16 @@
function
-
(compone
|
6026f085afd58cbd7e0d8e07cff0010fb7e254b3
|
Fix #178
|
src/commands/util/eval.js
|
src/commands/util/eval.js
|
const util = require('util');
const discord = require('discord.js');
const tags = require('common-tags');
const escapeRegex = require('escape-string-regexp');
const Command = require('../base');
const nl = '!!NL!!';
const nlPattern = new RegExp(nl, 'g');
module.exports = class EvalCommand extends Command {
constructor(client) {
super(client, {
name: 'eval',
group: 'util',
memberName: 'eval',
description: 'Executes JavaScript code.',
details: 'Only the bot owner(s) may use this command.',
ownerOnly: true,
args: [
{
key: 'script',
prompt: 'What code would you like to evaluate?',
type: 'string'
}
]
});
this.lastResult = null;
}
run(msg, args) {
// Make a bunch of helpers
/* eslint-disable no-unused-vars */
const message = msg;
const client = msg.client;
const objects = client.registry.evalObjects;
const lastResult = this.lastResult;
const doReply = val => {
if(val instanceof Error) {
msg.reply(`Callback error: \`${val}\``);
} else {
const result = this.makeResultMessages(val, process.hrtime(this.hrStart));
if(Array.isArray(result)) {
for(const item of result) msg.reply(item);
} else {
msg.reply(result);
}
}
};
/* eslint-enable no-unused-vars */
// Run the code and measure its execution time
let hrDiff;
try {
const hrStart = process.hrtime();
this.lastResult = eval(args.script);
hrDiff = process.hrtime(hrStart);
} catch(err) {
return msg.reply(`Error while evaluating: \`${err}\``);
}
// Prepare for callback time and respond
this.hrStart = process.hrtime();
return msg.reply(this.makeResultMessages(this.lastResult, hrDiff, args.script));
}
makeResultMessages(result, hrDiff, input = null) {
const inspected = util.inspect(result, { depth: 0 })
.replace(nlPattern, '\n')
.replace(this.sensitivePattern, '--snip--');
const split = inspected.split('\n');
const last = inspected.length - 1;
const prependPart = inspected[0] !== '{' && inspected[0] !== '[' && inspected[0] !== "'" ? split[0] : inspected[0];
const appendPart = inspected[last] !== '}' && inspected[last] !== ']' && inspected[last] !== "'" ?
split[split.length - 1] :
inspected[last];
const prepend = `\`\`\`javascript\n${prependPart}\n`;
const append = `\n${appendPart}\n\`\`\``;
if(input) {
return discord.splitMessage(tags.stripIndents`
*Executed in ${hrDiff[0] > 0 ? `${hrDiff[0]}s ` : ''}${hrDiff[1] / 1000000}ms.*
\`\`\`javascript
${inspected}
\`\`\`
`, 1900, '\n', prepend, append);
} else {
return discord.splitMessage(tags.stripIndents`
*Callback executed after ${hrDiff[0] > 0 ? `${hrDiff[0]}s ` : ''}${hrDiff[1] / 1000000}ms.*
\`\`\`javascript
${inspected}
\`\`\`
`, 1900, '\n', prepend, append);
}
}
get sensitivePattern() {
if(!this._sensitivePattern) {
const client = this.client;
let pattern = '';
if(client.token) pattern += escapeRegex(client.token);
Object.defineProperty(this, '_sensitivePattern', { value: new RegExp(pattern, 'gi') });
}
return this._sensitivePattern;
}
};
|
JavaScript
| 0 |
@@ -2530,34 +2530,41 @@
%60%5C%60%5C%60%0A%09%09%09%60,
-1900, '%5Cn'
+%7B maxLength: 1900
, prepend, a
@@ -2564,24 +2564,26 @@
pend, append
+ %7D
);%0A%09%09%7D else
@@ -2789,18 +2789,25 @@
%09%60,
-1900, '%5Cn'
+%7B maxLength: 1900
, pr
@@ -2819,16 +2819,18 @@
, append
+ %7D
);%0A%09%09%7D%0A%09
|
86993504b4729e5b1de039f58443f947e38e64b6
|
Simplify try/catch
|
src/common/makeRequest.js
|
src/common/makeRequest.js
|
'use strict'
const request = require('request')
const baseURL = 'https://data.police.uk/api'
module.exports = (path) => {
return new Promise((resolve, reject) => {
request(`${baseURL}${path}`, (error, response, body) => {
if (error) { return reject(error) }
if (response.statusCode !== 200) { return reject({message: `Non-200 status code received: ${response.statusCode}`}) }
let data
try {
data = JSON.parse(body)
} catch (e) {
return reject('Invalid JSON')
}
return resolve(data)
})
})
}
|
JavaScript
| 0.003821 |
@@ -400,44 +400,37 @@
-let data%0A try %7B%0A data =
+try %7B%0A return resolve(
JSON
@@ -441,16 +441,17 @@
se(body)
+)
%0A %7D
@@ -505,16 +505,16 @@
N')%0A
+
%7D%0A
@@ -513,35 +513,8 @@
%7D%0A
- return resolve(data)%0A
|
8d8e67fd86cab573f4374a80e699495fc3695ab1
|
remove length because it was returned as undefined
|
bitcoin/js/btc.js
|
bitcoin/js/btc.js
|
$(document).ready(function() {
var bitcoinPrice = ("https://blockchain.info/q/24hrprice");
$.getJSON(bitcoinPrice, function(cost) {
console.info('1 bitcoin = $', cost);
$(".bitcoin-price").append("<span>" + cost + "</span>");
var slushStats = ("https://mining.bitcoin.cz/stats/json/947244-fb33810230dadb19c00f1e13068cd5d6");
$.getJSON(slushStats, function(btcstats) {
console.info(btcstats.length);
for (var i = 0; i < btcstats.length; i++) {
console.info(btcstats);
console.info(btcstats.blocks);
console.info(btcstats.blocks[i].confirmations);
console.info(btcstats.blocks[i].reward);
}
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var h = new Date();
var day = h.getDate();
var year = h.getFullYear();
var hours = h.getHours();
var minutes = h.getMinutes();
var seconds = h.getSeconds();
var milliSeconds = h.getMilliseconds();
$(".btc-day").append("<span>" + monthNames[h.getMonth()] + " " + day + " " + year + " @ " + hours + ":" + minutes + ":" + seconds + ":" + milliSeconds + " </span>");
console.info("%cTimestamp: " + monthNames[h.getMonth()] + " " + day + " " + year + " @ " + hours + ":" + minutes + ":" + seconds + ":" + milliSeconds, "background-color:#00fa12;");
});
});
});
|
JavaScript
| 0.000307 |
@@ -442,23 +442,16 @@
btcstats
-.length
);%0A
@@ -487,15 +487,8 @@
tats
-.length
; i+
|
607b0772e623b5d6711a2701854c1fe0f25d0759
|
remove c r
|
bitcoin/js/btc.js
|
bitcoin/js/btc.js
|
$(document).ready(function() {
var bitcoinPrice = ("https://blockchain.info/q/24hrprice");
$.getJSON(bitcoinPrice, function(cost) {
console.info('1 bitcoin = $', cost);
$(".bitcoin-price").append("<span>" + cost + "</span>");
var slushStats = ("https://mining.bitcoin.cz/stats/json/947244-fb33810230dadb19c00f1e13068cd5d6");
$.getJSON(slushStats, function(btcstats) {
console.info(btcstats.confirmed_reward);
console.info(btcstats.blocks);
console.info(btcstats.blocks[391222].confirmations);
console.info(btcstats.blocks[391222].reward);
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var h = new Date();
var day = h.getDate();
var year = h.getFullYear();
var hours = h.getHours();
var minutes = h.getMinutes();
var seconds = h.getSeconds();
var milliSeconds = h.getMilliseconds();
$(".btc-day").append("<span>" + monthNames[h.getMonth()] + " " + day + " " + year + " @ " + hours + ":" + minutes + ":" + seconds + ":" + milliSeconds + " </span>");
console.info("%cTimestamp: " + monthNames[h.getMonth()] + " " + day + " " + year + " @ " + hours + ":" + minutes + ":" + seconds + ":" + milliSeconds, "background-color:#00fa12;");
});
});
});
|
JavaScript
| 0.999724 |
@@ -446,25 +446,8 @@
tats
-.confirmed_reward
);%0A
|
66ab6e4230d864fac6fadc07a98fc9701b5e20e0
|
add spinner to html5 playback
|
src/plugins/html5_video_playback/index.js
|
src/plugins/html5_video_playback/index.js
|
// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
var PlaybackPlugin = require('../../base/playback_plugin');
var Styler = require('../../base/styler');
var HTML5VideoPlaybackPlugin = PlaybackPlugin.extend({
pluginName: 'html5_video_playback',
attributes: {
'data-html5-video': ''
},
events: {
'timeupdate': 'timeUpdated',
'ended': 'ended'
},
tagName: 'video',
initialize: function(options) {
this.firstPlay = true;
this.el.src = options.src;
this.container.settings = ['play', 'pause', 'seekbar', 'fullscreen', 'volume'];
this.listenTo(this.container, 'container:play', this.play);
this.listenTo(this.container, 'container:pause', this.pause);
this.listenTo(this.container, 'container:seek', this.seek);
//this.listenTo(this.container, 'container:fullscreen', this.fullscreen);
this.listenTo(this.container, 'container:volume', this.volume);
this.listenTo(this.container, 'container:stop', this.stop);
},
play: function() {
if(this.firstPlay) {
this.render();
this.$el.show();
this.firstPlay = false;
}
this.el.play();
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
this.firstPlay = true;
this.$el.hide();
},
fullscreen: function() {
//this is not right, the player goes fullscreen, not the playback.
this.el.webkitRequestFullscreen();
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger('container:timeupdate', 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
var time = (100 / this.el.duration) * this.el.currentTime;
this.container.timeUpdated(time);
},
render: function() {
var style = Styler.getStyleFor(this.pluginName);
this.container.$el.append(style);
this.container.$el.append(this.el);
return this;
},
});
module.exports = HTML5VideoPlaybackPlugin;
|
JavaScript
| 0 |
@@ -453,16 +453,44 @@
dated',%0A
+ 'loadeddata': 'loaded',%0A
'end
@@ -666,16 +666,24 @@
'pause',
+ 'stop',
'seekba
@@ -1137,24 +1137,56 @@
unction() %7B%0A
+ this.container.buffering();%0A
if(this.
@@ -1303,16 +1303,77 @@
);%0A %7D,%0A
+ loaded: function() %7B%0A this.container.bufferfull();%0A %7D,%0A
pause:
|
b4e4ed39953a1e8e3b490c5ff33ae666e84640bd
|
Move past conference toggler
|
src/components/App/App.js
|
src/components/App/App.js
|
import React, {Component} from 'react';
import {format, isPast} from 'date-fns';
import {sortByDate} from './utils';
import styles from './App.scss';
import Footer from '../Footer';
import Link from '../Link';
import Heading from '../Heading';
import Icon from '../Icon';
import ConferenceList from '../ConferenceList';
import ConferenceFilter from '../ConferenceFilter';
const BASE_URL = 'https://raw.githubusercontent.com/nimzco/confs.tech/master/conferences';
const CURRENT_YEAR = (new Date()).getFullYear().toString();
export default class App extends Component {
state = {
filters: {
year: '2017',
type: 'javascript',
},
showPast: false,
loading: true,
conferences: [],
sortDateDirection: 'asc',
};
componentDidMount() {
this.loadConference();
}
loadConference = () => {
const {filters} = this.state;
this.setState({loading: true});
fetch(getConferenceLink(filters))
.then((result) => result.json())
// eslint-disable-next-line promise/always-return
.then((conferences) => {
this.setState({
loading: false,
conferences: sortByDate(conferences, 'asc'),
});
})
.catch((error) => {
console.warn(error); // eslint-disable-line no-console
});
};
handleYearChange = (year) => {
const {filters} = this.state;
this.setState(
{
filters: {...filters, year},
},
this.loadConference
);
};
handleTypeChange = (type) => {
const {filters} = this.state;
this.setState(
{
filters: {...filters, type},
},
this.loadConference
);
};
togglePast = () => {
const {showPast} = this.state;
this.setState({showPast: !showPast});
};
pastConferenceToggler = () => {
const {showPast, filters: {year}} = this.state;
if (CURRENT_YEAR !== year) {
return null;
}
return (
<p>
<Link onClick={this.togglePast}>
{showPast ? 'Hide past conferences' : 'Show past conferences'}
</Link>
</p>
);
};
sortByDate = (direction) => {
const {conferences} = this.state;
this.setState({
conferences: sortByDate(conferences, direction),
sortDateDirection: direction,
});
};
filterConferences = (conferences) => {
const {showPast} = this.state;
if (showPast) {
return conferences;
}
return conferences.filter((conference) => {
return !isPast(format(conference.startDate));
});
};
render() {
const {
sortDateDirection,
loading,
conferences,
filters: {year, type},
} = this.state;
return (
<div className={styles.App}>
<div>
<div>
<Heading element="h1">Find your next {TYPES[type]} conference</Heading>
</div>
<div>
{this.pastConferenceToggler()}
<ConferenceFilter
sortDateDirection={sortDateDirection}
sortByDate={this.sortByDate}
year={year}
type={type}
onYearChange={this.handleYearChange}
onTypeChange={this.handleTypeChange}
/>
</div>
<div>
<Link
url="https://github.com/nimzco/the-conference-list/issues/new"
external
>
Add a conference
</Link>
</div>
<div>
{loading
? Loader()
: <ConferenceList
sortDateDirection={sortDateDirection}
conferences={this.filterConferences(conferences)}
/>
}
</div>
<Footer />
</div>
</div>
);
}
}
function getConferenceLink(state) {
const {type, year} = state;
return `${BASE_URL}/${year}/${type.toLocaleLowerCase()}.json`;
}
function Loader() {
return (
<div className={styles.Loader}>
<Icon source="loading" size={64} />
</div>
);
}
|
JavaScript
| 0 |
@@ -2852,51 +2852,8 @@
iv%3E%0A
- %7Bthis.pastConferenceToggler()%7D%0A
@@ -3354,24 +3354,67 @@
%3C/Link%3E%0A
+ %7Bthis.pastConferenceToggler()%7D%0A
%3C/
|
5cf04bb912fc64d119a5c0c2693e9e2fa0823e4f
|
Implement scalar/vector multiply and divide
|
src/geom/Vector2.js
|
src/geom/Vector2.js
|
export default class Vector2 {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
set(x, y) {
this.x = x;
this.y = y;
return this;
}
add(vec2) {
this.x = vec2.x;
this.y = vec2.y;
return this;
}
subtract(vec2) {
this.x -= vec2.x;
this.y -= vec2.y;
return this;
}
multiply(vec2) {
this.x *= vec2.x;
this.y *= vec2.y;
return this;
}
divide(vec2) {
this.x /= vec2.x;
this.y /= vec2.y;
return this;
}
angle(vec2) {
return Math.atan2(vec2.y - this.y, vec2.x - this.x);
}
distance(vec2) {
return Math.sqrt(Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2));
}
distanceSq(vec2) {
return Math.pow(vec2.x - this.x, 2) + Math.pow(vec2.y - this.y, 2);
}
clone() {
return new Vector2(this.x, this.y);
}
}
|
JavaScript
| 0.000023 |
@@ -395,16 +395,22 @@
multiply
+Vector
(vec2) %7B
@@ -498,73 +498,295 @@
-divide(vec2) %7B%0A this.x /= vec2.x;%0A this.y /= vec2.y
+multiplyScalar(scalar) %7B%0A this.x *= scalar;%0A this.y *= scalar;%0A return this;%0A %7D%0A%0A divideVector(vec2) %7B%0A this.x /= vec2.x;%0A this.y /= vec2.y;%0A return this;%0A %7D%0A%0A divideScalar(scalar) %7B%0A this.x /= scalar;%0A this.y /= scalar
;%0A
|
2c067908d8fae5425e2568c43f0501021caf172b
|
Enhance nav component and introduce prefix prop
|
src/components/Nav/Nav.js
|
src/components/Nav/Nav.js
|
import React from 'react';
import classnames from 'classnames';
import { GridContainer, GridRow, GridCol } from '../Grid';
const Nav = props => (
<div
className={classnames('ui-nav', {
'ui-nav-fixed': props.fixed,
'ui-nav-inverse': props.inverse,
})}
>
<GridContainer fluid>
<GridRow>
<GridCol>
<div className={classnames('ui-nav-navitems')}>
{props.children}
</div>
</GridCol>
</GridRow>
</GridContainer>
</div>
);
Nav.propTypes = {
fixed: React.PropTypes.bool.isRequired,
inverse: React.PropTypes.bool.isRequired,
children: React.PropTypes.node,
};
Nav.defaultProps = {
fixed: false,
inverse: false,
};
export default Nav;
|
JavaScript
| 0 |
@@ -61,101 +61,69 @@
s';%0A
-import %7B GridContainer, GridRow, GridCol %7D from '../Grid';%0A%0Aconst Nav = props =%3E (%0A %3Cdiv%0A
+%0Afunction Nav(%7B inverse, children, fixed, prefix %7D) %7B%0A const
cla
@@ -120,34 +120,35 @@
const className
-=%7B
+ =
classnames('ui-n
@@ -154,26 +154,24 @@
nav', %7B%0A
-
'ui-nav-fixe
@@ -178,23 +178,15 @@
d':
-props.
fixed,%0A
-
@@ -203,22 +203,16 @@
verse':
-props.
inverse,
@@ -218,82 +218,120 @@
,%0A
- %7D)%7D%0A %3E%0A %3CGridContainer fluid%3E%0A %3CGridRow%3E%0A %3CGridCol%3E%0A
+%7D);%0A%0A return (%0A %3Cdiv className=%7BclassName%7D%3E%0A %7Bprefix && %3Cdiv className=%22ui-nav-prefix%22%3E%7Bprefix%7D%3C/div%3E%7D%0A
@@ -392,19 +392,9 @@
- %7Bprops.
+%7B
chil
@@ -399,20 +399,16 @@
ildren%7D%0A
-
%3C/
@@ -420,72 +420,21 @@
- %3C/GridCol%3E%0A %3C/GridRow%3E%0A %3C/GridContainer%3E%0A %3C/div%3E%0A);
+%3C/div%3E%0A );%0A%7D
%0A%0ANa
@@ -569,16 +569,48 @@
s.node,%0A
+ prefix: React.PropTypes.node,%0A
%7D;%0A%0A%0ANav
@@ -661,16 +661,50 @@
false,%0A
+ prefix: null,%0A children: null,%0A
%7D;%0A%0Aexpo
|
37e4cae3abcfd6a2938c718acad6d3c21885cc53
|
Remove used parts.
|
src/components/Top/Top.js
|
src/components/Top/Top.js
|
// @flow weak
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import { blueGrey } from 'material-ui/colors';
import {WalletDialog} from './WalletDialog';
import {Title} from './Title';
import {Wallet} from './Wallet';
import './Top.css';
const styles = {
root: {
width: '100%'
},
flex: {
flex: 1
},
};
class Top extends Component {
state = {
open: false,
};
handleRequestClose = () => {
this.setState({ open: false });
};
render () {
const classes = this.props.classes;
const account = this.props.account &&
<p className="Top-info">{this.props.account}</p>;
const balance = this.props.balance &&
<p className="Top-info">Balance: {this.props.balance}</p>;
const privateKey = this.props.privateKey &&
<p className="Top-info">PrivateKey: {this.props.privateKey}</p>;
return (
<div className={classes.root}>
<AppBar position="static" style={{ backgroundColor: blueGrey[900] }}>
<Toolbar>
<Title className={classes.flex} />
<Wallet
privateKey={this.props.privateKey}
onClick={() => this.setState({ open: true })} />
<WalletDialog
open={this.state.open}
{...this.props}
handleRequestClose={this.handleRequestClose}
/>
</Toolbar>
</AppBar>
</div>
);
}
}
Top.propTypes = {
classes: PropTypes.object,
};
export default withStyles(styles)(Top);
|
JavaScript
| 0 |
@@ -673,335 +673,12 @@
es;%0A
-%0A
-const account = this.props.account && %0A %3Cp className=%22Top-info%22%3E%7Bthis.props.account%7D%3C/p%3E;%0A%0A const balance = this.props.balance && %0A %3Cp className=%22Top-info%22%3EBalance: %7Bthis.props.balance%7D%3C/p%3E;%0A%0A const privateKey = this.props.privateKey &&%0A %3Cp className=%22Top-info%22%3EPrivateKey: %7Bthis.props.privateKey%7D%3C/p%3E;%0A
%0A
|
bb576b21100eaafd134712a2b80084ff39e6589b
|
update the carousel
|
src/components/TopNews.js
|
src/components/TopNews.js
|
import React, { Component, PropTypes } from 'react'
import Slider from 'react-slick'
import { ts2yyyymmdd } from '../lib/date-transformer'
if (process.env.BROWSER) {
require("./TopNews.css");
}
export default class TopNews extends Component {
constructor(props, context) {
super(props, context)
}
componentDidMount() {
// this.handleResize()
// window.addEventListener('resize', this.handleResize);
}
render() {
const { topnews } = this.props
let settings = {
dots: true,
infinite: true,
speed: 1500,
autoplay: false,
autoplaySpeed: 4500,
arrows: false,
slidesToShow: 1,
slidesToScroll: 1,
lazyLoad: false,
useCSS: true
};
return Array.isArray(topnews) ? (
<Slider {...settings}>
{topnews.map((a) => {
const pubDate = ts2yyyymmdd(a.lastPublish * 1000, '.');
let tags = a.tags
let catDisplay = "專題"
for (let i = 0; i < tags.length; i++) {
if (tags[i].substring(0,4) == 'cat:') {
catDisplay = tags[i].substring(4)
break
}
}
return (
<a
key={a.id}
href={a.storyLink || "https://www.twreporter.org/a/" + a.slug}
className="topnewsimage-wrap"
style={{
backgroundImage: 'url(' + a.previewImage + ')',
}}
>
<div className="topnews_categorycontainer">
<div className="topnews_category">{catDisplay.substring(0,1)}</div>
<div className="topnews_category">{catDisplay.substring(2,1)}</div>
</div>
<div className="carousel-item">
<div className="carousel-itemtitle">{a.title}</div>
<div className="carousel-excerpt">{a.excerpt}</div>
<div className="carousel-published">
{pubDate}
</div>
</div>
</a>
);
})}
</Slider>
) : null;
}
}
export { TopNews };
|
JavaScript
| 0 |
@@ -617,20 +617,19 @@
toplay:
-fals
+tru
e,%0A
@@ -676,20 +676,19 @@
arrows:
-fals
+tru
e,%0A
|
e1f76e4b6785616889724dcb877de53bd43c4537
|
Remove id generation from constructor
|
src/components/tooltip.js
|
src/components/tooltip.js
|
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
export default class Tooltip extends React.Component {
static propTypes = {
children: PropTypes.any.isRequired,
content: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
styles: PropTypes.object,
}
styles = {
wrapper: {
position: 'relative',
zIndex: '98',
color: '#555',
cursor: 'help',
},
tooltip: {
position: 'absolute',
display: 'inline-block',
zIndex: '99',
bottom: '100%',
left: '50%',
WebkitTransform: 'translateX(-50%)',
msTransform: 'translateX(-50%)',
OTransform: 'translateX(-50%)',
transform: 'translateX(-50%)',
marginBottom: '10px',
padding: '5px',
width: '100%',
background: '#000',
},
content: {
background: '#000',
padding: '.3em 1em',
color: '#fff',
whiteSpace: 'normal',
overflow: 'auto',
},
arrow: {
borderLeft: 'solid transparent 5px',
borderRight: 'solid transparent 5px',
borderTop: 'solid #000 5px',
bottom: '-5px',
height: '0',
left: '50%',
marginLeft: '-5px',
position: 'absolute',
width: '0',
},
gap: {
bottom: '-20px',
display: 'block',
height: '20px',
left: '0',
position: 'absolute',
width: '100%',
},
}
constructor(props) {
super(props);
this.state = {
id: Math.random().toString(36),
visible: false,
};
if (props.styles) this.mergeStyles(props.styles);
}
mergeStyles = (userStyles) => {
Object.keys(this.styles).forEach((name) => {
Object.assign(this.styles[name], userStyles[name]);
});
}
show = () => this.setVisibility(true);
hide = () => this.setVisibility(false);
setVisibility = (visible) => {
this.setState(Object.assign({}, this.state, {
visible,
}));
}
handleTouch = () => {
this.show();
this.assignOutsideTouchHandler();
}
assignOutsideTouchHandler = () => {
const handler = (e) => {
let currentNode = e.target;
const componentNode = ReactDOM.findDOMNode(this.refs.instance);
while (currentNode.parentNode) {
if (currentNode === componentNode) return;
currentNode = currentNode.parentNode;
}
if (currentNode !== document) return;
this.hide();
document.removeEventListener('click', handler);
}
document.addEventListener('click', handler);
}
render() {
const {props, state, styles, show, hide, handleTouch} = this;
return (
<div
onMouseEnter={show}
onMouseLeave={hide}
onTouchStart={handleTouch}
style={styles.wrapper}>
{props.children}
{
state.visible &&
<div style={styles.tooltip}>
<div style={styles.content}>{props.content}</div>
<div style={styles.arrow}> </div>
<div style={styles.gap}> </div>
</div>
}
</div>
)
}
}
|
JavaScript
| 0.000001 |
@@ -1477,46 +1477,8 @@
= %7B%0A
- id: Math.random().toString(36),%0A
|
a22be7a50ed444e792f9897c759a1d10b106359c
|
change getById to getByPublicId. controller function now calls service method and uses $rs.$apply when assigning returned data to local variable
|
app/angular/controllers/games_controller.js
|
app/angular/controllers/games_controller.js
|
'use strict';
module.exports = function(app) {
app.controller('GamesController', ['$rootScope', '$scope', '$http', '$location', '$route', '$routeParams', 'AuthService', 'UserService', 'GameService', function($rs, $scope, $http, $location, $route, $routeParams, AuthService, UserService, GameService) {
AuthService.checkSessionExists();
this.publicId = $routeParams.publicId;
this.baseUrl = $rs.baseUrl;
this.user = $rs.user;
this.editing = false;
this.gameData = $rs.gameData;
this.game = {
players: [],
};
this.game.players[0] = $rs.user;
this.games = [];
this.publicIds = [];
this.friendsList = [];
$rs.user.gameIds.forEach((game) => {
this.publicIds.push(game.publicId);
});
this.toggleEdit = function(isEditing) {
isEditing === true ? this.editing = false : this.editing = true;
};
this.getAllByPublicId = function(publicIds) {
GameService.getAllByPublicId(publicIds)
.then((games) => {
this.games = games;
this.games.forEach((game) => {
game.totalGolfers = game.players.length;
game.players.forEach((player) => {
if ($rs.user.email === player.email) {
game.yourStrokes = player.strokes;
game.yourScore = game.yourStrokes + 72;
}
});
});
})
.catch(() => {
alert('error getting games');
});
};
this.getAllByPublicId(this.publicIds);
this.createGame = function(gameData) {
$http.post('/games/create', gameData)
.then((game) => {
let playersArray = game.data.players;
playersArray.forEach((player) => {
this.updatePlayer(player)
.then((playerData) => {
if (playerData.data.email === $rs.user.email) {
$rs.user = playerData.data;
window.sessionStorage.setItem('currentUser', JSON.stringify($rs.user));
}
$route.reload();
})
.catch((err) => {
alert('error creating game');
});
});
})
.catch((err) => {
alert('error creating game');
});
};
this.getById = GameService.getById;
this.getFriendsList = function() {
$http.get('/friends/list')
.then((friendsList) => {
this.friendsList = friendsList.data;
})
.catch((err) => {
alert('error getting friends list');
});
};
this.addPlayer = function(user) {
if (user === undefined || user === null) return;
this.game.players.push(user);
this.friendsList = this.friendsList.filter((friend) => {
return friend._id !== user._id;
});
};
this.removePlayer = function(user) {
let playersArray = this.game.players;
let userIndex = playersArray.indexOf(user);
this.friendsList.push(playersArray[userIndex]);
playersArray.splice(userIndex, 1);
};
this.updatePlayer = function(player) {
return new Promise((resolve, reject) => {
let playerData = {
emailOrUsername: player.email,
};
$http.post('/users', playerData)
.then((user) => {
UserService.calcHandicap(user.data)
.then((handicapData) => {
UserService.updateUser(playerData, handicapData)
.then((user) => {
resolve(user);
})
.catch(reject);
})
.catch(reject);
})
.catch(reject);
});
};
}]);
};
|
JavaScript
| 0.000001 |
@@ -2282,32 +2282,291 @@
etBy
-Id = GameService.getById
+PublicId = function(publicId) %7B%0A GameService.getByPublicId(publicId)%0A .then((gameData) =%3E %7B%0A $rs.$apply(() =%3E %7B%0A this.gameData = gameData;%0A %7D);%0A %7D)%0A .catch((err) =%3E %7B%0A alert('error getting game data');%0A %7D);%0A %7D
;%0A%0A
|
b73115eb9e47c4b18115b749014eabeb57c761c8
|
Remove duplicate HMR plugin invocation
|
src/config/webpack.dev.js
|
src/config/webpack.dev.js
|
import fs from 'fs';
import path from 'path';
import autoprefixer from 'autoprefixer';
import flexbugs from 'postcss-flexbugs-fixes';
import MiniCSSExtractPlugin from 'mini-css-extract-plugin';
import webpack from 'webpack';
import webpackMiddleware from 'koa-webpack';
import { GenerateSW } from 'workbox-webpack-plugin';
import hasConfig from '../shared/utils/hasConfig';
import logger from '../shared/utils/logger';
export default (app, options) => {
const hasRenderingConfig = hasConfig(options.appLocation, 'rendering');
let devConfig = {
mode: 'development',
resolve: {
alias: {
fervorAppRoutes: path.resolve(options.appLocation, 'src', 'urls.js'),
fervorConfigRendering: hasRenderingConfig ?
path.join(options.appLocation, 'src', 'config', 'rendering.js') :
path.join(__dirname, 'renderingConfig.js'),
},
},
entry: [
path.join(__dirname, '..', 'client', 'main.js'),
],
output: {
path: options.appLocation,
publicPath: '/build/',
filename: 'bundle.js',
sourceMapFilename: 'bundle.js.map',
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.json$/,
exclude: /node_modules/,
use: 'json-loader',
},
{
test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$|\.html$/,
loader: 'file-loader',
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 2,
localIdentName: '[name]__[local]___[hash:base64:5]',
},
},
{
loader: 'postcss-loader',
options: {
plugins: () => (
[autoprefixer(), flexbugs()]
),
},
},
{
loader: 'sass-loader',
options: {
outputStyle: 'compressed',
},
},
],
},
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
// eslint-disable-next-line global-require
options: require('./babelrcHelper').default(
false,
options.appLocation,
true,
['react-hot-loader/babel'],
),
},
],
exclude: [/node_modules/],
},
],
},
plugins: [
new MiniCSSExtractPlugin({
filename: 'bundle-[chunkhash:6].css',
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || true)),
'process.env': {
BROWSER: JSON.stringify(true),
HOST: JSON.stringify(process.env.HOST),
},
}),
new webpack.DllReferencePlugin({
context: path.join(__dirname, '..'),
// the next line requires a yarn build
// eslint-disable-next-line
manifest: require('../../lib/fervorVendors-manifest.json'),
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.NamedModulesPlugin(),
new GenerateSW({
runtimeCaching: [],
swDest: path.join(options.appLocation, 'build', 'sw.js'),
importWorkboxFrom: 'cdn',
}),
],
optimization: {
splitChunks: {
minChunks: 2,
},
},
};
const customConfigPath = path.join(options.appLocation, 'src', 'config', 'webpack');
if (fs.existsSync(`${customConfigPath}.js`)) {
// Server side only - this is fine
// eslint-disable-next-line import/no-dynamic-require, global-require
devConfig = require(customConfigPath).default(devConfig);
}
const devSetup = {
dev: {
publicPath: '/build/',
headers: { 'Content-Type': 'text/html; charset=utf-8' },
stats: { colors: true },
quiet: false,
noInfo: true,
},
hot: {
log: logger.info,
path: '/__webpack_hmr',
heartbeat: 10 * 1000,
},
config: devConfig,
};
const wpMiddleware = options.webpackMiddleware || webpackMiddleware;
app.use(wpMiddleware(devSetup));
};
|
JavaScript
| 0 |
@@ -3301,56 +3301,8 @@
(),%0A
- new webpack.HotModuleReplacementPlugin(),%0A
|
504aad6a7093d2bc8e92a64bb9733481858fd4a2
|
Update CoinChange_II.js
|
algorithms/CoinChange_II.js
|
algorithms/CoinChange_II.js
|
// Source : https://leetcode.com/problems/coin-change-2
// Author : Dean Shi
// Date : 2017-07-15
/***************************************************************************************
*
* You are given coins of different denominations and a total amount of money. Write a
* function to compute the number of combinations that make up that amount. You may
* assume that you have infinite number of each kind of coin.
*
* Note:
* You can assume that
*
* 0
* 1
* the number of coins is less than 500
* the answer is guaranteed to fit into signed 32-bit integer
*
* Example 1:
*
* Input: amount = 5, coins = [1, 2, 5]
* Output: 4
* Explanation: there are four ways to make up the amount:
* 5=5
* 5=2+2+1
* 5=2+1+1+1
* 5=1+1+1+1+1
*
* Example 2:
*
* Input: amount = 3, coins = [2]
* Output: 0
* Explanation: the amount of 3 cannot be made up just with coins of 2.
*
* Example 3:
*
* Input: amount = 10, coins = [10]
* Output: 1
*
***************************************************************************************/
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function(amount, coins) {
const dp = Array(amount + 1).fill(0)
dp[0] = 1
for (let i of coins) {
for (let j = i; j <= amount + 1; ++j) {
dp[j] += dp[j - i]
}
}
return dp[amount]
}
|
JavaScript
| 0 |
@@ -1228,16 +1228,20 @@
%5B0%5D = 1%0A
+
%0A for
@@ -1246,17 +1246,20 @@
or (let
-i
+coin
of coin
@@ -1284,16 +1284,19 @@
let
-j = i; j
+i = coin; i
%3C=
@@ -1305,17 +1305,13 @@
ount
- + 1
; ++
-j
+i
) %7B%0A
@@ -1329,17 +1329,17 @@
dp%5B
-j
+i
%5D += dp%5B
j -
@@ -1338,13 +1338,16 @@
dp%5B
-j - i
+i - coin
%5D%0A
@@ -1382,10 +1382,11 @@
amount%5D%0A
-
%7D
+;
%0A
|
2f0bbcaa07d27a25836b12e270597c4e36d8237d
|
make codacy happier
|
lib/hashauth.js
|
lib/hashauth.js
|
'use strict';
var crypto = require('crypto');
var hashauth = {
apisecret: ''
, storeapisecret: false
, apisecrethash: null
, authenticated: false
, initialized: false
};
hashauth.init = function init(client, $) {
if (hashauth.initialized) {
return hashauth;
}
hashauth.verifyAuthentication = function verifyAuthentication(next) {
hashauth.authenticated = false;
$.ajax({
method: 'GET'
, url: '/api/v1/verifyauth?t=' + Date.now() //cache buster
, headers: client.headers()
}).done(function verifysuccess (response) {
if (response.message === 'OK') {
hashauth.authenticated = true;
console.log('Authentication passed.');
next(true);
} else {
console.log('Authentication failed.');
hashauth.removeAuthentication();
next(false);
}
}).fail(function verifyfail ( ) {
console.log('Authentication failed.');
hashauth.removeAuthentication();
next(false);
});
};
hashauth.initAuthentication = function initAuthentication(next) {
hashauth.apisecrethash = $.localStorage.get('apisecrethash') || null;
hashauth.verifyAuthentication(function () {
$('#authentication_placeholder').html(hashauth.inlineCode());
if (next) { next( hashauth.isAuthenticated() ); }
});
return hashauth;
};
hashauth.removeAuthentication = function removeAuthentication(event) {
$.localStorage.remove('apisecrethash');
if (hashauth.authenticated) {
client.browserUtils.reload();
}
// clear eveything just in case
hashauth.apisecret = null;
hashauth.apisecrethash = null;
hashauth.authenticated = false;
if (event) {
event.preventDefault();
}
return false;
};
hashauth.requestAuthentication = function requestAuthentication(event) {
var translate = client.translate;
$( '#requestauthenticationdialog' ).dialog({
width: 500
, height: 240
, buttons: [
{
text: translate('Update')
, click: function() {
var dialog = this;
hashauth.processSecret($('#apisecret').val(), $('#storeapisecret').is(':checked'), function done (close) {
if (close) {
client.afterAuth(true);
$( dialog ).dialog( 'close' );
} else {
$('#apisecret').val('').focus();
}
});
}
}
]
, open: function open ( ) {
$('#requestauthenticationdialog').keypress(function pressed (e) {
if (e.keyCode === $.ui.keyCode.ENTER) {
$(this).parent().find('button.ui-button-text-only').trigger('click');
}
});
$('#apisecret').val('').focus();
}
});
if (event) {
event.preventDefault();
}
return false;
};
hashauth.processSecret = function processSecret(apisecret, storeapisecret, callback) {
var translate = client.translate;
hashauth.apisecret = apisecret;
hashauth.storeapisecret = storeapisecret;
if (hashauth.apisecret.length < 12) {
window.alert(translate('Too short API secret'));
if (callback) {
callback(false);
}
} else {
var shasum = crypto.createHash('sha1');
shasum.update(hashauth.apisecret);
hashauth.apisecrethash = shasum.digest('hex');
hashauth.verifyAuthentication( function(isok) {
if (isok) {
if (hashauth.storeapisecret) {
$.localStorage.set('apisecrethash',hashauth.apisecrethash);
}
$('#authentication_placeholder').html(hashauth.inlineCode());
hashauth.updateSocketAuth();
if (callback) {
callback(true);
}
} else {
alert(translate('Wrong API secret'));
if (callback) {
callback(false);
}
}
});
}
};
hashauth.inlineCode = function inlineCode() {
var translate = client.translate;
var status = null;
if (client.authorized) {
status = translate('Authorized by token') + ' <a href="/">(' + translate('view without token') + ')</a>' +
'<br/><span class="small">' + client.authorized.sub + ': ' + client.authorized.permissionGroups.join(', ') + '</span>'
} else if (hashauth.isAuthenticated()) {
console.info('status isAuthenticated', hashauth);
status = translate('Admin authorized') + ' <a href="#" onclick="Nightscout.client.hashauth.removeAuthentication(); return false;">(' + translate('Remove') + ')</a>'
} else {
status = translate('Not authorized') + ' <a href="#" onclick="Nightscout.client.hashauth.requestAuthentication(); return false;">(' + translate('Authenticate') + ')</a>'
}
var html =
'<div id="requestauthenticationdialog" style="display:none" title="'+translate('Device authentication')+'">'+
'<label for="apisecret">'+translate('Your API secret')+': </label>'+
'<input type="password" id="apisecret" size="20" />'+
'<br>'+
'<input type="checkbox" id="storeapisecret" /> <label for="storeapisecret">'+translate('Store hash on this computer (Use only on private computers)')+'</label>'+
'<div id="apisecrethash">'+
(hashauth.apisecrethash ? translate('Hash') + ' ' + hashauth.apisecrethash: '')+
'</div>'+
'</div>'+
'<div id="authorizationstatus">' + status + '</div>';
return html;
};
hashauth.updateSocketAuth = function updateSocketAuth() {
client.socket.emit(
'authorize'
, {
client: 'web'
, secret: client.authorized && client.authorized.token ? null : client.hashauth.hash()
, token: client.authorized && client.authorized.token
}
, function authCallback(data) {
console.log('Client rights: ',data);
if (!data.read && !client.authorized) {
hashauth.requestAuthentication();
}
}
);
};
hashauth.hash = function hash() {
return hashauth.apisecrethash;
};
hashauth.isAuthenticated = function isAuthenticated() {
return hashauth.authenticated;
};
hashauth.initialized = true;
return hashauth;
};
module.exports = hashauth;
|
JavaScript
| 0.000001 |
@@ -4299,16 +4299,17 @@
%3C/span%3E'
+;
%0A %7D e
@@ -4568,24 +4568,25 @@
') + ')%3C/a%3E'
+;
%0A %7D else
@@ -4762,16 +4762,17 @@
')%3C/a%3E'
+;
%0A %7D%0A%0A
|
3f0c073915fc1cae7c2d624f8c845e1a434111d7
|
add linkify for comments
|
app/assets/javascripts/components/stream.js
|
app/assets/javascripts/components/stream.js
|
APP.components.stream = (function() {
function init() {
initEntryCreateForm();
initCommentForm();
initLinkify();
$('.show-all-comments-link').on("click", function() {
$(this).parents(".post-comments").find(".comment-container").show();
$(this).hide();
});
}
function initEntryCreateForm() {
var $parent = $('.entryCreate').not('.js-initialized');
if($parent.find('.postTitle').exists()) {
$parent.find('.postMessage').autogrow();
$parent.addClass('js-initialized')
.find('.postTitle, .postMessage')
.on("focusin", function() {
$parent.addClass("is-focused");
})
.on("focusout", function() {
if(!$('.postTitle').val().length && !$('.postMessage').val().length ) {
$parent.removeClass("is-focused");
}
});
} else {
initSingleTextarea($parent);
}
}
function initLinkify() {
$('.stream .entryInitialContent .txt').linkify({ target: "_blank"});
$('.stream .post-comments .txt').linkify({ target: "_blank"});
}
function initCommentForm() {
$('.entryCommentForm').not('.js-initialized').each(function() {
var $parent = $(this);
initSingleTextarea($parent);
})
}
function initSingleTextarea($parent) {
$parent
.addClass('js-initialized')
.find('textarea')
.autogrow()
.on("focusin touch", function(){
(APP.utils.isLoggedIn()) ? $parent.addClass("is-focused") : injectFormBlocker($parent);
});
}
function injectFormBlocker($container) {
$('.stream .formBlocker').remove();
var $markup = $('<div class="formBlocker">' +
'<div class="wrp">' +
'<div>Du musst eingeloggt sein, um einen Kommentar zu verfassen.</div>' +
'<div><a href="/users/login">Zum Login</a> | <a href="/users/registrierung">Zur Registrierung</a></div>' +
'<span class="close"></span>' +
'</div>' +
'</div>');
$container.find('textarea').prop('disabled', true);
$container.find('textarea').blur();
$container.append($markup);
$markup.hide().fadeIn();
$markup.on('click', function(e) { e.stopPropagation(); });
$container.find('.close').on('click.hideblock', function(e) {
$markup.remove();
$container.find('textarea').prop('disabled', false);
});
}
return {
init : init,
initEntryCreateForm : initEntryCreateForm,
initCommentForm : initCommentForm,
initLinkify: initLinkify
}
})();
|
JavaScript
| 0 |
@@ -1228,24 +1228,90 @@
%22_blank%22%7D);%0A
+ $('.entryUserComment .txt').linkify(%7B target: %22_blank%22%7D);%0A
%7D%0A%0A f
|
5bb792af4ecb2bc11130491f5aae37cc55be3562
|
fix navigate
|
js/reducers/route.js
|
js/reducers/route.js
|
import { REHYDRATE } from 'redux-persist/constants';
import type { Action } from '../actions/types';
import { globalNav } from '../AppNavigator';
import { PUSH_NEW_ROUTE, POP_ROUTE, POP_TO_ROUTE, REPLACE_ROUTE, REPLACE_OR_PUSH_ROUTE } from '../actions/route';
export type State = {
routes: Array<string>
}
const initialState = {
routes: ['login'],
};
export default function (state:State = initialState, action:Action): State {
// console.log(state, "route state *()*(*&77");
if (action.type === PUSH_NEW_ROUTE) {
// console.log(action.route, "route");
globalNav.navigator.push({ id: action.route });
return {
routes: [...state.routes, action.route],
};
}
if (action.type === REPLACE_ROUTE) {
globalNav.navigator.replaceWithAnimation({ id: action.route });
const routes = state.routes;
routes.pop();
return {
routes: [...routes, action.route],
};
}
// For sidebar navigation
if (action.type === REPLACE_OR_PUSH_ROUTE) {
let routes = state.routes;
if (routes[routes.length - 1] === 'home') {
// If top route is home and user navigates to a route other than home, then push
if (action.route !== 'home') {
globalNav.navigator.push({ id: action.route });
} else { // If top route is home and user navigates to home, do nothing
routes = [];
}
} else if (action.route === 'home') {
globalNav.navigator.resetTo({ id: 'home' });
routes = [];
} else {
globalNav.navigator.replaceWithAnimation({ id: action.route });
routes.pop();
}
return {
routes: [...routes, action.route],
};
}
if (action.type === POP_ROUTE) {
globalNav.navigator.pop();
const routes = state.routes;
routes.pop();
return {
routes,
};
}
if (action.type === POP_TO_ROUTE) {
globalNav.navigator.popToRoute({ id: action.route });
const routes = state.routes;
while (routes.pop() !== action.route) {
// keep popping till you get to the route
}
return {
routes: [...routes, action.route],
};
}
if (action.type === REHYDRATE) {
const savedData = action.payload.route || state;
return {
...savedData,
};
}
return state;
}
|
JavaScript
| 0.000002 |
@@ -1506,37 +1506,24 @@
ator.replace
-WithAnimation
(%7B id: actio
|
4dd93e45a6a8c54d5aadbfb3cf0f42f11460d468
|
remove flow test
|
src/containers/App/App.js
|
src/containers/App/App.js
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Alert from 'react-bootstrap/lib/Alert';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { Notifs, InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from 'config';
import { asyncConnect } from 'redux-connect';
@asyncConnect([{
promise: ({ store: { dispatch, getState } }) => {
const promises = [];
if (!isAuthLoaded(getState())) {
promises.push(dispatch(loadAuth()));
}
if (!isInfoLoaded(getState())) {
promises.push(dispatch(loadInfo()));
}
return Promise.all(promises);
}
}])
@connect(
state => ({
notifs: state.notifs,
user: state.auth.user
}),
{ logout, pushState: push })
export default class App extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
router: PropTypes.object.isRequired,
user: PropTypes.object,
notifs: PropTypes.object.isRequired,
logout: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired
};
static defaultProps = {
user: null
};
static contextTypes = {
store: PropTypes.object.isRequired
};
componentWillReceiveProps(nextProps) {
if (!this.props.user && nextProps.user) {
// login
const redirect = this.props.router.location.query && this.props.router.location.query.redirect;
this.props.pushState(redirect || '/loginSuccess');
} else if (this.props.user && !nextProps.user) {
// logout
this.props.pushState('/');
}
}
handleLogout = event => {
event.preventDefault();
this.props.logout();
};
render() {
const { user, notifs, children } = this.props;
const styles = require('./App.scss');
const add = (a: number, b: number): number => a + b;
console.log(add(3, 4));
console.log(add(3, false));
return (
<div className={styles.app}>
<Helmet {...config.app.head} />
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<IndexLink to="/" activeStyle={{ color: '#33e0ff' }}>
<div className={styles.brand} />
<span>{config.app.title}</span>
</IndexLink>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav navbar>
{user && <LinkContainer to="/chatFeathers">
<NavItem>Chat with Feathers</NavItem>
</LinkContainer>}
<LinkContainer to="/chat">
<NavItem>Chat</NavItem>
</LinkContainer>
<LinkContainer to="/widgets">
<NavItem>Widgets</NavItem>
</LinkContainer>
<LinkContainer to="/survey">
<NavItem>Survey</NavItem>
</LinkContainer>
<LinkContainer to="/about">
<NavItem>About Us</NavItem>
</LinkContainer>
{!user && <LinkContainer to="/login">
<NavItem>Login</NavItem>
</LinkContainer>}
{!user && <LinkContainer to="/register">
<NavItem>Register</NavItem>
</LinkContainer>}
{user && <LinkContainer to="/logout">
<NavItem className="logout-link" onClick={this.handleLogout}>
Logout
</NavItem>
</LinkContainer>}
</Nav>
{user && <p className="navbar-text">
Logged in as <strong>{user.email}</strong>.
</p>}
<Nav navbar pullRight>
<NavItem
target="_blank" title="View on Github"
href="https://github.com/erikras/react-redux-universal-hot-example"
>
<i className="fa fa-github" />
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className={styles.appContent}>
{notifs.global && <div className="container">
<Notifs
className={styles.notifs}
namespace="global"
NotifComponent={props => <Alert bsStyle={props.kind}>{props.message}</Alert>}
/>
</div>}
{children}
</div>
<InfoBar />
<div className="well text-center">
Have questions? Ask for help{' '}
<a
href="https://github.com/erikras/react-redux-universal-hot-example/issues"
target="_blank" rel="noopener noreferrer"
>
on Github
</a>
{' '}or in the{' '}
<a
href="https://discord.gg/0ZcbPKXt5bZZb1Ko"
target="_blank" rel="noopener noreferrer"
>
#react-redux-universal
</a>
{' '}Discord channel.
</div>
</div>
);
}
}
|
JavaScript
| 0.000001 |
@@ -2162,126 +2162,8 @@
);%0A%0A
- const add = (a: number, b: number): number =%3E a + b;%0A console.log(add(3, 4));%0A console.log(add(3, false));%0A%0A
|
e824bccd285134ec51489cdb8a2b0c473c63fcc4
|
Remove bootstrap
|
app/assets/javascripts/puddy/application.js
|
app/assets/javascripts/puddy/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require_tree .
|
JavaScript
| 0.000002 |
@@ -619,38 +619,8 @@
ujs%0A
-//= require twitter/bootstrap%0A
//=
|
a75ff025cf31a7fd6b486408a12e192466135cab
|
Check for the articles to exist before deciding on the default tracked status filter to use
|
app/assets/javascripts/reducers/articles.js
|
app/assets/javascripts/reducers/articles.js
|
import _ from 'lodash';
import { sortByKey } from '../utils/model_utils';
import {
RECEIVE_ARTICLES,
SORT_ARTICLES,
SET_PROJECT_FILTER,
SET_NEWNESS_FILTER,
SET_TRACKED_STATUS_FILTER,
UPDATE_ARTICLE_TRACKED_STATUS
} from '../constants';
const initialState = {
articles: [],
limit: 500,
limitReached: false,
sort: {
key: null,
sortKey: null
},
wikis: [],
wikiFilter: null,
newnessFilter: null,
trackedStatusFilter: 'tracked',
loading: true,
newnessFilterEnabled: false,
trackedStatusFilterEnabled: false
};
const SORT_DESCENDING = {
character_sum: true,
references_count: true,
view_count: true
};
const isLimitReached = (revs, limit) => {
return revs.length < limit;
};
const mapWikis = (article) => {
return {
language: article.language,
project: article.project
};
};
const getTrackedStatusFilterEnabledStatus = _articles =>
_articles.some(a => a.tracked) && _articles.some(a => !a.tracked);
const getDefaultTrackedStatusFilter = _articles =>
(_articles[0].tracked ? 'tracked' : 'both');
export default function articles(state = initialState, action) {
switch (action.type) {
case RECEIVE_ARTICLES: {
const wikis = _.uniqWith(
_.map(action.data.course.articles, mapWikis),
_.isEqual
);
const _articles = action.data.course.articles;
const newnessFilterEnabled = _articles.some(a => a.new_article) && _articles.some(a => !a.new_article);
const trackedStatusFilterEnabled = getTrackedStatusFilterEnabledStatus(_articles);
let trackedStatusFilter = state.trackedStatusFilter;
if (!trackedStatusFilterEnabled) {
trackedStatusFilter = getDefaultTrackedStatusFilter(_articles);
}
return {
...state,
articles: _articles,
limit: action.limit,
limitReached: isLimitReached(action.data.course.articles, action.limit),
wikis,
wikiFilter: state.wikiFilter,
newnessFilter: state.newnessFilter,
trackedStatusFilter,
newnessFilterEnabled,
trackedStatusFilterEnabled,
loading: false
};
}
case SORT_ARTICLES: {
const sorted = sortByKey(
state.articles,
action.key,
state.sort.sortKey,
SORT_DESCENDING[action.key]
);
return {
...state,
articles: sorted.newModels,
sort: {
sortKey: sorted.newKey,
key: action.key
},
wikiFilter: state.wikiFilter,
wikis: state.wikis
};
}
case SET_PROJECT_FILTER: {
if (action.wiki.project === 'all') {
return { ...state, wikiFilter: null };
}
return { ...state, wikiFilter: action.wiki };
}
case SET_NEWNESS_FILTER: {
return { ...state, newnessFilter: action.newness };
}
case SET_TRACKED_STATUS_FILTER: {
return { ...state, trackedStatusFilter: action.trackedStatus };
}
case UPDATE_ARTICLE_TRACKED_STATUS: {
// Make sure the article's tracked status is reflected in the redux state
const updatedArticles = state.articles.map((a) => {
if (a.id === action.articleId) {
a.tracked = action.tracked;
}
return a;
});
let { trackedStatusFilter } = state;
const trackedStatusFilterEnabled = getTrackedStatusFilterEnabledStatus(updatedArticles);
if (!trackedStatusFilterEnabled) {
trackedStatusFilter = getDefaultTrackedStatusFilter(updatedArticles);
}
return { ...state, trackedStatusFilterEnabled, trackedStatusFilter, articles: updatedArticles };
}
default:
return state;
}
}
|
JavaScript
| 0 |
@@ -1012,16 +1012,33 @@
s =%3E%0A (
+(_articles%5B0%5D &&
_article
@@ -1049,16 +1049,17 @@
.tracked
+)
? 'trac
|
ed97d9628d7f884ecfba1e201e068f02ba4883f9
|
use on to be compatible
|
app/assets/javascripts/typus/application.js
|
app/assets/javascripts/typus/application.js
|
//= require typus/jquery-2.1.1.min
//= require jquery_ujs
//= require bootstrap
//= require typus/jquery.application
//= require typus/custom
$(".ajax-modal").live('click', function() {
var url = $(this).attr('url');
var modal_id = $(this).attr('data-controls-modal');
$("#" + modal_id + " .modal-body").load(url);
});
|
JavaScript
| 0 |
@@ -157,20 +157,18 @@
l%22).
-live('
+on(%22
click
-'
+%22
, fu
|
5b5fc8423876643dd6341734f11b74ece2bf05bc
|
Include the correct option name.
|
lib/reporters/coverage/html.js
|
lib/reporters/coverage/html.js
|
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick 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 util = require('util');
var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');
var templates = require('magic-templates');
var constants = require('./../../constants');
var coverage = require('./../../coverage');
var CoverageReporter = require('./base').CoverageReporter;
function HtmlReporter(tests, options) {
CoverageReporter.call(this, tests, options);
if (!options['directory']) {
throw new Error('Missing coverage-directory option');
}
this._coverage = {};
this._coverageDirectory = this._options['directory'];
this._assetsDirectory = path.join(__dirname, '../../../', 'assets');
templates.setTemplatesDir(this._assetsDirectory);
templates.setDebug(false);
}
HtmlReporter.prototype.handleTestFileComplete = function(filePath, coverageObj) {
var filename = filePath;
this._coverage[filename] = coverageObj;
};
HtmlReporter.prototype.handleTestsComplete = function(coverageObj) {
coverageObj = (!coverageObj) ? coverage.populateCoverage(null, this._coverage) : coverageObj;
this._writeCoverage(coverageObj);
};
HtmlReporter.prototype._writeCoverage = function(cov) {
var self = this;
/* Remove output directory */
rimraf(self._coverageDirectory, function(err) {
fs.mkdir(self._coverageDirectory, 0755, function() {
self._writeFile(cov);
self._writeSourceFiles(cov);
self._writeStaticFiles(self._coverageDirectory);
});
});
};
HtmlReporter.prototype._writeFile = function(cov) {
var self = this;
var template = new templates.Template('whiskey.magic');
var context = {
version: constants.VERSION,
coverage: cov.coverage,
cov: cov
};
template.load(function(err, template) {
if (err) {
// load/parse errors (invalid filename, bad template syntax)
console.log(err);
}
else {
template.render(context, function(err, output) {
if (err) {
// render errors (invalid filename in context variables, bad context variables)
console.log(err);
}
else {
fs.writeFile(path.join(self._coverageDirectory, 'index.html'),
output.join(''));
}
});
}
});
};
HtmlReporter.prototype._writeSourceFiles = function(cov) {
var self = this;
var template = new templates.Template('whiskey_source.magic');
template.load(function(err, template) {
if (err) {
// load/parse errors (invalid filename, bad template syntax)
console.log(err);
}
else {
for (var name in cov.files) {
var context = {
version: constants.VERSION,
name: name,
cov: cov.files[name],
markup: self._generateSourceMarkup(cov.files[name])
};
template.render(context, function(err, output) {
if (err) {
// render errors (invalid filename in context variables, bad context variables)
console.log(err);
}
else {
fs.writeFile(path.join(self._coverageDirectory,
cov.files[name].htmlName),
output.join(''));
}
});
}
}
});
};
HtmlReporter.prototype._generateSourceMarkup = function(cov) {
var rv = [], _class, data, source;
for (var i = 1, linesLen = (cov.source.length + 1); i < linesLen; i++) {
data = cov.lines[i.toString()];
_class = 'pln';
if (data !== null) {
if (parseInt(data, 10) > 0) {
_class = 'stm run';
}
else if (parseInt(data, 10) === 0) {
_class = 'stm mis';
}
}
source = cov.source[i-1];
source = source.replace(/\s/g, ' ');
rv.push({number: i, css: _class, source: source});
}
return rv;
};
HtmlReporter.prototype._writeStaticFiles = function(dest) {
this._copyAsset('style.css', dest);
this._copyAsset('coverage_html.js', dest);
this._copyAsset('jquery-1.4.3.min.js', dest);
this._copyAsset('jquery.tablesorter.min.js', dest);
this._copyAsset('jquery.isonscreen.js', dest);
this._copyAsset('jquery.hotkeys.js', dest);
this._copyAsset('keybd_closed.png', dest);
this._copyAsset('keybd_open.png', dest);
};
HtmlReporter.prototype._copyAsset = function(asset, dest) {
this._copyFile(path.join(this._assetsDirectory, asset),
path.join(dest, asset));
};
HtmlReporter.prototype._copyFile = function(src, dst) {
var oldFile = fs.createReadStream(src);
var newFile = fs.createWriteStream(dst);
newFile.once('open', function(fd) {
util.pump(oldFile, newFile);
});
};
exports.name = 'html';
exports.klass = HtmlReporter;
|
JavaScript
| 0.000074 |
@@ -1258,22 +1258,16 @@
rage-dir
-ectory
option'
|
2df01f3ccb379b875d284cfe627c35c7e40a2f89
|
Fix bug with filters
|
src/controllers/movies.js
|
src/controllers/movies.js
|
import models from '../models';
import express from 'express';
import _ from 'lodash';
let router = express.Router();
const defaults = {
limit: 10,
page: 1,
category: null
};
router.get('/', (req, res) => {
let params = _.defaults(req.query, defaults);
let category = params.category ? {'name': params.category} : {};
models.Movie.findAndCountAll({
include: [
{ model: models.Actors, required: false },
{ model: models.Categories, where: category, required: true }
],
offset: (params.limit * params.page) - params.limit,
limit: params.limit,
order: [['release_date', 'DESC']]
}).then(movies => {
res.json({
meta: {
total: Math.ceil(movies.count / parseInt(params.limit, 10)),
page: parseInt(params.page, 10),
limit: parseInt(params.limit, 10)
},
movies: movies.rows
});
});
});
router.get('/:movie_id', (req, res) => {
models.Movie.findOne({
include: [
models.Categories,
models.Actors
],
where: {
'slug': req.params.movie_id
}
}).then(movie => {
res.json({
movie: movie
});
}).catch(err => {
res.json(err);
});
});
export default router;
|
JavaScript
| 0 |
@@ -675,35 +675,403 @@
%3E %7B%0A
-res.json(%7B%0A
+/**%0A * findAndCountAll with requireds = false, will return the right count number%0A * but wont have the included models when filtering by category or actor. I%0A * suspect is a bug from sequelize, so ill just skip it by counting records%0A * using a new query.%0A */%0A models.Movie.findAndCountAll().then((data) =%3E %7B%0A res.json(%7B%0A
me
@@ -1072,24 +1072,26 @@
meta: %7B%0A
+
@@ -1107,22 +1107,20 @@
th.ceil(
-movies
+data
.count /
@@ -1161,16 +1161,18 @@
+
page: pa
@@ -1196,16 +1196,18 @@
e, 10),%0A
+
@@ -1254,19 +1254,23 @@
+
%7D,%0A
+
@@ -1291,16 +1291,30 @@
es.rows%0A
+ %7D);%0A
|
7968674cc5001846356e55e1c3fec6a55d743932
|
Fix country page
|
app/assets/scripts/components/map/legend.js
|
app/assets/scripts/components/map/legend.js
|
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { Dropdown } from 'openaq-design-system';
import c from 'classnames';
import styled from 'styled-components';
import { ParameterContext } from '../../context/parameter-context';
import { generateLegendStops } from '../../utils/colors';
const Wrapper = styled.div`
position: absolute;
bottom: 1rem;
left: 1rem;
right: 1rem;
z-index: 20;
max-width: 24rem;
overflow: hidden;
box-shadow: 0 0 32px 2px rgba(35, 47, 59, 0.04),
0 16px 48px -16px rgba(35, 47, 59, 0.12);
background-color: rgba(35, 47, 59, 0.04);
display: flex;
flex-direction: column;
gap: 1rem;
@media only screen and (min-width: 768px) {
bottom: 2rem;
left: 2rem;
}
`;
const Container = styled.div`
padding: 1.5rem;
background: #fff;
`;
const Definition = styled.dl`
margin: 0;
& > dd {
margin: 0;
}
display: grid;
grid-template-columns: 15px auto;
gap: 0.75rem;
align-items: center;
text-transform: uppercase;
`;
const Square = styled.div`
width: 15px;
height: 15px;
background-color: #198cff;
`;
const Circle = styled(Square)`
border-radius: 50%;
`;
const Drop = ({ parameters, activeParameter, onParamSelection }) => {
function onFilterSelect(parameter, e) {
e.preventDefault();
onParamSelection(parameter);
}
return (
<Dropdown
triggerElement="button"
triggerClassName="button button--primary-unbounded drop__toggle--caret"
triggerTitle="Show/hide parameter options"
triggerText={activeParameter.displayName}
>
<ul
role="menu"
className="drop__menu drop__menu--select"
style={{ overflowY: `scroll`, maxHeight: `15rem` }}
>
{parameters.map(param => (
<li key={`${param.parameterId || param.id}`}>
<a
className={c('drop__menu-item', {
'drop__menu-item--active': activeParameter.id === param.id,
})}
href="#"
title={`Show values for ${param.displayName}`}
data-hook="dropdown:close"
onClick={e => onFilterSelect(param.parameterId || param.id, e)}
>
<span>{param.displayName}</span>
</a>
</li>
))}
</ul>
</Dropdown>
);
};
Drop.propTypes = {
parameters: PropTypes.array,
activeParameter: PropTypes.shape({
displayName: PropTypes.string.isRequired,
name: PropTypes.string,
id: PropTypes.number,
parameterId: PropTypes.number,
}).isRequired,
onParamSelection: PropTypes.func,
};
const ColorScaleLegend = ({
legendParameters,
activeParameter,
onParamSelection,
isCoreParameter,
}) => {
const scaleStops = generateLegendStops(
activeParameter.parameterId || activeParameter.id
);
const colorWidth = 100 / scaleStops.length;
return (
<Container>
<p>
Showing the most recent* values for{' '}
{legendParameters?.length > 1 ? (
<Drop
parameters={legendParameters}
activeParameter={activeParameter}
onParamSelection={onParamSelection}
/>
) : (
activeParameter.displayName
)}
</p>
{isCoreParameter && (
<>
<ul className="color-scale">
{scaleStops.map(o => (
<li
key={o.label}
style={{
backgroundColor: o.color,
width: `${colorWidth}%`,
}}
className="color-scale__item"
>
<span className="color-scale__value">{o.label}</span>
</li>
))}
</ul>
<p>* Locations not updated in the last two days are shown in grey.</p>
<small className="disclaimer">
<a href="https://medium.com/@openaq/where-does-openaq-data-come-from-a5cf9f3a5c85">
Data Disclaimer and More Information
</a>
</small>
</>
)}
</Container>
);
};
ColorScaleLegend.propTypes = {
parameters: PropTypes.array,
legendParameters: PropTypes.array,
activeParameter: PropTypes.shape({
displayName: PropTypes.string.isRequired,
name: PropTypes.string,
id: PropTypes.number,
parameterId: PropTypes.number,
}).isRequired,
onParamSelection: PropTypes.func,
isCoreParameter: PropTypes.bool.isRequired,
};
export default function Legend({
presetParameterList,
paramIds,
activeParameter,
onParamSelection,
showOnlyParam,
}) {
const { parameters, isCore } = useContext(ParameterContext);
const activeParameterId = activeParameter.parameterId || activeParameter.id;
const filteredParams =
paramIds && parameters
? parameters.filter(param => paramIds.includes(param.id))
: null;
let legendParameters = presetParameterList ||
filteredParams || [activeParameter];
return (
<Wrapper>
<Container>
{showOnlyParam && legendParameters?.length > 1 && (
<p>
Showing locations for:
<Drop
parameters={legendParameters}
activeParameter={activeParameter}
onParamSelection={onParamSelection}
/>
</p>
)}
<Definition>
<dt>
<Circle />
</dt>
<dd>Reference grade sensor</dd>
<dt>
<Square />
</dt>
<dd>Low Cost Sensor</dd>
</Definition>
</Container>
{!showOnlyParam && activeParameter && (
<ColorScaleLegend
legendParameters={legendParameters}
activeParameter={activeParameter}
onParamSelection={onParamSelection}
isCoreParameter={isCore(activeParameterId)}
/>
)}
</Wrapper>
);
}
Legend.propTypes = {
presetParameterList: PropTypes.array,
paramIds: PropTypes.array,
activeParameter: PropTypes.shape({
displayName: PropTypes.string.isRequired,
name: PropTypes.string,
id: PropTypes.number,
parameterId: PropTypes.number,
}).isRequired,
onParamSelection: PropTypes.func,
showOnlyParam: PropTypes.bool,
};
|
JavaScript
| 0.000027 |
@@ -4657,16 +4657,38 @@
eterId =
+ activeParameter%0A ?
activeP
@@ -4729,16 +4729,27 @@
meter.id
+%0A : null
;%0A%0A con
@@ -6133,35 +6133,24 @@
number,%0A %7D)
-.isRequired
,%0A onParamS
|
f088427c07f626ce26e1f1f04ad8cbdf16940d38
|
Set the rich-text info for new replies.
|
reviewboard/static/rb/js/views/reviewReplyEditorView.js
|
reviewboard/static/rb/js/views/reviewReplyEditorView.js
|
/*
* Handles editing a reply to a comment in a review.
*
* This will handle the "Add Comment" link and the draft banners for the
* review.
*/
RB.ReviewReplyEditorView = Backbone.View.extend({
commentTemplate: _.template([
'<li <% if (isDraft) { %>class="draft"<% } %>',
' <% if (commentID) { %>data-comment-id="<%= commentID %>"<% } %>>',
' <dl>',
' <dt>',
' <label for="<%= id %>">',
' <a href="<%= userPageURL %>" class="user"><%- fullName %></a>',
'<% if (timestamp) { %>',
' <span class="timestamp">',
' <time class="timesince" datetime="<%= timestampISO %>">',
'<%= timestamp %></time> (<%= timestamp %>)',
' </span>',
'<% } %>',
' </label>',
' </dt>',
' <dd><pre id="<%= id %>" class="reviewtext"><%- text %></pre></dd>',
' </dl>',
'</li>'
].join('')),
events: {
'click .add_comment_link': '_onAddCommentClicked'
},
initialize: function() {
this._$addCommentLink = null;
this._$draftComment = null;
this._$editor = null;
this._$commentsList = null;
},
/*
* Renders the comment section.
*
* If there were any draft comments found, then editors will be
* created for them, the Add Comment link will be hidden.
*/
render: function() {
var $draftComment,
$time;
this._$addCommentLink = this.$('.add_comment_link');
this._$commentsList = this.$('.reply-comments');
/* See if there's a draft comment to import from the page. */
$draftComment = this._$commentsList.children('.draft');
if ($draftComment.length !== 0) {
$time = $draftComment.find('time');
this.model.set({
commentID: $draftComment.data('comment-id'),
text: $draftComment.find('pre.reviewtext').text(),
timestamp: new Date($time.attr('datetime')),
hasDraft: true
});
this._createCommentEditor($draftComment);
}
this.model.on('change:text', function(model, text) {
var reviewRequest = this.model.get('review').get('parentObject');
if (this._$editor) {
RB.formatText(this._$editor, text,
reviewRequest.get('bugTrackerURL'), {
forceRichText: true
});
}
}, this);
this.model.on('resetState', function() {
if (this._$draftComment) {
this._$draftComment.fadeOut(_.bind(function() {
this._$draftComment.remove();
this._$draftComment = null;
}, this));
}
this._$addCommentLink.fadeIn();
}, this);
this.model.on('published', this._onPublished, this);
},
/*
* Opens the comment editor for a new comment.
*/
openCommentEditor: function() {
this._createCommentEditor(this._makeCommentElement());
this._$editor.inlineEditor('startEdit');
},
/*
* Creates a comment editor for an element.
*/
_createCommentEditor: function($draftComment) {
var pageEditState = this.options.pageEditState;
this._$draftComment = $draftComment;
this._$editor = $draftComment.find('pre.reviewtext')
.inlineEditor({
cls: 'inline-comment-editor',
editIconClass: 'rb-icon rb-icon-edit',
notifyUnchangedCompletion: true,
multiline: true
})
.on({
beginEdit: function() {
if (pageEditState) {
pageEditState.incr('editCount');
}
},
complete: _.bind(function(e, value) {
if (pageEditState) {
pageEditState.decr('editCount');
}
this.model.set('text', value);
this.model.save();
}, this),
cancel: _.bind(function() {
if (pageEditState) {
pageEditState.decr('editCount');
}
this.model.resetStateIfEmpty();
}, this)
});
this._$addCommentLink.hide();
},
/*
* Creates an element for the comment form.
*/
_makeCommentElement: function(options) {
var userSession = RB.UserSession.instance,
now;
options = options || {};
now = options.now || moment().zone(userSession.get('timezoneOffset'));
return (
$(this.commentTemplate(_.extend({
id: _.uniqueId('draft_comment_'),
text: '',
commentID: null,
userPageURL: userSession.get('userPageURL'),
fullName: userSession.get('fullName'),
isDraft: true,
timestampISO: now.format(),
/*
* Note that we format the a.m./p.m. this way to match
* what's coming from the Django templates.
*/
timestamp: now.format('MMMM Do, YYYY, h:mm ') +
(now.hour() < 12 ? 'a.m.' : 'p.m.')
}, options)))
.find('.user')
.user_infobox()
.end()
.find('time.timesince')
.timesince()
.end()
.appendTo(this._$commentsList)
);
},
/*
* Handler for when the Add Comment link is clicked.
*
* Creates a new comment form and editor.
*/
_onAddCommentClicked: function(e) {
e.preventDefault();
e.stopPropagation();
this.openCommentEditor();
},
/*
* Handler for when the reply is published.
*
* Updates the draft comment to be a standard comment, and brings back
* the Add Comment link.
*/
_onPublished: function() {
if (this._$draftComment) {
this._$draftComment.replaceWith(this._makeCommentElement({
commentID: this.model.get('commentID'),
text: this.model.get('text'),
isDraft: false
}));
this._$draftComment = null;
}
}
});
|
JavaScript
| 0 |
@@ -846,16 +846,70 @@
viewtext
+ rich-text%22',%0A ' data-rich-text=%22true
%22%3E%3C%25- te
|
0567741c3bfbdd483858912abda2b6b69b5fc651
|
handle twitter connection error
|
imwatchingyou.js
|
imwatchingyou.js
|
var cfg = require('./config')
, db = require('./db')
, twit = require('./twitter')
, http = require('http-get')
, fs = require('fs')
, path_util = require('path')
, colors = require('colors');
// We check if we have an error to connect Mongoose
db.db.on('error', console.error.bind(console, 'connection error:'));
db.db.once('open', function callback () { // It's ok, so we start the stream from Twitter
console.log('Mongoose : OK'.green);
checkCredentials();
initStream();
});
function checkCredentials() {
twit.verifyCredentials(function (err, data) {
var welcomeMessage = 'Logged as ' + data.name + ' (' + data.screen_name + ')';
console.log(welcomeMessage.cyan);
});
}
function initStream () {
twit.stream('user', {'with':'followings'}, function(stream) {
console.log('Stream : OK'.green);
console.log('Waiting for a new tweet !'.green);
stream.on('data', function (data) {
if(data.text !== undefined) {
displayStream(data);
saveStream(data);
}
});
});
}
function displayStream(data) {
if (data.entities.media != undefined) {
console.log("[Media detected !]".rainbow + ' ' + data.user.screen_name.green + ': ' + data.text.red);
}
else {
console.log(data.user.screen_name.green + ': ' + data.text.red);
}
}
function saveStream(data) {
var tweet = new db.Tweet({data: data})
tweet.save(function (err, tweet) {
if (err) {}// TODO handle the error
});
if (data.entities.media != undefined) {
saveMedia(data.entities.media, data.user);
}
}
function saveMedia(medias, user) {
medias.forEach(function (media) { // foreach medias posted
var mediaLink = media.media_url_https + ':large'; // we add :large to get a better quality
var path_folder = cfg.basePath + user.screen_name + '/';
fs.mkdir(path_util.normalize(path_folder));
var path = path_util.normalize(path_folder + media.id_str + '.jpg');
http.get(mediaLink, path, function (error, result) { // Function to save this image
if (error) {
console.error(error.red);
} else {
console.log('File downloaded at: ' + result.file.green);
}
});
});
}
|
JavaScript
| 0.000001 |
@@ -453,125 +453,106 @@
);%0A%09
-checkCredentials();%0A%09initStream();%0A%7D);%0A%0Afunction checkCredentials() %7B%0A%09twit.verifyCredentials(function (err, data) %7B%0A
+%0A%09twit.verifyCredentials(function (err, data) %7B%0A%09%09if (err) %7B%0A%09%09%09console.error(err);%0A%09%09%7D%0A%09%09else %7B%0A%09
%09%09va
@@ -626,24 +626,25 @@
me + ')';%0A%09%09
+%09
console.log(
@@ -664,23 +664,47 @@
e.cyan);
+%0A%0A%09%09%09initStream();%0A%09%09%7D
%0A%09%7D);%0A%7D
+);
%0A%0Afuncti
@@ -914,16 +914,17 @@
%7B%0A%09%09%09if
+
(data.te
@@ -1059,32 +1059,33 @@
ntities.media !=
+=
undefined) %7B%0A%09%09
@@ -1445,16 +1445,17 @@
media !=
+=
undefin
@@ -2012,17 +2012,20 @@
d);%0A%09%09%09%7D
-
+%0A%09%09%09
else %7B%0A%09
|
31f5069954d5750c28d8ffa02ada736995e7d199
|
Fix CRLF line-endings in `hard-break-spaces`
|
lib/rules/hard-break-spaces.js
|
lib/rules/hard-break-spaces.js
|
/**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module hard-break-spaces
* @fileoverview
* Warn when too many spaces are used to create a hard break.
* @example
* <!-- Note: the middle-dots represent spaces -->
*
* <!-- Valid: -->
* Lorem ipsum··
* dolor sit amet
*
* <!-- Invalid: -->
* Lorem ipsum···
* dolor sit amet.
*/
'use strict';
/* eslint-env commonjs */
/*
* Dependencies.
*/
var visit = require('unist-util-visit');
var position = require('mdast-util-position');
/**
* Warn when too many spaces are used to create a
* hard break.
*
* @param {Node} ast - Root node.
* @param {File} file - Virtual file.
* @param {*} preferred - Ignored.
* @param {Function} done - Callback.
*/
function hardBreakSpaces(ast, file, preferred, done) {
var contents = file.toString();
visit(ast, 'break', function (node) {
var start = position.start(node).offset;
var end = position.end(node).offset;
var value;
if (position.generated(node)) {
return;
}
value = contents.slice(start, end).split('\n', 1)[0];
if (value.length > 2) {
file.warn('Use two spaces for hard line breaks', node);
}
});
done();
}
/*
* Expose.
*/
module.exports = hardBreakSpaces;
|
JavaScript
| 0.001684 |
@@ -1135,16 +1135,35 @@
', 1)%5B0%5D
+.replace(/%5Cr$/, '')
;%0A%0A
|
80c43e0f4015452401679c47560ecd921e9acbb7
|
fix post generator still including match post link and fix title formatting
|
app/components/Generator/headergenerator.js
|
app/components/Generator/headergenerator.js
|
'use strict';
/**
* @ngdoc function
* @name MatchCalendarApp.controller:HeadergeneratorCtrl
* @description
* # HeadergeneratorCtrl
* Controller of the MatchCalendarApp
*/
angular.module('MatchCalendarApp')
.controller('HeadergeneratorCtrl', ['$scope', '$window', '$state', '$interpolate', '$modal', '$localForage', 'HeaderGeneratorRegions', function ($scope, $window, $state, $interpolate, $modal, $localForage, HeaderGeneratorRegions) {
$scope.regions = HeaderGeneratorRegions;
// set up templating
$scope.templates = $scope.$new(true);
// set up the raw pre-processed version
$scope.templates.rawTemplate =
'\n**Game Information**' +
'\n---' +
'\n\n**Opens:** {{ opensUTC() }}' +
'\n\n**Starts:** {{ startsUTC() }}' +
'\n\n**Gametype:** Random Teams of 3' +
'\n\n**Scenario:** Vanilla+' +
'\n\n**Map Size:** 2000x2000' +
'\n\n**Nether:** Enabled' +
'\n\n**Duration:** 90 Minutes + Meetup' +
'\n\n**PvP:** 15 minutes in' +
'\n\n**Perma Day:** 30 minutes prior to Meetup' +
'\n\n**TeamSpeak 3 + Working Mic:** Required' +
'\n\n**Winner(s):** TBD' +
'\n___' +
'\n\n**Server Information**' +
'\n---' +
'\n\n**Slots:** 40' +
'\n\n___' +
'\n\n**Features**' +
'\n---' +
'\n\n**Golden Heads:** Enabled (Heal: 4 hearts)' +
'\n\n**Absorption:** Disabled' +
'\n\n**Enderpearl Damage:** Disabled' +
'\n\n**Death Lightning:** Enabled' +
'\n\n**Strength II:** Enabled but nerfed' +
'\n\n**Flint Rates:** Default' +
'\n\n**Apple Rates:** Default' +
'\n\n*To know more, /feature list in-game!*' +
'\n\n___' +
'\n\n**General Server Information**' +
'\n---' +
'\n\n**Location:** ' +
'\n\n**Server Provider / RAM:** ' +
'\n\n**IP:** {{ generator.address }}' +
'\n\n**Version:** 1.7.x' +
'\n\n___' +
'\n\n\n**Scenarios**' +
'\n---' +
'\n\n* **Vanilla+:** Vanilla with minor tweaks';
// the compiled version
$scope.templates.generated = '';
// save (and load) the template
$localForage.bind($scope.templates, 'rawTemplate');
// generator information
$scope.generator = {
postTitle: 'Game Title',
region: 'NA'
};
// save and load the generator settings
$localForage.bind($scope, 'generator');
// add utility functions for templating
$scope.opensUTC = function() {
return $scope.T.format($scope.T.formats.REDDIT_POST, $scope.opens, true);
};
$scope.startsUTC = function() {
return $scope.T.format($scope.T.formats.REDDIT_POST, $scope.starts, true);
};
// set the opening time to the current time for easy use
$scope.opens = $scope.T.currentTime();
// minimum time for things to show
$scope.minTime = $scope.T.currentTime();
/**
* Updates $scope.templates.generated with the compiled version of $scope.templates.rawTemplate
*/
$scope.updateTemplate = function() {
$scope.templates.generated = $interpolate($scope.templates.rawTemplate, false, null, true)($scope);
};
/**
* opens a new window to create a reddit post with the compiled template and info included
*/
$scope.openReddit = function() {
$scope.updateGenerated();
$scope.updateTemplate();
$window.open(
'https://reddit.com/r/ultrahardcore/submit?title=' +
encodeURIComponent($scope.T.format($scope.T.formats.REDDIT_POST, $scope.starts.utc(), true) + ' ' + $scope.generator.region + ' - ' + $scope.generator.postTitle) +
'&text=' +
encodeURIComponent($scope.templates.generated) +
encodeURIComponent('\n\n' +
$scope.generatedLink) +
encodeURIComponent('\n\n*^created ^using ^the [^Match ^Calendar](' + $window.location.protocol + '//' + $window.location.host + ')*'),
'_blank');
};
$scope.editTemplate = function() {
$scope.updateTemplate();
$modal.open({
templateUrl: 'components/Generator/TemplateEditor.html',
scope: $scope,
size: 'lg'
});
};
}]);
|
JavaScript
| 0 |
@@ -3883,24 +3883,49 @@
RIComponent(
+%0A
$scope.T.for
@@ -3965,21 +3965,20 @@
$scope.
-start
+open
s.utc(),
@@ -3989,48 +3989,146 @@
e) +
- ' ' + $scope.generator.region + ' - ' +
+%0A ' - ' +%0A $scope.generator.region +%0A ' - ' +%0A
$sc
@@ -4150,17 +4150,16 @@
ostTitle
-)
+%0A
@@ -4177,15 +4177,16 @@
+
-'&text=
+ ' -
' +%0A
@@ -4209,131 +4209,149 @@
-encodeURIComponent($scope.templates.generated) +%0A encodeURIComponent('%5Cn%5Cn' +%0A $scope
+ 'TODO ADD REGIONS' // TODO%0A ) +%0A '&text=' +%0A encodeURIComponent($scope.templates
.gen
@@ -4360,12 +4360,8 @@
ated
-Link
) +%0A
|
55e29257f27a3b4e95eabf13b03d6ad4a51bf2e9
|
Add host field.
|
lib/json_udp.js
|
lib/json_udp.js
|
/*
* <Brian K. Hsieh>
* Flush stats to udp in json formate.
*
* To enable this backend, include 'statsd-json-udp-backend' in the backends
* configuration array:
*
* backends: ['statsd-json-udpbackend']
*
* The backend will read the configuration options from the following
* 'json-udp' hash defined in the main statsd config file:
* {
* jsonUdp: {
* type: 'lmm-metric',
* port: "9999",
* },
* Each data point is sent seperated in the following format.
* {
* "flushTimestamp" => 1406828678000,
* "type" => "lmm-metric",
* "lmm.demo2.time.mean" => 0.3333333333333333,
*
* }
*
*/
var util = require('util'), dgram = require('dgram');
var os = require('os');
var fs = require('fs');
function JsonUdpBackend(startupTime, config, emitter, udpger) {
var self = this;
this.lastFlush = startupTime;
this.lastException = startupTime;
this.config = config.jsonUdp || {};
this.udpger = udpger;
this.hostname = this.config.hostname || 'localhost';
this.port = this.config.port || '9999';
this.sock = dgram.createSocket('udp4');
// Attach DNS error handler
this.sock.on('error', function (err) {
if (debug) {
l.udp('Repeater error: ' + err);
}
});
// attach
emitter.on('flush',
function(timestamp, metrics) {
self.flush(timestamp, metrics);
});
emitter.on('status', function(callback) { self.status(callback); });
}
JsonUdpBackend.prototype.flush = function(timestamp, metrics) {
var self = this;
if (parseInt(metrics.counters['statsd.packets_received']) === 0) {
return true;
}
var ts = timestamp * 1000;
var type = this.config.type || os.hostname();
var counters = metrics.counters;
for (var key in counters) {
/* Do not include statsd counters. */
if (key.match(/^statsd\./)) {
continue;
}
var output = jsonify(ts, type, key + '.counter', '', counters[key]);
emitJsonUdp(self, output);
}
// gauges
var gauges = metrics.gauges;
for (var key in gauges) {
/* Do not include statsd counters. */
if (key.match(/^statsd\./)) {
continue;
}
var output = jsonify(ts, type, key + '.gauge', '', gauges[key])
emitJsonUdp(self, output);
}
// timers
// From statsd, please ignore the coding style error for timer_data
var timers = metrics.timer_data;
for (var key in timers) {
var data = timers[key];
for (var item in data) {
var output = jsonify(ts, type, key + '.timer', item, data[item]);
emitJsonUdp(self, output);
}
}
return true;
};
function jsonify(ts, type, name, typeInstance, value) {
var output = {
flushTimestamp: ts,
type: type,
};
output['name'] = name;
output['value'] = value;
output['type_instance'] = typeInstance;
output = JSON.stringify(output) + '\n';
return output;
}
function emitJsonUdp(self, result) {
var out = new Buffer (result);
self.sock.send(out, 0, out.length, self.port, self.hostname,
function(err, bytes) {
if (err && debug) {
l.udp(err);
}
});
};
JsonUdpBackend.prototype.status = function(write) {
['lastFlush', 'lastException'].forEach(function(key) {
write(null, 'statsd-json-udp-backend', key, this[key]);
}, this);
};
exports.init = function(startupTime, config, events) {
var instance = new JsonUdpBackend(startupTime, config, events);
return true;
};
module.exports.jsonify = jsonify;
|
JavaScript
| 0 |
@@ -2740,16 +2740,50 @@
value;%0A
+ output%5B'host'%5D = os.hostname();%0A
output
|
8332978d8276e779e269d8404345dd7438a31034
|
Fix missed semicolon
|
roadmapplanningboard/plugin/OrcaColumnDropController.js
|
roadmapplanningboard/plugin/OrcaColumnDropController.js
|
(function() {
var Ext;
Ext = window.Ext4 || window.Ext;
Ext.define('Rally.apps.roadmapplanningboard.plugin.OrcaColumnDropController', {
extend: 'Rally.ui.cardboard.plugin.ColumnDropController',
alias: 'plugin.orcacolumndropcontroller',
init: function(column) {
this.callParent(arguments);
this.cmp = column;
},
_addDropTarget: function() {
var column = this.cmp;
this.dropTarget = Ext.create('Rally.apps.roadmapplanningboard.OrcaColumnDropTarget', this.getDndContainer(), {
ddGroup: column.ddGroup,
column: column
});
return this.dropTarget;
},
canDragDropCard: function(card) {
return true;
},
onCardDropped: function(dragData, index) {
var card, column, record, records, relativeRank, relativeRecord, sourceColumn, type;
card = dragData.card;
record = card.getRecord();
sourceColumn = dragData.column;
column = this.cmp;
records = column.getRecords();
if (column.mayRank() && isNaN(index)) {
index = records.length;
}
if (records.length && column.mayRank() && (sourceColumn === column || column.enableCrossColumnRanking)) {
if (index === 0) {
relativeRecord = records[index];
relativeRank = 'rankAbove';
} else {
relativeRecord = records[index - 1];
relativeRank = 'rankBelow';
}
}
this._addDroppedCard(sourceColumn, card, relativeRecord, relativeRank);
type = sourceColumn === column ? "reorder" : "move";
if (column.fireEvent("beforecarddroppedsave", column, card, type) !== false) {
if (!sourceColumn.planRecord) {
return this._moveOutOfBacklog({
sourceColumn: sourceColumn,
destinationColumn: column,
card: card
});
} else if (!column.planRecord) {
return this._moveIntoBacklog({
sourceColumn: sourceColumn,
destinationColumn: column,
card: card
});
} else {
return this._moveFromColumnToColumn({
sourceColumn: sourceColumn,
destinationColumn: column,
card: card
});
}
}
},
_moveIntoBacklog: function(options) {
var record,
_this = this;
record = options.card.getRecord();
options.sourceColumn.planRecord.set('features', Ext.Array.filter(options.sourceColumn.planRecord.get('features'), function(obj) {
return obj.id !== '' + record.getId();
}));
return options.sourceColumn.planRecord.save({
success: function() {
return _this._onDropSaveSuccess(options.destinationColumn, options.sourceColumn, options.card, record, "move");
},
failure: function(response, opts) {
var sourceIndex;
sourceIndex = options.sourceColumn.findCardInfo(record) && options.sourceColumn.findCardInfo(record).index;
return _this._onDropSaveFailure(options.destinationColumn, options.sourceColumn, record, options.card, sourceIndex, response);
}
});
},
_moveOutOfBacklog: function(options) {
var record,
_this = this;
record = options.card.getRecord();
options.destinationColumn.planRecord.get('features').push({
id: record.getId().toString(),
ref: record.get('_ref')
});
return options.destinationColumn.planRecord.save({
success: function() {
return _this._onDropSaveSuccess(options.destinationColumn, null, options.card, record, "move");
},
failure: function(response, opts) {
var sourceIndex;
sourceIndex = options.sourceColumn.findCardInfo(record) && options.sourceColumn.findCardInfo(record).index;
return _this._onDropSaveFailure(options.destinationColumn, options.sourceColumn, record, options.card, sourceIndex, response);
}
});
},
_moveFromColumnToColumn: function(options) {
var record,
_this = this;
record = options.card.getRecord();
options.sourceColumn.planRecord.set('features', Ext.Array.filter(options.sourceColumn.planRecord.get('features'), function(obj) {
return obj.id !== '' + record.getId();
}));
options.destinationColumn.planRecord.get('features').push({
id: record.getId().toString(),
ref: record.get('_ref')
});
return Ext.Ajax.request({
method: 'POST',
url: this._constructUrl(options.sourceColumn.planRecord.getId(), options.destinationColumn.planRecord.getId()),
jsonData: {
data: [
{
id: record.getId() + '',
ref: record.get('_ref')
}
]
},
success: function() {
var type;
type = options.sourceColumn === options.column ? "reorder" : "move";
return _this._onDropSaveSuccess(options.destinationColumn, options.sourceColumn, options.card, record, type);
},
failure: function(response, opts) {
var sourceIndex;
sourceIndex = options.sourceColumn.findCardInfo(record) && options.sourceColumn.findCardInfo(record).index;
return _this._onDropSaveFailure(options.destinationColumn, options.sourceColumn, record, options.card, sourceIndex, response);
}
});
},
_constructUrl: function(sourceId, destinationId) {
return Rally.environment.getContext().context.services.planning_service_url + '/api/plan/' + sourceId + '/features/to/' + destinationId
},
_onDropSaveSuccess: function(column, sourceColumn, card, updatedRecord, type) {
if (column) {
return column.fireEvent('aftercarddroppedsave', this, card, type);
}
},
_onDropSaveFailure: function(column, sourceColumn, record, card, sourceIndex, errorSource) {
if (errorSource.error && errorSource.error.errors && errorSource.error.errors.length) {
Rally.ui.notify.Notifier.showError({
message: errorSource.error.errors[0]
});
}
return sourceColumn.addCard(card, sourceIndex, true);
},
_addDragZone: function() {
var column;
column = this.cmp;
this._dragZone = Ext.create('Ext.dd.DragZone', this.getDndContainer(), {
ddGroup: column.ddGroup,
onBeforeDrag: function(data, e) {
var avatar;
avatar = Ext.fly(this.dragElId);
avatar.setWidth(data.targetWidth);
return column.fireEvent('cardpickedup', data.card);
},
proxy: Ext.create('Ext.dd.StatusProxy', {
animRepair: true,
shadow: false,
dropNotAllowed: "cardboard"
}),
getDragData: function(e) {
var avatar, dragEl, sourceEl;
dragEl = e.getTarget('.drag-handle', 10);
if (dragEl) {
sourceEl = e.getTarget('.rui-card', 10) || e.getTarget('.rui-card-slim', 10);
avatar = sourceEl.cloneNode(true);
avatar.id = Ext.id();
return {
targetWidth: Ext.fly(sourceEl).getWidth(),
ddel: avatar,
sourceEl: sourceEl,
repairXY: Ext.fly(sourceEl).getXY(),
card: Ext.ComponentManager.get(sourceEl.id),
column: column
};
}
},
getRepairXY: function() {
return this.dragData.repairXY;
}
});
},
destroy: function() {
var _ref, _ref1, _ref2;
if (this._dragZone) {
this._dragZone.destroy();
if(this._dragZone.proxy) {
this._dragZone.proxy.destroy();
}
}
return this.callParent(arguments);
}
});
}).call(this);
|
JavaScript
| 0.000003 |
@@ -5589,16 +5589,17 @@
nationId
+;
%0A %7D,%0A
|
95168b6b7e34d79d9d90db101336194a7ce609b4
|
allow null filter
|
lib/launcher.js
|
lib/launcher.js
|
var _ = require('lodash');
var TDManagerLauncher = function (args, managerConnect, /* config.managerConnect */ config, logger, helper, baseLauncherDecorator, captureTimeoutLauncherDecorator, retryLauncherDecorator) {
baseLauncherDecorator(this);
captureTimeoutLauncherDecorator(this);
retryLauncherDecorator(this);
config = config || {};
var log = logger.create('launcher.test-device-manager'),
self = this;
self.name = helper._.values(args.filter).join(' ');
this.on('start', function (url, done) {
var options = helper.merge(config.options, args, {
filter: args.filter,
tags: args.tags || config.tags || [],
name: args.testName || config.testName || 'Karma test'
});
// Adding any other option that was specified in args, but not consumed from above
// Useful for supplying chromeOptions, firefoxProfile, etc.
for (var key in args) {
if (typeof options[key] === 'undefined') {
options[key] = args[key];
}
}
managerConnect.start(config, helper).then(function () {
var browsers = helper._.where(managerConnect.clientList, options.filter);
if (!browsers.length) {
log.error('Browser %s not found! Retry in 10 seconds...', self.name);
setTimeout(function () {
self._done('failure');
}, 10000);
} else {
managerConnect.go(url, helper._.pluck(browsers, 'id'));
}
done();
});
});
};
module.exports = TDManagerLauncher;
|
JavaScript
| 0.000001 |
@@ -1162,16 +1162,151 @@
owsers =
+ %5B%5D;%0A%0A if (options.filter === null) %7B%0A browsers = clientList;%0A %7D else %7B%0A browsers =
helper.
@@ -1356,16 +1356,30 @@
filter);
+%0A %7D
%0A%0A
|
0c9f173df99f52e93d5d04c3026858b8b4932d9a
|
Remove useless logging
|
site/media/orbital.js
|
site/media/orbital.js
|
(function(){
orbital = this;
var host = 'ws://' + window.location.host + '/';
var maxLayers = 30;
var dateKeyFunc = function(){
return new Date().getMinutes();
};
var lastDateKey = null;
var element = null;
var layers = [];
var activeLayer;
var adjustOffset = 0;
var targetHeight = 1800;
var targetWidth = 3600;
var setHeight;
var setWidth;
var currentData = [];
var lastMessage = null;
function sizePageElements() {
var $geo = $("#geo");
$geo.css("height", $("body").height() - adjustOffset);
if ($geo.width() / $geo.height() > 2) {
orbital.scale = $geo.height() / targetHeight;
} else {
orbital.scale = $geo.width() / targetWidth;
}
element.css({
"top": $geo.height() - targetHeight * orbital.scale,
"left": ($geo.width() - targetWidth * orbital.scale) / 2
});
setWidth = element.width();
setHeight = element.height();
$('#mapdata').css({
"-moz-transform": "scale(" + orbital.scale + ")",
"-webkit-transform": "scale(" + orbital.scale + ")",
"-ms-transform": "scale(" + orbital.scale + ")",
"-o-transform": "scale(" + orbital.scale + ")"
});
$("canvas").css({
width: setWidth + "px",
height: setHeight + "px"
});
$("canvas").attr('width', setWidth);
$("canvas").attr('height', setHeight);
}
orbital.addMessage = function(data, x, y){
if (lastMessage) {
return;
}
var post = data.post;
var icon;
if (post.icon) {
icon = '<img src="' + post.icon + '" class="favicon"/>';
} else {
icon = '';
}
lastMessage = $('<div class="overlay">' +
icon +
'<strong>' + post.title + '</strong>' +
'</div>').hide().appendTo(element).css({
'left': x,
'top': y
}).show();
setTimeout(function(){
lastMessage.fadeOut('fast', function(){
lastMessage.remove();
lastMessage = null;
});
}, 1500);
};
orbital.addData = function(data) {
var x = ~~((parseFloat(data.lng) + 180) * 10) * orbital.scale,
y = ~~((-parseFloat(data.lat) + 90) * 10) * orbital.scale;
// render and animate our point
var point = jc.circle(x, y,
5, "rgba(255, 255, 255, 1)", 1)
.animate({radius:1, opacity:0.4}, 300, function(){
point.del();
activeLayer.fillStyle = "rgba(255, 255, 255, 0.2)";
activeLayer.beginPath();
activeLayer.arc(x, y, 1, 0, Math.PI * 2, false);
activeLayer.fill();
});
if (data.post) {
this.addMessage(data, x, y);
}
};
orbital.connect = function(params){
// if params are empty, set them to * (all results)
if (params === undefined || params === '') {
params = '*';
}
orbital.params = params;
// close the open socket first
orbital.disconnect();
console.log('Opening websocket connection');
orbital.socket = new WebSocket(host);
orbital.socket.onclose = function(e){
setTimeout(function(){
orbital.connect(orbital.params);
}, 3000);
};
orbital.socket.onopen = function(){
this.send('SUB ' + orbital.params);
};
orbital.socket.onmessage = function(msg){
var data = JSON.parse(msg.data);
orbital.addData(data);
this.send('OK');
};
};
orbital.disconnect = function(){
if (orbital.socket) {
console.log('Closing websocket connection');
orbital.socket.onclose = function(){
console.log('Socket closed');
};
orbital.socket.close();
orbital.socket = null;
}
};
orbital.createLayer = function(dateKey){
var layer = $('<canvas data-date-key="' + dateKey + '"></canvas>').css({
width: setWidth + 'px',
height: setHeight + 'px'
}).attr({
width: setWidth,
height: setHeight
});
element.append(layer);
layers.push(layer);
return layer;
};
orbital.watchActiveLayer = function() {
dateKey = dateKeyFunc();
if (dateKey == lastDateKey) {
setTimeout(orbital.watchActiveLayer, 3000);
return;
}
lastDateKey = dateKey;
// create a new layer
layer = orbital.createLayer(dateKey);
// set the new layer as the active layer
activeLayer = layer[0].getContext("2d");
// remove excess layers
var excess = layers.slice(maxLayers, layers.length);
orbital.layers = layers.slice(0, maxLayers);
for (var i=0; i<excess.length; i++) {
console.log('Removing layer ( ' + excess[i].attr('data-date-key') + ' )');
excess[i].remove();
}
setTimeout(orbital.watchActiveLayer, 3000);
};
orbital.initOptions = function() {
var $options = $('#options');
$('.close', $options).click(function(){
$('#options').hide();
});
$('#header .options').click(function(){
$options.show();
});
$('form', $options).submit(function(){
orbital.connect($(this).serialize());
return false;
});
};
orbital.init = function(el, params) {
element = el;
sizePageElements();
jc.start('pings', true);
orbital.watchActiveLayer();
orbital.initOptions();
window.onbeforeunload = function() {
orbital.disconnect();
};
orbital.connect(params);
};
})();
|
JavaScript
| 0.000002 |
@@ -3230,61 +3230,8 @@
);%0A%0A
- console.log('Opening websocket connection');%0A
@@ -3800,160 +3800,44 @@
-console.log('Closing websocket connection');%0A orbital.socket.onclose = function()%7B%0A console.log('Socket closed');%0A
+orbital.socket.onclose = function()%7B
%7D;%0A
|
f4f512b80af67efde796881e9e96fa0261bbace8
|
clarify application config comments - fixes #279
|
archetype/config/application.js
|
archetype/config/application.js
|
/* Exports a function which returns an object that overrides the default &
* plugin grunt configuration object.
*
* You can familiarize yourself with Lineman's defaults by checking out:
*
* - https://github.com/linemanjs/lineman/blob/master/config/application.coffee
* - https://github.com/linemanjs/lineman/blob/master/config/plugins
*
* You can also ask Lineman's about config from the command line:
*
* $ lineman config #=> to print the entire config
* $ lineman config concat_sourcemap.js #=> to see the JS config for the concat task.
*/
module.exports = function(lineman) {
//Override application configuration here. Common examples follow in the comments.
return {
// API Proxying
//
// During development, you'll likely want to make XHR (AJAX) requests to an API on the same
// port as your lineman development server. By enabling the API proxy and setting the port, all
// requests for paths that don't match a static asset in ./generated will be forwarded to
// whatever service might be running on the specified port.
//
// server: {
// apiProxy: {
// enabled: true,
// host: 'localhost',
// port: 3000
// }
// }
// Sass
//
// Lineman supports Sass via grunt-contrib-sass, which requires you first
// have Ruby installed as well as the `sass` gem. To enable it, comment out the
// following line:
//
// enableSass: true
// Asset Fingerprints
//
// Lineman can fingerprint your static assets by appending a hash to the filename
// and logging a manifest of logical-to-hashed filenames in dist/assets.json
// via grunt-asset-fingerprint
//
// enableAssetFingerprint: true
// LiveReload
//
// Lineman can LiveReload browsers whenever a file is changed that results in
// assets to be processed, preventing the need to hit F5/Cmd-R every time you
// make a change in each browser you're working against. To enable LiveReload,
// comment out the following line:
//
// livereload: true
};
};
|
JavaScript
| 0 |
@@ -174,19 +174,17 @@
by
-chec
+loo
king
-ou
+a
t:%0A
@@ -361,16 +361,22 @@
lso ask
+about
Lineman'
@@ -377,21 +377,16 @@
neman's
-about
config
@@ -1380,24 +1380,26 @@
ble it,
+un
comment
out the%0A
@@ -1390,20 +1390,16 @@
comment
-out
the%0A
|
7165d86e39740e32152e3d803943248fe368f497
|
Test that the GOV.UK view escapes model values
|
spec/server-pure/views/spec.govuk.js
|
spec/server-pure/views/spec.govuk.js
|
var requirejs = require('requirejs');
var GovUkView = require('../../../app/server/views/govuk');
var Model = requirejs('extensions/models/model');
describe('GovUkView', function () {
var model;
beforeEach(function () {
model = new Model({
requirePath: '/testRequirePath/',
assetPath: '/testAssetPath/',
assetDigest: {
'spotlight.css': 'spotlight-cachebust.css'
},
environment: 'development'
});
});
it('renders a page with content view in GOV.UK style', function () {
var view = new GovUkView({
model: model
});
spyOn(view, 'loadTemplate').andCallThrough();
spyOn(view, 'getContent').andReturn('test_content');
spyOn(view, 'getReportForm').andReturn('report_a_problem');
view.render();
var context = view.loadTemplate.mostRecentCall.args[1];
expect(context.head.trim().indexOf('<link href="/testAssetPath/stylesheets/spotlight-cachebust.css" media="all" rel="stylesheet" type="text/css">')).not.toBe(-1);
expect(context.pageTitle).toEqual('Performance - GOV.UK');
var content = context.content.replace(/\s+/g, ' ').trim();
expect(content).toEqual('<div id="wrapper"> <main id="content" class="group" role="main"> test_content report_a_problem </main> </div>');
});
});
|
JavaScript
| 0 |
@@ -187,32 +187,63 @@
%0A%0A
-var model;%0A beforeEach(
+it('renders a page with content view in GOV.UK style',
func
@@ -252,24 +252,28 @@
on () %7B%0A
+var
model = new
@@ -481,86 +481,8 @@
%7D);
-%0A %7D);%0A%0A it('renders a page with content view in GOV.UK style', function () %7B
%0A%0A
@@ -1080,24 +1080,24 @@
').trim();%0A
-
expect(c
@@ -1233,12 +1233,1039 @@
%0A %7D);%0A%0A
+ it('escapes values that are reflected into the page', function () %7B%0A var original = '%5C'%22;%3Cscript%3E';%0A%0A var model = new Model(%7B%0A requirePath: '/testRequirePath/',%0A assetPath: '/testAssetPath/',%0A assetDigest: %7B%0A 'spotlight.css': 'spotlight-cachebust.css'%0A %7D,%0A environment: 'development',%0A params: %7B%0A sortby: original%0A %7D%0A %7D);%0A%0A var view = new GovUkView(%7B%0A model: model%0A %7D);%0A%0A spyOn(view, 'loadTemplate').andCallThrough();%0A spyOn(view, 'getContent').andReturn('test_content');%0A spyOn(view, 'getReportForm').andReturn('report_a_problem');%0A%0A view.render();%0A%0A // Check the context of the render call for bodyEnd%0A // and inspect the serializedModel JSON string%0A var calls = view.loadTemplate.calls;%0A var bodyEndCall = calls%5B1%5D;%0A var context = bodyEndCall.args%5B1%5D;%0A var serialized = context.serializedModel;%0A%0A // Ensure the params string is fully escaped.%0A expect(serialized).toMatch(/sortby%22:%22'%5C%5C%22;%5C%5Cu003Cscript%5C%5Cu003E/);%0A %7D);%0A%0A
%7D);%0A
|
85d924a5c1b937bbb4be84f0b890a18809a5dc74
|
Update serializers.js
|
lib/marshal/serializers.js
|
lib/marshal/serializers.js
|
var UUID = require('../uuid');
/**
* Serializers for various types
* @class
*/
var Serializers = {};
/**
* Encodes an N length Integer
* @param {Number} bits The number of bits to encode to
* @param {Number} num The number to encode
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeInteger = function(bits, num){
var buf = new Buffer(bits/8), func;
if(typeof num !== 'number'){
num = parseInt(num, 10);
}
switch(bits){
case 32: buf.writeUInt32BE(num, 0); break;
case 64:
var hex = num.toString(16);
hex = new Array(17 - hex.length).join('0') + hex;
buf.writeUInt32BE(parseInt(hex.slice( 0, 8), 16), 0);
buf.writeUInt32BE(parseInt(hex.slice( 8, 16), 16), 4);
}
return buf;
};
/**
* Does binary encoding
* @param {String} val The binary string to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeBinary = function(val){
if(Buffer.isBuffer(val)){
return val;
} else {
return new Buffer(val.toString(), 'binary');
}
};
/**
* Encodes a Long (UInt64)
* @param {Number} val The number to serialize into a long
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeLong = function(val){
return Serializers.encodeInteger(64, val);
};
/**
* Encodes a 32bit Unsinged Integer
* @param {Number} val The number to serialize into a 32-bit integer
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeInt32 = function(val){
return Serializers.encodeInteger(32, val);
};
/**
* Encodes for UTF8
* @param {String} val The utf8 string value to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeUTF8 = function(val){
if(Buffer.isBuffer(val)){
return val;
}
if(val === undefined || val === null){
val = '';
}
return new Buffer(val.toString(), 'utf8');
};
/**
* Encodes for Ascii
* @param {String} val The ascii string value to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeAscii = function(val){
if(Buffer.isBuffer(val)){
return val;
}
if(val === undefined || val === null){
val = '';
}
return new Buffer(val.toString(), 'ascii');
};
/**
* Encode a Double Precision Floating Point Type
* @param {Number} val The number to serialize into a Double Precision Floating Point
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeDouble = function(val){
var buf = new Buffer(8);
buf.writeDoubleBE(val, 0);
return buf;
};
/**
* Encode a Double Precision Floating Point Type
* @param {Number} val The number to serialize into a Single Precision Floating Point
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeFloat = function(val){
var buf = new Buffer(4);
buf.writeFloatBE(val, 0);
return buf;
};
/**
* Encodes a boolean type
* @param {Boolean} val true or false, will be serialized into the proper boolean value
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeBoolean = function(val){
if(val){
return new Buffer([0x01]);
} else {
return new Buffer([0x00]);
}
};
/**
* Encodes a Date object
* @param {Date} val The date to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeDate = function(val){
var t;
if(val instanceof Date){
t = val.getTime();
} else {
t = new Date(val).getTime();
}
return Serializers.encodeLong(t);
};
/**
* Encodes a UUID Object
* @param {UUID} val The uuid object to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeUUID = function(val){
return val.toBuffer();
};
/**
* Encodes a TimeUUID Object
* @param {TimeUUID} val The uuid object to serialize
* @returns {Buffer} A buffer containing the value bytes
* @static
*/
Serializers.encodeTimeUUID = function(val){
return val.toBuffer();
};
module.exports = Serializers;
|
JavaScript
| 0 |
@@ -3814,38 +3814,152 @@
val)%7B%0A
-return val.toBuffer();
+if (val instanceof UUID.UUID) %7B%0A return val.toBuffer();%0A %7D else %7B%0A var uuid = new UUID.UUID(val);%0A return uuid.toBuffer();%0A %7D
%0A%7D;%0A%0A/**
@@ -4160,38 +4160,168 @@
val)%7B%0A
-return val.toBuffer();
+if (val instanceof UUID.TimeUUID) %7B%0A return val.toBuffer();%0A %7D else %7B%0A var timeUUID = new UUID.TimeUUID(val);%0A return timeUUID.toBuffer();%0A %7D
%0A%7D;%0A%0Amod
|
aaaac2972d17e6cb9a2988c207752558b0c77767
|
Remove unused var
|
lib/log_tree.js
|
lib/log_tree.js
|
// Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
var factory = function(object) {
var tree, numerator, denominator, children, is_complete;
tree = { };
numerator = 0;
denominator = 1;
children = [ ];
is_complete = false;
if (object.hasOwnProperty("c")) {
for (let c of object.c) {
children.push(factory(c));
}
}
for (let c of children) {
denominator += c.den();
}
tree.description = "";
tree.num = function() {
var result = is_complete ? 1 : 0;
for (let x of children) {
result += x.num();
}
return result;
};
tree.den = function() { return denominator; };
tree.complete = function(json_string) {
var array, timestamp, code, message;
array = JSON.parse(json_string);
timestamp = array.shift();
code = array.shift();
message = array.pop();
tree.mark_true(array);
};
tree.mark_true = function(array) {
var i;
if (array.length == 0) {
is_complete = true;
} else {
i = array.shift();
children[i].mark_true(array);
}
};
tree[Symbol.iterator] = function() {
return children[Symbol.iterator]();
};
return tree;
};
module.exports = factory;
|
JavaScript
| 0.000001 |
@@ -223,19 +223,8 @@
ree,
- numerator,
den
@@ -276,25 +276,8 @@
%7D;%0A%0A
- numerator = 0;%0A
de
|
275626be9f7ff61bb026058e4cfa4673118c977a
|
Fix undo of insertColumn when cursor is in inserted column
|
lib/transforms/insertColumn.js
|
lib/transforms/insertColumn.js
|
const TablePosition = require('../TablePosition');
const createCell = require('../createCell');
/**
* Insert a new column in current table
*
* @param {Object} opts
* @param {Slate.Transform} transform
* @param {Number} at
* @return {Slate.Transform}
*/
function insertColumn(opts, transform, at) {
const { state } = transform;
const { startBlock } = state;
const pos = TablePosition.create(state, startBlock);
const { table } = pos;
if (typeof at === 'undefined') {
at = pos.getColumnIndex() + 1;
}
let rows = table.nodes;
// Add a new cell to each row
rows = rows.map(function(row) {
let cells = row.nodes;
const newCell = createCell(opts.typeCell);
cells = cells.insert(at, newCell);
return row.merge({ nodes: cells });
});
// Update table
const newTable = table.merge({
nodes: rows
});
// Replace the table
return transform
.setNodeByKey(table.key, newTable);
}
module.exports = insertColumn;
|
JavaScript
| 0.000002 |
@@ -44,16 +44,66 @@
tion');%0A
+const moveSelection = require('./moveSelection');%0A
const cr
@@ -977,22 +977,27 @@
ble%0A
-return
+transform =
transfo
@@ -998,25 +998,16 @@
ransform
-%0A
.setNode
@@ -1034,16 +1034,163 @@
Table);%0A
+ // Update the selection (not doing can break the undo)%0A return moveSelection(opts, transform, pos.getColumnIndex() + 1, pos.getRowIndex());%0A
%7D%0A%0Amodul
|
590dd3c4ebb49a5e6d3bb7f462f77f9bc3be888a
|
Add redirect and more informative error messages
|
server.js
|
server.js
|
"use strict";
let express = require('express');
let validate = require('./validate');
let pg = require('pg');
var favicon = require('serve-favicon');
let app = express();
app.use(favicon(__dirname + '/public/favicon.ico'));
let conString = process.env.DATABASE_URL || "postgres://test:test@localhost/test_db";
app.all((req, res, next) => {
next();
})
.get('/', (req, res, next) => {// home page
res.sendFile(__dirname + '/public/index.html');
})
.get('/new', (req, res, next) => {
let url = decodeURIComponent(req.query["original-url"]);
validate.checkUrl(url, (err, status) => {
if (err) { // if validator says the url is invalid
console.log(err);
res.send("That URL isn't valid. Please make sure it's correct and try again."); // make this send an error json
} else if (status === 200 || 301 || 302) {
pg.connect(conString, (err, client, done) => {
let handleError = (err) => {
if (!err) return false; // no error, continue with the request
if (client) done(client); // remove client from connection pool
res.status(500).send('An error occurred. Please try again in a few moments.');
return true;
};
if (handleError(err)) return; // handle error from the connection
client.query('SELECT * FROM urls WHERE url=$1', [url], (err, result) => {
if (handleError(err)) return; // handle error from the query
done();
if (result.rowCount) { // url is already in db
res.json({
original_url: result.rows[0].url,
short_code: result.rows[0].p_id
});
} else { // url is new
client.query('INSERT INTO urls (url) VALUES ($1) RETURNING *', [url], (err, result) => {
if (handleError(err)) return; // handle error from the query
done();
res.json({
original_url: result.rows[0].url,
short_code: result.rows[0].p_id
});
});
}
});
});
} else { // if http request returned with something other than 200
console.log(status);
res.send("There was a problem checking the URL. Please try again."); // make this send an error json
}
});
})
.get('/:short_code', (req, res, next) => {
let shortCode = req.params["short_code"];
pg.connect(conString, (err, client, done) => {
let handleError = (err) => {
if (!err) return false; // no error, continue with the request
if (client) done(client); // remove client from connection pool
res.status(500).send('An error occurred. Please try again in a few moments.');
return true;
};
if (handleError(err)) return; // handle error from the connection
client.query('SELECT * FROM urls WHERE p_id=$1', [shortCode], (err, result) => {
if (handleError(err)) return; // handle error from the query
done();
if (result.rowCount) { // url is already in db
res.json({
original_url: result.rows[0].url,
short_code: result.rows[0].p_id
});
} else { // url is new
// return error
res.send("URL doesn't exist.");
}
});
});
});
let port = process.env.PORT || 8080;
app.listen(port, () => {
console.log("Server is running on port " + port + "\n");
});
|
JavaScript
| 0 |
@@ -12,23 +12,18 @@
%22;%0A%0Alet
-express
+pg
= requi
@@ -30,23 +30,18 @@
re('
-express
+pg
');%0Alet
vali
@@ -36,24 +36,23 @@
');%0Alet
-validate
+express
= requi
@@ -59,42 +59,15 @@
re('
-./validate');%0Alet pg = require('pg
+express
');%0A
@@ -103,24 +103,63 @@
favicon');%0A%0A
+let validate = require('./validate');%0A%0A
let app = ex
@@ -1511,32 +1511,44 @@
res.
+status(200).
json(%7B%0A
@@ -1890,32 +1890,44 @@
res.
+status(201).
json(%7B%0A
@@ -2193,20 +2193,40 @@
res.s
-end(
+tatus(400).json(%7Berror:
%22There w
@@ -2267,53 +2267,50 @@
ase
-try again.%22); // make this send an error json
+make sure it is correct and try again.%22%7D);
%0A
@@ -2654,39 +2654,51 @@
us(500).
-send('An error occurred
+json(%7Berror: %22Internal server error
. Please
@@ -2709,37 +2709,33 @@
again in a
-few
moment
-s.'
+.%22%7D
);%0A ret
@@ -3058,112 +3058,36 @@
res.
-json(%7B%0A original_url: result.rows%5B0%5D.url,%0A short_code: result.rows%5B0%5D.p_id%0A %7D);
+redirect(result.rows%5B0%5D.url)
%0A
@@ -3124,41 +3124,37 @@
-// return error%0A res.send(
+res.status(400).json(%7Berror:
%22URL
@@ -3169,18 +3169,35 @@
exist.%22
+%7D
);
+ // return error
%0A %7D
|
58f1bca330301596bea17e771c2ec03c34d0fa2c
|
apply review https://oss.navercorp.com/egjs/egjs/pull/180#discussion_r1383
|
src/customEvent/rotate.js
|
src/customEvent/rotate.js
|
// jscs:disable maximumLineLength
eg.module("rotate", ["jQuery", eg, window, document], function($, ns, global, doc) {
"use strict";
// jscs:enable maximumLineLength
/**
* @namespace jQuery
* @group jQuery Extension
*/
/**
* Support rotate event in jQuery
*
* @ko jQuery custom rotate 이벤트 지원
* @name jQuery#rotate
* @event
* @param {Event} e event
* @param {Boolean} e.isVertical vertical <ko>수직여부</ko>
* @support { "ios" : "7+", "an" : "2.1+ (except 3.x)", "n-ios" : "latest", "n-an" : "latest" }
* @example
* $(window).on("rotate",function(e){
* e.isVertical;
* });
*
*/
var beforeScreenWidth = -1;
var beforeVertical = null;
var rotateTimer = null;
var agent = ns.agent();
var isMobile = /android|ios/.test(agent.os.name);
/*
* This orientationChange method is return event name for bind orientationChange event.
*/
var orientationChange = function() {
var type;
/**
* Android Bug
* Android 2.4 has orientationchange but It use change width, height. so Delay 500ms use setTimeout.
* : If android 2.3 made samsung bind resize on window then change rotate then below version browser.
* Twice fire orientationchange in android 2.2. (First time change widht, height, second good.)
* Below version use resize.
*
* In app bug
* If fire orientationChange in app then change width, height. so delay 200ms using setTimeout.
*/
if ((agent.os.name === "android" && agent.os.version === "2.1")) {//|| htInfo.galaxyTab2)
type = "resize";
} else {
type = "onorientationchange" in global ? "orientationchange" : "resize";
}
orientationChange = function() {
return type;
};
return type;
};
/*
* If viewport is vertical return true else return false.
*/
function isVertical() {
var eventName = orientationChange();
var screenWidth;
var degree;
var vertical;
if (eventName === "resize") {
screenWidth = doc.documentElement.clientWidth;
if (beforeScreenWidth === -1) { //first call isVertical
vertical = screenWidth < doc.documentElement.clientHeight;
} else {
if (screenWidth < beforeScreenWidth) {
vertical = true;
} else if (screenWidth === beforeScreenWidth) {
vertical = beforeVertical;
} else {
vertical = false;
}
}
beforeScreenWidth = screenWidth;
} else {
degree = global.orientation;
if (degree === 0 || degree === 180) {
vertical = true;
} else if (degree === 90 || degree === -90) {
vertical = false;
}
}
return vertical;
}
/*
* Trigger that rotate event on an element.
*/
function triggerRotate() {
var currentVertical = isVertical();
if (isMobile) {
if (beforeVertical !== currentVertical) {
beforeVertical = currentVertical;
$(global).trigger("rotate");
}
}
}
/*
* Trigger event handler.
*/
function handler(e) {
var eventName = orientationChange();
var delay;
var screenWidth;
if (eventName === "resize") {
global.setTimeout(function() {
triggerRotate();
}, 0);
} else {
delay = 300;
if (agent.os.name === "android") {
screenWidth = doc.documentElement.clientWidth;
if (e.type === "orientationchange" && screenWidth === beforeScreenWidth) {
global.setTimeout(function() {
handler(e);
}, 500);
// When fire orientationchange if width not change then again call handler after 300ms.
return false;
}
beforeScreenWidth = screenWidth;
}
global.clearTimeout(rotateTimer);
rotateTimer = global.setTimeout(function() {
triggerRotate();
}, delay);
}
}
$.event.special.rotate = {
setup: function() {
beforeScreenWidth = doc.documentElement.clientWidth;
$(global).on(orientationChange(), handler);
},
teardown: function() {
$(global).off(orientationChange(), handler);
},
trigger: function(e) {
e.isVertical = beforeVertical;
}
};
/**
* If a viewport of your device is portrait mode, this method returns "true"
* @ko 해당 기기의 viewport 가 portait(수직방향)이라면 true을 반환한다.
* @method eg#isPortrait
* @return {Boolean}
* @example
eg.isPortrait(); // If a viewport of your device is portrait mode, this method returns "true".
*/
ns.isPortrait = isVertical;
return {
"orientationChange": orientationChange,
"isVertical": isVertical,
"triggerRotate": triggerRotate,
"handler": handler
};
});
|
JavaScript
| 0 |
@@ -3879,37 +3879,24 @@
/**%0A%09 *
-If a viewport of your
+Check if
device
@@ -3890,32 +3890,35 @@
ck if device is
+in
portrait mode, t
@@ -3918,36 +3918,8 @@
mode
-, this method returns %22true%22
%0A%09 *
@@ -3932,19 +3932,8 @@
%EB%8B%B9 %EA%B8%B0%EA%B8%B0
-%EC%9D%98 viewport
%EA%B0%80 po
@@ -3947,11 +3947,16 @@
%EC%A7%81%EB%B0%A9%ED%96%A5)
-%EC%9D%B4%EB%9D%BC%EB%A9%B4
+ %EB%AA%A8%EB%93%9C%EC%9D%BC %EA%B2%BD%EC%9A%B0,
tru
@@ -4050,29 +4050,16 @@
//
-If a viewport of your
+Check if
dev
@@ -4065,16 +4065,19 @@
vice is
+in
portrait
@@ -4085,37 +4085,8 @@
mode
-, this method returns %22true%22.
%0A%09*/
|
21ba8a3eab95e05fa8041ca04254247e1cce3a44
|
Fix #445 IE11 error with Number constructor
|
lib/modules/fields/type.js
|
lib/modules/fields/type.js
|
import _ from 'lodash';
import Validators from '../validators/validators.js';
const typeDefinitionPattern = {
name: String,
class: Match.Any,
validate: Match.Optional(Function),
cast: Match.Optional(Function),
raw: Match.Optional(Function)
};
const enumDefinitionPattern = {
name: String,
options: Object
};
class Type {
constructor(definition) {
check(definition, typeDefinitionPattern);
this.name = definition.name;
this.class = definition.class;
if (_.has(definition, 'validate')) {
this.validate = definition.validate;
}
if (_.has(definition, 'cast')) {
this.cast = definition.cast;
}
if (_.has(definition, 'raw')) {
this.raw = definition.raw;
}
}
validate(doc, fieldName) {
return true;
}
static create(definition) {
let type = new Type(definition);
this.types[type.name] = type;
}
static get(name) {
return this.types[name];
}
static has(name) {
return _.has(this.types, name);
}
static find(Class) {
return _.find(this.types, (type) => {
return type.class === Class;
});
}
};
Type.types = {};
export default Type;
|
JavaScript
| 0.000001 |
@@ -1091,18 +1091,38 @@
lass
- === Class
+.prototype === Class.prototype
;%0A
|
9815a45757ef665a7d7f1877049a4da0af66207f
|
Change welcome messsage
|
server.js
|
server.js
|
const Telegraf = require('telegraf');
const express = require('express');
const decrypt = require('./src/decrypt');
const app = new Telegraf(process.env.BOT_TOKEN);
app.command('start', (ctx) => {
console.log('start', ctx.from);
ctx.reply('Welcome!');
});
app.on('text', (ctx) => {
console.log(ctx.message);
var reply = decrypt(ctx.message.text);
ctx.reply('👍: ' + reply);
});
app.startPolling();
const web = express(); // needed for Heroku not to consider app failed
web.set('port', (process.env.PORT || 5000));
web.get('/', function(request, response) {
response.send('Hello, Heroku!\n\nThis response is just to make Heroku happy.')
});
web.listen(web.get('port'), function() {
console.log('Node app is running on port', web.get('port'));
});
|
JavaScript
| 0 |
@@ -244,15 +244,46 @@
ly('
-Welcome
+This machine has no brain use your own
!');
|
3b8a9cf9f215409302f3da290e7b60885387875f
|
Fix migration for tests
|
server/migrations/20171221080916-drop-mammals-fields.js
|
server/migrations/20171221080916-drop-mammals-fields.js
|
'use strict'
const Promise = require('bluebird')
module.exports = {
up: (queryInterface, Sequelize) => {
return Promise
.all([
queryInterface.addColumn('FormMammals', 'L', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'C', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'A', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'Pl', Sequelize.FLOAT)
])
.then(function () {
if (queryInterface.sequelize.options.dialect !== 'postgres') return
return queryInterface.sequelize.query('UPDATE "FormMammals" SET "L"="sCLL", "C"="mPLLcdC", "A"="mCWA", "Pl"="hLcapPl"')
})
.then(function () {
return Promise.all([
queryInterface.removeColumn('FormMammals', 'sCLL'),
queryInterface.removeColumn('FormMammals', 'mPLLcdC'),
queryInterface.removeColumn('FormMammals', 'mCWA'),
queryInterface.removeColumn('FormMammals', 'hLcapPl'),
queryInterface.removeColumn('FormMammals', 'sqVentr'),
queryInterface.removeColumn('FormMammals', 'sqCaud'),
queryInterface.removeColumn('FormMammals', 'sqDors'),
queryInterface.removeColumn('FormMammals', 'tempCloaca')
])
})
},
down: (queryInterface, Sequelize) => {
return Promise
.all([
queryInterface.addColumn('FormMammals', 'sCLL', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'mPLLcdC', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'mCWA', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'hLcapPl', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'sqVentr', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'sqCaud', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'sqDors', Sequelize.FLOAT),
queryInterface.addColumn('FormMammals', 'tempCloaca', Sequelize.FLOAT)
])
.then(function () {
if (queryInterface.sequelize.options.dialect !== 'postgres') return
return queryInterface.sequelize.query('UPDATE "FormMammals" SET "sCLL"="L", "mPLLcdC"="C", "mCWA"="A", "hLcapPl"="Pl"')
})
.then(function () {
return Promise.all([
queryInterface.removeColumn('FormMammals', 'L'),
queryInterface.removeColumn('FormMammals', 'C'),
queryInterface.removeColumn('FormMammals', 'A'),
queryInterface.removeColumn('FormMammals', 'Pl')
])
})
}
}
|
JavaScript
| 0.000002 |
@@ -684,32 +684,108 @@
n(function () %7B%0A
+ if (queryInterface.sequelize.options.dialect !== 'postgres') return%0A
return P
@@ -2286,32 +2286,108 @@
n(function () %7B%0A
+ if (queryInterface.sequelize.options.dialect !== 'postgres') return%0A
return P
|
3eabaf04b469de47043df39de8a4c643974a1be7
|
Add warnings for unconfigured repos
|
lib/messages.js
|
lib/messages.js
|
var users = require('./users');
var repos = require('./repos');
exports.assignees = function(pullRequest, repo) {
if (!pullRequest) {
return [];
}
if (pullRequest.assignees) {
return pullRequest.assignees.map(function(a) {
return users.slackUserRef(a.login, repo);
});
} else if (pullRequest.assignee) { // older api -- github enterprise
return [ users.slackUserRef(pullRequest.assignee.login, repo) ];
}
return [];
}
exports.assigneesStr = function(pullRequest, repo) {
return exports.assignees(pullRequest, repo).join(', ');
}
exports.sendToAll = function(slack, msg, attachments, item, repo, sender) {
if (repo) {
msg = msg + ' (<' + repo.html_url + '|' + repo.full_name + '>)';
// send to default channel only if configured
var repoChannel = repos.getChannel(repo);
if (repoChannel) {
slack.send({
text: msg,
attachments: attachments,
channel: repoChannel,
});
}
}
var slackbots = exports.assignees(item, repo);
if (item.user) {
var owner = users.slackUserRef(item.user.login, repo);
if (slackbots.indexOf(owner) < 0) {
slackbots.push(owner);
}
}
// make sure we do not send private message to author
if (sender) {
var author = users.slackUserRef(sender.login, repo);
var authorIndex = slackbots.indexOf(author);
if (authorIndex >= 0) {
slackbots.splice(authorIndex, 1);
}
}
// send direct messages
slackbots.forEach(function(name) {
slack.send({
text: msg,
attachments: attachments,
channel: name,
});
});
}
|
JavaScript
| 0 |
@@ -58,16 +58,42 @@
pos');%0A%0A
+var g_warned_repos = %7B%7D;%0A%0A
exports.
@@ -1079,23 +1079,320 @@
%7D
+ else %7B%0A if (!g_warned_repos%5Brepo.html_url%5D) %7B%0A console.warn(%22Warning: No repo configured for '%22 + repo.html_url + %22'%22);%0A g_warned_repos%5Brepo.html_url%5D = true;%0A %7D%0A %7D%0A %7D else %7B%0A console.error(%22%60sendToAll%60 called without a repo!%22);
%0A %7D
-%0A
%0A%0A va
|
a1515bda7c839e511e04b99b20870bae3e3ab87a
|
Add exceptions to spaced-comment rule
|
rules/stylistic-issues.js
|
rules/stylistic-issues.js
|
/* eslint no-magic-numbers: 0 */
'use strict';
module.exports = {
rules: {
'array-bracket-spacing': [2, 'never'],
'block-spacing': [2, 'always'],
'brace-style': [2, 'stroustrup', {allowSingleLine: false}],
'camelcase': [2, {properties: 'always'}],
'comma-spacing': [2, {before: false, after: true}],
'comma-style': [2, 'last'],
'computed-property-spacing': [2, 'never'],
'consistent-this': [2, 'self'],
'eol-last': 2,
'func-names': 0,
'func-style': 0,
'id-length': [2, {
min: 2,
max: 35,
properties: 'always',
exceptions: ['_', 'i']
}],
'id-match': 0,
'indent': [2, 2],
'jsx-quotes': [2, 'prefer-double'],
'key-spacing': [2, {beforeColon: false, afterColon: true}],
'linebreak-style': [2, 'unix'],
'lines-around-comment': [2, {
beforeBlockComment: true,
afterBlockComment: false,
beforeLineComment: true,
afterLineComment: false,
allowBlockStart: true,
allowBlockEnd: false,
allowObjectStart: true,
allowObjectEnd: false,
allowArrayStart: true,
allowArrayEnd: false
}],
'max-depth': [2, 3],
'max-len': [2, 80, 4],
'max-nested-callbacks': [2, 3],
'max-params': [2, 4],
'max-statements': [2, 25],
'new-cap': [2, {newIsCap: true, capIsNew: true}],
'new-parens': 2,
'newline-after-var': 0,
'no-array-constructor': 2,
'no-bitwise': 2,
'no-continue': 2,
'no-inline-comments': 0,
'no-lonely-if': 2,
'no-mixed-spaces-and-tabs': 2,
'no-multiple-empty-lines': [2, {max: 1, maxEOF: 1}],
'no-negated-condition': 2,
'no-nested-ternary': 2,
'no-new-object': 2,
'no-plusplus': [2, {allowForLoopAfterthoughts: true}],
'no-restricted-syntax': [2, 'WithStatement'],
'no-spaced-func': 2,
'no-ternary': 0,
'no-trailing-spaces': 2,
'no-underscore-dangle': 2,
'no-unneeded-ternary': 2,
'object-curly-spacing': [2, 'never'],
'one-var': [2, 'never'],
'operator-assignment': [2, 'always'],
'operator-linebreak': [2, 'after'],
'padded-blocks': [2, 'never'],
'quote-props': [2, 'consistent-as-needed', {keywords: true}],
'quotes': [2, 'single', 'avoid-escape'],
'require-jsdoc': 0,
'semi-spacing': [2, {before: false, after: true}],
'semi': [2, 'always'],
'sort-vars': [2, {ignoreCase: false}],
'space-after-keywords': [2, 'always'],
'space-before-blocks': 2,
'space-before-function-paren': [2, 'never'],
'space-before-keywords': [2, 'always'],
'space-in-parens': [2, 'never'],
'space-infix-ops': [2, {int32Hint: false}],
'space-return-throw-case': 2,
'space-unary-ops': [2, {words: true, nonwords: false}],
'spaced-comment': [2, 'always'],
'wrap-regex': 2
}
};
|
JavaScript
| 0.000001 |
@@ -2743,32 +2743,65 @@
t': %5B2, 'always'
+, %7B'exceptions': %5B'+', '-', '='%5D%7D
%5D,%0A 'wrap-reg
|
73f5b31dc69d179a93ea90f52f0edfcca5d85382
|
Add separate source column to payments export
|
app/scripts/services/PaymentsViewService.js
|
app/scripts/services/PaymentsViewService.js
|
'use strict';
angular.module('confRegistrationWebApp')
.service('PaymentsViewService', function PaymentsViewService(ConferenceHelper, U, $filter) {
this.getTable = function (conference, registrations) {
var table = [];
var header = getHeader();
table.push(header);
var rows = getRows(conference, registrations);
// sort rows by last name
U.sortArrayByIndex(rows, _.findIndex(header, function (string) {
return angular.equals(string, 'Last');
}));
table.push.apply(table, rows);
return table;
};
var getHeader = function () {
var header = [];
header.push('First');
header.push('Last');
header.push('Payment');
header.push('Type');
header.push('Date');
header.push('Description');
return header;
};
var getRows = function (conference, registrations) {
var rows = [];
var blocks = ConferenceHelper.getPageBlocks(conference.registrationPages);
registrations.forEach(function (registration) {
if(!registration.completed) {
return;
}
var name;
if(angular.isDefined(registration.registrants[0])) {
name = ConferenceHelper.getRegistrantName(registration.registrants[0].answers, blocks);
}
if (registration.pastPayments.length > 0) {
angular.forEach(registration.pastPayments, function (payment) {
var row = [];
row.push.apply(row, name);
row.push.apply(row, ['"' + $filter('moneyFormat')(payment.amount) + '"']);
if(payment.paymentType === 'CREDIT_CARD') {
row.push(U.getValue('Credit Card **' + payment.creditCard.lastFourDigits));
} else if(payment.paymentType === 'CHECK') {
row.push(U.getValue('Check #' + payment.check.checkNumber));
} else if(payment.paymentType === 'SCHOLARSHIP') {
row.push(U.getValue('Scholarship from: ' + payment.scholarship.source));
} else if(payment.paymentType === 'TRANSFER') {
row.push(U.getValue('Transfer from: ' + payment.transfer.source));
} else if(payment.paymentType === 'CASH') {
row.push(U.getValue('Cash'));
} else if(payment.paymentType === 'CREDIT_CARD_REFUND') {
row.push(U.getValue('Credit Card Refund **' + payment.creditCard.lastFourDigits));
} else if(payment.paymentType === 'REFUND') {
row.push(U.getValue('Refund'));
}
row.push(U.getDate(payment.transactionDatetime));
row.push(U.getValue(payment.description));
rows.push(row);
});
}
});
return rows;
};
}
);
|
JavaScript
| 0 |
@@ -735,24 +735,53 @@
sh('Type');%0A
+ header.push('Source');%0A
header
@@ -1996,45 +1996,9 @@
ship
- from: ' + payment.scholarship.source
+'
));%0A
@@ -2096,50 +2096,25 @@
ue('
-Transfer from: ' + payment.transfer.source
+Account Transfer'
));%0A
@@ -2432,32 +2432,32 @@
=== 'REFUND') %7B%0A
-
@@ -2494,32 +2494,349 @@
;%0A %7D%0A
+ if(payment.paymentType === 'SCHOLARSHIP') %7B%0A row.push(U.getValue(payment.scholarship.source));%0A %7D else if(payment.paymentType === 'TRANSFER') %7B%0A row.push(U.getValue(payment.transfer.source));%0A %7D else %7B%0A row.push(U.getValue(' '));%0A %7D%0A
row.
|
7f54aa78cf82d7f150d0894c82147fff80f8bbbf
|
Use urls instead of url for iceServers
|
server.js
|
server.js
|
import express from 'express';
import http from 'http';
import serveStatic from 'serve-static';
import path from 'path';
import SocketIO from 'socket.io';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackConfig from './webpack.config.babel';
import axios from 'axios';
import config from 'config';
const googleStunServers = [
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'stun:stun1.l.google.com:19302' },
{ url: 'stun:stun2.l.google.com:19302' },
{ url: 'stun:stun3.l.google.com:19302' },
{ url: 'stun:stun4.l.google.com:19302' }
];
const respokeAppSecret = config.has('respoke.appSecret') ?
config.get('respoke.appSecret') : null;
if (!respokeAppSecret) {
console.error('No respoke appSecret configured. TURN will not be available.');
}
const app = express();
const server = http.createServer(app);
const io = new SocketIO(server);
app.use(webpackMiddleware(webpack(webpackConfig)));
app.use(serveStatic(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
console.log(`${socket.id} connected`);
io.emit('join', socket.id);
socket.on('disconnect', () => {
console.log(`${socket.id} disconnected`);
io.emit('leave', socket.id);
});
socket.on('signal', (signal) => {
console.log(`${socket.id} sending ${signal.type} signal to ${signal.to}`);
signal.from = socket.id;
io.to(signal.to).emit('signal', signal);
});
socket.on('need-turn-servers', (callback) => {
Promise.resolve().then(() => {
if (!respokeAppSecret) {
return [];
}
return axios.get(`https://api.respoke.io/v1/turn?endpointId=${socket.id}`, {
headers: { 'App-Secret': respokeAppSecret }
}).then((response) => {
if (!response.data.uris || !Array.isArray(response.data.uris)) {
console.error('No respoke turn servers available', response.data);
return [];
}
return response.data.uris.map(uri => {
return {
url: uri,
username: response.data.username,
credential: response.data.password
};
});
});
}).then((respokeServers) => {
const servers = [ ...googleStunServers, ...respokeServers ];
console.log('Sending STUN/TURN servers', servers);
callback(servers);
}).catch((err) => {
console.error('Error retrieving respoke turn servers', err);
callback([]);
});
});
});
server.listen(3000, () => {
console.log('listening at http://localhost:3000');
});
|
JavaScript
| 0.000001 |
@@ -374,18 +374,23 @@
s =
-%5B
+%7B
%0A
- %7B
url
-:
+s: %5B%0A
'st
@@ -412,36 +412,29 @@
e.com:19302'
- %7D
,%0A
-%7B url:
+
'stun:stun1
@@ -449,36 +449,29 @@
e.com:19302'
- %7D
,%0A
-%7B url:
+
'stun:stun2
@@ -486,36 +486,29 @@
e.com:19302'
- %7D
,%0A
-%7B url:
+
'stun:stun3
@@ -531,20 +531,13 @@
302'
- %7D
,%0A
-%7B url:
+
'st
@@ -568,12 +568,14 @@
302'
- %7D%0A%5D
+%0A %5D%0A%7D
;%0A%0Ac
@@ -1918,61 +1918,10 @@
urn
-response.data.uris.map(uri =%3E %7B%0A return %7B%0A
+%7B%0A
@@ -1933,17 +1933,31 @@
url
+s
:
+response.data.
uri
+s
,%0A
-
@@ -2006,18 +2006,16 @@
-
credenti
@@ -2053,15 +2053,11 @@
-
%7D;%0A
-
@@ -2062,26 +2062,16 @@
%7D);%0A
- %7D);%0A
%7D).t
@@ -2120,19 +2120,16 @@
ers = %5B
-...
googleSt
@@ -2143,11 +2143,8 @@
rs,
-...
resp
|
02a0f1c89712b505e21b965a786e5f9dbf753785
|
use moneyFormat
|
app/scripts/services/PaymentsViewService.js
|
app/scripts/services/PaymentsViewService.js
|
'use strict';
angular.module('confRegistrationWebApp')
.service('PaymentsViewService', function PaymentsViewService(ConferenceHelper, U) {
this.getTable = function (conference, registrations) {
var table = [];
var header = getHeader();
table.push(header);
var rows = getRows(conference, registrations);
// sort rows by last name
U.sortArrayByIndex(rows, _.findIndex(header, function (string) {
return angular.equals(string, 'Last');
}));
table.push.apply(table, rows);
return table;
};
var getHeader = function () {
var header = [];
header.push('First');
header.push('Last');
header.push('Payment');
header.push('Type');
header.push('Date');
header.push('Description');
return header;
};
var getRows = function (conference, registrations) {
var rows = [];
var blocks = ConferenceHelper.getPageBlocks(conference.registrationPages);
registrations.forEach(function (registration) {
if(!registration.completed) {
return;
}
var name;
if(angular.isDefined(registration.registrants[0])) {
name = ConferenceHelper.getRegistrantName(registration.registrants[0].answers, blocks);
}
if (registration.pastPayments.length > 0) {
angular.forEach(registration.pastPayments, function (payment) {
var row = [];
row.push.apply(row, name);
row.push('$' + U.getValue(payment.amount, '0'));
if(payment.paymentType === 'CREDIT_CARD') {
row.push(U.getValue('Credit Card **' + payment.creditCard.lastFourDigits));
} else if(payment.paymentType === 'CHECK') {
row.push(U.getValue('Check #' + payment.check.checkNumber));
} else if(payment.paymentType === 'SCHOLARSHIP') {
row.push(U.getValue('Scholarship from: ' + payment.scholarship.source));
} else if(payment.paymentType === 'TRANSFER') {
row.push(U.getValue('Transfer from: ' + payment.transfer.source));
} else if(payment.paymentType === 'CASH') {
row.push(U.getValue('Cash'));
} else if(payment.paymentType === 'CREDIT_CARD_REFUND') {
row.push(U.getValue('Credit Card Refund **' + payment.creditCard.lastFourDigits));
} else if(payment.paymentType === 'REFUND') {
row.push(U.getValue('Refund'));
}
row.push(U.getDate(payment.transactionDatetime));
row.push(U.getValue(payment.description));
rows.push(row);
});
}
});
return rows;
};
}
);
|
JavaScript
| 0.000002 |
@@ -131,16 +131,25 @@
elper, U
+, $filter
) %7B%0A%0A
@@ -1489,16 +1489,103 @@
name);%0A
+ row.push.apply(row, %5B'%22' + $filter('moneyFormat')(payment.amount) + '%22'%5D);%0A
|
0978b8f9b376f58ad6e4f5522bd1382ae77d4d38
|
Return Buffer instead of String.
|
lib/minidump.js
|
lib/minidump.js
|
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var searchPaths = [
path.resolve(__dirname, '..', 'build', 'Release'),
path.resolve(__dirname, '..', 'build', 'Debug'),
path.resolve(__dirname, '..', 'bin'),
];
function searchCommand(command) {
if (process.platform == 'win32') {
command += '.exe'
var binaryPath = path.join(__dirname, '..', 'deps', 'breakpad', command)
if (fs.existsSync(binaryPath))
return b
} else {
for (var i in searchPaths) {
var binaryPath = path.join(searchPaths[i], command);
if (fs.existsSync(binaryPath))
return binaryPath;
}
}
}
function execute(command, args, callback) {
var stderr = '';
var stdout = '';
var child = spawn(command, args);
child.stdout.on('data', function(chunk) { stdout += chunk; });
child.stderr.on('data', function(chunk) { stderr += chunk; });
child.on('close', function(code) {
if (code != 0)
callback(stderr);
else
callback(null, stdout);
});
}
var globalSymbolPaths = [];
module.exports.addSymbolPath = Array.prototype.push.bind(globalSymbolPaths);
module.exports.walkStack = function(minidump, symbolPaths, callback) {
if (!callback) {
callback = symbolPaths;
symbolPaths = [];
}
var stackwalk = searchCommand('minidump_stackwalk');
if (!stackwalk) {
callback('Unable to find the "minidump_stackwalk"');
return;
}
args = [minidump].concat(symbolPaths, globalSymbolPaths)
execute(stackwalk, args, callback);
}
module.exports.dumpSymbol = function(binary, callback) {
var dumpsyms = searchCommand('dump_syms');
if (!dumpsyms) {
callback('Unable to find the "dump_syms"');
return;
}
execute(dumpsyms, ['-r', '-c', binary], callback)
}
|
JavaScript
| 0.000001 |
@@ -714,35 +714,57 @@
std
-err = '';%0A var stdout = ''
+out = new Buffer(0);%0A var stderr = new Buffer(0)
;%0A
@@ -840,24 +840,28 @@
chunk) %7B
+%0A
stdout
+= chunk
@@ -852,25 +852,51 @@
stdout
-+
=
-chunk;
+Buffer.concat(%5Bstdout, chunk%5D);%0A
%7D);%0A c
@@ -935,24 +935,28 @@
chunk) %7B
+%0A
stderr
+= chunk
@@ -951,17 +951,43 @@
err
-+
=
-chunk;
+Buffer.concat(%5Bstderr, chunk%5D);%0A
%7D);
|
643038eeaac9e9d8ac18a4e075c886585f32d568
|
Add chromedriver for Windows & Linux
|
script/lib/download-chromedriver.js
|
script/lib/download-chromedriver.js
|
'use strict'
const assert = require('assert')
const downloadFileFromGithub = require('./download-file-from-github')
const fs = require('fs-extra')
const path = require('path')
const semver = require('semver')
const spawnSync = require('./spawn-sync')
const syncRequest = require('sync-request')
const CONFIG = require('../config')
module.exports = function () {
if (process.platform === 'darwin') {
// Chromedriver is only distributed with the first patch release for any given
// major and minor version of electron.
const electronVersion = semver.parse(CONFIG.appMetadata.electronVersion)
const electronVersionWithChromedriver = `${electronVersion.major}.${electronVersion.minor}.0`
const electronAssets = getElectronAssetsForVersion(electronVersionWithChromedriver)
const chromedriverAssets = electronAssets.filter(e => /chromedriver.*darwin-x64/.test(e.name))
assert(chromedriverAssets.length === 1, 'Found more than one chrome driver asset to download!')
const chromedriverAsset = chromedriverAssets[0]
const chromedriverZipPath = path.join(CONFIG.electronDownloadPath, `electron-${electronVersionWithChromedriver}-${chromedriverAsset.name}`)
if (!fs.existsSync(chromedriverZipPath)) {
downloadFileFromGithub(chromedriverAsset.url, chromedriverZipPath)
}
const chromedriverDirPath = path.join(CONFIG.electronDownloadPath, 'chromedriver')
unzipPath(chromedriverZipPath, chromedriverDirPath)
} else {
console.log('Skipping Chromedriver download because it is used only on macOS'.gray)
}
}
function getElectronAssetsForVersion (version) {
const releaseURL = `https://api.github.com/repos/electron/electron/releases/tags/v${version}`
const response = syncRequest('GET', releaseURL, {'headers': {'User-Agent': 'Atom Build'}})
if (response.statusCode === 200) {
const release = JSON.parse(response.body)
return release.assets.map(a => { return {name: a.name, url: a.browser_download_url} })
} else {
throw new Error(`Error getting assets for ${releaseURL}. HTTP Status ${response.statusCode}.`)
}
}
function unzipPath (inputPath, outputPath) {
if (fs.existsSync(outputPath)) {
console.log(`Removing "${outputPath}"`)
fs.removeSync(outputPath)
}
console.log(`Unzipping "${inputPath}" to "${outputPath}"`)
spawnSync('unzip', [inputPath, '-d', outputPath])
}
|
JavaScript
| 0 |
@@ -362,49 +362,8 @@
) %7B%0A
- if (process.platform === 'darwin') %7B%0A
//
@@ -439,18 +439,16 @@
y given%0A
-
// maj
@@ -481,18 +481,16 @@
ectron.%0A
-
const
@@ -556,18 +556,16 @@
ersion)%0A
-
const
@@ -652,18 +652,16 @@
nor%7D.0%60%0A
-
const
@@ -736,24 +736,118 @@
medriver)%0A
+const chromeDriverMatch = new RegExp(%60%5Echromedriver-v.*-$%7Bprocess.platform%7D-$%7Bprocess.arch%7D%60)%0A
const chro
@@ -894,34 +894,25 @@
=%3E
-/
chrome
-d
+D
river
-.*darwin-x64/
+Match
.tes
@@ -922,18 +922,16 @@
.name))%0A
-
assert
@@ -1020,18 +1020,16 @@
load!')%0A
-
const
@@ -1071,18 +1071,16 @@
ets%5B0%5D%0A%0A
-
const
@@ -1213,18 +1213,16 @@
name%7D%60)%0A
-
if (!f
@@ -1258,18 +1258,16 @@
ath)) %7B%0A
-
down
@@ -1333,17 +1333,13 @@
th)%0A
-
%7D%0A%0A
-
co
@@ -1419,18 +1419,16 @@
river')%0A
-
unzipP
@@ -1477,111 +1477,8 @@
th)%0A
- %7D else %7B%0A console.log('Skipping Chromedriver download because it is used only on macOS'.gray)%0A %7D%0A
%7D%0A%0Af
|
c0a1bcc5a5101413c86df661a043712bafb32f9f
|
clean up
|
lib/parsers/pptx_parser.js
|
lib/parsers/pptx_parser.js
|
var fs = require('fs');
var unzip = require('unzip');
var streamBuffers = require('stream-buffers');
var xpath = require('xpath');
var xmldom = require('xmldom').DOMParser;
var _ = require('underscore');
_.str = require('underscore.string');
_.mixin(_.str.exports());
var select = xpath.useNamespaces(
{
"p": "http://schemas.openxmlformats.org/presentationml/2006/main",
"a": "http://schemas.openxmlformats.org/drawingml/2006/main"
});
var PPTXParser = module.exports = function () {
};
PPTXParser.prototype.parse = function(file, success, error) {
var presentation = { slides : [] };
fs.createReadStream(file).pipe(unzip.Parse())
.on('entry', function(entry){
var filename = entry.path;
var type = entry.type;
if (_(filename).startsWith('ppt/slides/') && _(filename).endsWith('.xml')) {
var slide = { shapes : [] };
slide.index = parseInt(filename.substring('ppt/slides/slide'.length, filename.indexOf('.xml')));
var writableStream = new streamBuffers.WritableStreamBuffer();
writableStream.on('close', function () {
var str = writableStream.getContentsAsString('utf8');
var doc = new xmldom().parseFromString(str);
_.each(select('//p:sld/p:cSld/p:spTree/p:sp', doc), function(shapeNode) {
var shape = { paragraphs:[] };
// read the texts (in the structured way: body->paragraph->run->text)
var bodyNodes = select('p:txBody', shapeNode);
shape.text = "";
if (bodyNodes && bodyNodes.length == 1) {
_.each(select('a:p', bodyNodes[0]), function(paragraphNode) {
var paragraph = { runs : [] };
_.each(select('a:r', paragraphNode), function(runNode) {
var run = { text: select('a:t/text()', runNode).toString() };
paragraph.runs.push(run);
shape.text += run.text;
});
shape.paragraphs.push(paragraph);
});
}
// get the type of the shape
var propertiesNodes = select('./p:nvSpPr/p:nvPr/p:ph', shapeNode);
if (propertiesNodes && propertiesNodes.length == 1) {
shape.type = propertiesNodes[0].getAttribute('type');
if (shape.type === 'ctrTitle') {
slide.title = shape.text;
} else if (shape.type === 'subTitle') {
slide.subTitle = shape.text;
}
}
slide.shapes.push(shape);
});
presentation.slides.push(slide);
});
entry.pipe(writableStream);
}
})
.on('error', function(err) {
error(err);
})
.on('close', function() {
success(presentation);
});
}
|
JavaScript
| 0.000001 |
@@ -1340,16 +1340,25 @@
raphs:%5B%5D
+, text:%22%22
%7D;%0A%0A
@@ -1499,37 +1499,8 @@
e);%0A
- shape.text = %22%22;%0A
|
a21468561bcf0d49992affdd2831d2aa0c43f01a
|
Update uniques
|
formatter.js
|
formatter.js
|
var dropdownPrep = function(){
var dropdown = document.getElementById("lang");
var option;
for (var lang in l10n){
option = document.createElement("option");
option.innerHTML = l10n[lang];
option.value = lang;
dropdown.appendChild(option);
}
}
var render = function(){
var results = document.getElementsByClassName('finish');
for (var i = 0; i < results.length; i++){
results[i].style.display = 'block';
}
var dropdown = document.getElementById("lang");
var lang = dropdown.value;
var final = {};
final[lang] = {};
final[lang]['language'] = dropdown.selectedOptions[0].text;
final[lang]["translator"] = document.getElementById('translator').value.replace(/[\"]/g, "\\\"");
var unique1 = document.getElementById('unique1').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>";
var unique2 = document.getElementById('unique2').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
var unique3 = document.getElementById('unique3').value.replace(/[\"]/g, "\\\"") + "<br/><br/>";
var unique4 = document.getElementById('unique4').value.replace(/[\"]/g, "\\\"") + "<br/>";
final[lang]["unique"] = unique1 + unique2 + unique3 + unique4;
var link = document.getElementById('link').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>";
var age = document.getElementById('age').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>";
var appropriate = document.getElementById('appropriate').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/>";
var patience = document.getElementById('patience').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>";
var whatIsSDS = document.getElementById('whatIsSDS').value.replace(/[\"]/g, "\\\"") + "\n";
var selected = " " + document.getElementById('selected').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/projects/55738732/\">" + "https://scratch.mit.edu/projects/55738732/" + "</a>" + "\n";
var ask = document.getElementById('ask').value.replace(/[\"]/g, "\\\"") + "\n" + "<br/><br/>";
var idea = document.getElementById('idea').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/studios/93627/\">" + "https://scratch.mit.edu/studios/93627/" + "</a>" + "\n" + "<br/><br/>";
var wiki = document.getElementById('wiki').value.replace(/[\"]/g, "\\\"") + " <a href=\"http://wiki.scratch.mit.edu/wiki/SDS/\">" + "http://wiki.scratch.mit.edu/wiki/SDS/" + "</a>" + "\n" + "<br/><br/>";
var account = document.getElementById('account').value.replace(/[\"]/g, "\\\"") + " <a href=\"https://scratch.mit.edu/users/SDS-Updates/\">" + "@SDS-Updates" + "</a>" + "\n" + "<br/><br/>";
var thumbnail = document.getElementById('thumbnail').value.replace(/[\"]/g, "\\\"");
final[lang]["standard"] = link + age + appropriate + patience + whatIsSDS + selected + ask + idea + wiki + account + thumbnail;
var curators = document.getElementById('curatorsp').value.replace(/[\"]/g, "\\\"");
var result = document.getElementById('result');
final[lang]["curators"] = curators;
result.value = JSON.stringify(final,null,2).slice(2,-2) + ",";
console.log(JSON.stringify(final,null,2).slice(2,-2) + ",");
};
document.onkeyup = render;
|
JavaScript
| 0 |
@@ -1005,106 +1005,8 @@
%22) +
- %22%3Cbr/%3E%3Cbr/%3E%22;%0A var unique4 = document.getElementById('unique4').value.replace(/%5B%5C%22%5D/g, %22%5C%5C%5C%22%22) +
%22%3Cb
@@ -1068,18 +1068,8 @@
que3
- + unique4
;%0A%0A
|
88940e2e5ee75484aed99b984fa256921322eb63
|
Convert to angular’s $interval
|
lib/periodical_executor.js
|
lib/periodical_executor.js
|
(function(){
function PeriodicalExecutor(frequency, callback) {
var currentlyRunning = false;
this.tick = function() {
if (!currentlyRunning) {
try {
currentlyRunning = true;
callback();
} finally {
currentlyRunning = false;
}
}
};
this.frequency = frequency;
this.start();
}
PeriodicalExecutor.prototype.start = function() {
if (!this.timer) {
this.timer = setInterval(this.tick, this.frequency);
}
};
PeriodicalExecutor.prototype.stop = function() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
};
angular
.module('PeriodicalExecutor', [])
.value('PeriodicalExecutor', PeriodicalExecutor);
})();
|
JavaScript
| 0.999997 |
@@ -1,16 +1,97 @@
-(function()%7B
+angular.module('PeriodicalExecutor', %5B%5D).factory('PeriodicalExecutor', function($interval) %7B%0A
%0A f
@@ -541,12 +541,10 @@
r =
-setI
+$i
nter
@@ -670,20 +670,23 @@
-clearInterva
+$interval.cance
l(th
@@ -739,88 +739,14 @@
%0A%0A
-angular%0A .module('PeriodicalExecutor', %5B%5D)%0A .value('PeriodicalExecutor',
+return
Per
@@ -764,13 +764,10 @@
utor
-)
;%0A%7D)
-()
;%0A
|
a213ce0ba415bea139154c766772a8e07bfc739a
|
Add plugin.tunnelRulesServer
|
lib/plugins/load-plugin.js
|
lib/plugins/load-plugin.js
|
var http = require('http');
var util = require('util');
var path = require('path');
var ca = require('../https/ca');
var Storage = require('../rules/storage');
var MAX_PORT = 60000;
var curPort = 45000;
function getServer(callback) {
if (curPort > MAX_PORT) {
curPort = 40000;
}
var server = http.createServer();
var port = curPort++;
var next = function() {
getServer(callback);
};
server.on('error', next);
server.listen(port, function() {
server.removeListener('error', next);
callback(server, port);
});
}
module.exports = function(options, callback) {
options.getRootCAFile = ca.getRootCAFile;
options.createCertificate = ca.createCertificate;
options.storage = new Storage(path.join(options.config.DATA_DIR, '.plugins', options.name));
if (options.debugMode) {
var cacheLogs = [];
console.log = function() {
var msg = util.format.apply(this, arguments);
if (cacheLogs) {
cacheLogs.push(msg);
} else {
process.sendData({
type: 'console.log',
message: msg
});
}
};
process.on('data', function(data) {
if (cacheLogs && data && data.type == 'console.log' && data.status == 'ready') {
var _cacheLogs = cacheLogs;
cacheLogs = null;
_cacheLogs.forEach(function(msg) {
process.sendData({
type: 'console.log',
message: msg
});
});
}
});
}
var execPlugin = require(options.value);
var port, uiPort, rulesPort, resRulesPort, statusPort;
var count = 0;
var callbackHandler = function() {
if (--count <= 0) {
callback(null, {
port: port,
uiPort: uiPort,
rulesPort: rulesPort,
resRulesPort: resRulesPort,
statusPort: statusPort
});
}
};
var startServer = execPlugin.server || execPlugin;
if (typeof startServer == 'function') {
++count;
getServer(function(server, _port) {
startServer(server, options);
port = _port;
callbackHandler();
});
}
var startUIServer = execPlugin.uiServer || execPlugin.innerServer || execPlugin.internalServer;
if (typeof startUIServer == 'function') {
++count;
getServer(function(server, _port) {
startUIServer(server, options);
uiPort = _port;
callbackHandler();
});
}
var startRulesServer = execPlugin.rulesServer || execPlugin.reqRulesServer;
if (typeof startRulesServer == 'function') {
++count;
getServer(function(server, _port) {
startRulesServer(server, options);
rulesPort = _port;
callbackHandler();
});
}
var startResRulesServer = execPlugin.resRulesServer;
if (typeof startResRulesServer == 'function') {
++count;
getServer(function(server, _port) {
startResRulesServer(server, options);
resRulesPort = _port;
callbackHandler();
});
}
var startStatusServer = execPlugin.statusServer || execPlugin.stateServer;
if (typeof startStatusServer == 'function') {
++count;
getServer(function(server, _port) {
startStatusServer(server, options);
statusPort = _port;
callbackHandler();
});
}
if (!count) {
callbackHandler();
}
};
|
JavaScript
| 0 |
@@ -1441,16 +1441,33 @@
atusPort
+, tunnelRulesPort
;%0A%09var c
@@ -1674,16 +1674,54 @@
atusPort
+,%0A%09%09%09%09tunnelRulesPort: tunnelRulesPort
%0A%09%09%09%7D);%0A
@@ -3014,16 +3014,282 @@
);%0A%09%7D%0A%09%0A
+%09var startTunnelRulesServer = execPlugin.tunnelRulesServer;%0A%09if (typeof startTunnelRulesServer == 'function') %7B%0A%09%09++count;%0A%09%09getServer(function(server, _port) %7B%0A%09%09%09startTunnelRulesServer(server, options);%0A%09%09%09tunnelRulesPort = _port;%0A%09%09%09callbackHandler();%0A%09%09%7D);%0A%09%7D%0A%09%0A
%09if (!co
|
779b16c7d2260ca5812f11c27502c8b188c139d9
|
allow x-access-token authorization header
|
server.js
|
server.js
|
/* eslint-disable no-console */
/* eslint import/no-unresolved: 0 */
import http from 'http';
import express from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import dotenv from 'dotenv';
import routes from './server/app/routes';
dotenv.config();
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const port = process.env.PORT || 3000;
const httpServer = http.createServer(app);
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
// Endpoints route
app.use('/', routes.userRoutes);
app.use('/', routes.documentRoutes);
app.use('/roles', routes.roleRoutes);
// Setup a default catch-all route that sends back a welcome message.
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to Document Management System!',
}));
if (!module.parent) {
httpServer.listen(port, () => console.log(`Server started at port ${port}`));
}
// export app for testing
export default app;
|
JavaScript
| 0.000001 |
@@ -781,16 +781,32 @@
dentials
+, x-access-token
');%0A re
|
bbdbee8dc1bcebfa7051cd67a6d42f70e82441ec
|
update middleware for localhost
|
server.js
|
server.js
|
var express = require('express');
var app = express();
const PORT = process.env.PORT || 3000;
app.use(function(req, res, next) {
if (req.headers['x-forwarded-proto'] === 'http') {
next();
} else {
res.redirect('http://' + req.hostname + req.url);
}
});
app.use(express.static('public'));
app.listen(PORT, function() {
console.log('Express server is up on port ' + PORT);
});
|
JavaScript
| 0.000001 |
@@ -178,42 +178,14 @@
http
+s
') %7B%0A
- next();%0A %7D else %7B%0A
@@ -238,16 +238,45 @@
q.url);%0A
+ %7D else %7B%0A next();%0A
%7D%0A%7D)
|
5d84f54f0e0a32c5eaa9dd963f98aab1e21a679b
|
Set isWebService property on process object to be able to distinguish web service process from application process
|
server.js
|
server.js
|
'use strict';
require('./processRequire.js');
var path = require('path');
var async = require('async');
var nopt = require('nopt');
var openVeoAPI = require('@openveo/api');
var ClientProvider = process.require('app/server/providers/ClientProvider.js');
var RoleProvider = process.require('app/server/providers/RoleProvider.js');
var TokenProvider = process.require('app/server/providers/TokenProvider.js');
var UserProvider = process.require('app/server/providers/UserProvider.js');
var conf = process.require('conf.json');
var TaxonomyProvider = openVeoAPI.TaxonomyProvider;
var applicationStorage = openVeoAPI.applicationStorage;
var configurationDirectoryPath = path.join(openVeoAPI.fileSystem.getConfDir(), 'core');
var loggerConfPath = path.join(configurationDirectoryPath, 'loggerConf.json');
var serverConfPath = path.join(configurationDirectoryPath, 'serverConf.json');
var databaseConfPath = path.join(configurationDirectoryPath, 'databaseConf.json');
var loggerConf;
var serverConf;
var databaseConf;
var migrationProcess = process.require('app/server/migration/migrationProcess.js');
// Process arguments
var knownProcessOptions = {
ws: [Boolean],
serverConf: [String, null],
databaseConf: [String, null],
loggerConf: [String, null]
};
// Parse process arguments
var processOptions = nopt(knownProcessOptions, null, process.argv);
// Load configuration files
try {
loggerConf = require(processOptions.loggerConf || loggerConfPath);
serverConf = require(processOptions.serverConf || serverConfPath);
databaseConf = require(processOptions.databaseConf || databaseConfPath);
} catch (error) {
throw new Error('Invalid configuration file : ' + error.message);
}
var entities = {};
var webServiceScopes = conf['webServiceScopes'] || [];
var server;
if (processOptions['ws']) {
process.logger = openVeoAPI.logger.add('openveo', loggerConf.ws);
var WebServiceServer = process.require('app/server/servers/WebServiceServer.js');
server = new WebServiceServer(serverConf.ws);
} else {
process.logger = openVeoAPI.logger.add('openveo', loggerConf.app);
var ApplicationServer = process.require('app/server/servers/ApplicationServer.js');
server = new ApplicationServer(serverConf.app);
}
// Loaders
var pluginLoader = process.require('app/server/loaders/pluginLoader.js');
var entityLoader = process.require('app/server/loaders/entityLoader.js');
/**
* Executes a plugin function on all plugins in parallel.
*
* @param {String} functionToExecute The name of the function to execute on each plugin
* @param {Function} callback Function to call when it's done with :
* - **Error** An error if something went wrong, null otherwise
*/
function executePluginFunction(functionToExecute, callback) {
var plugins = applicationStorage.getPlugins();
var asyncFunctions = [];
plugins.forEach(function(plugin) {
if (plugin[functionToExecute] && typeof plugin[functionToExecute] === 'function')
asyncFunctions.push(function(callback) {
plugin[functionToExecute](callback);
});
});
if (asyncFunctions.length)
async.parallel(asyncFunctions, callback);
else
callback();
}
async.series([
// Establish a connection to the database
function(callback) {
// Get a Database instance
var db = openVeoAPI.Database.getDatabase(databaseConf);
// Establish connection to the database
db.connect(function(error) {
if (error) {
process.logger.error(error && error.message);
throw new Error(error);
}
applicationStorage.setDatabase(db);
server.onDatabaseAvailable(db);
// Build core entities
var decodedEntities = entityLoader.decodeEntities(process.root + '/', conf['entities']);
if (decodedEntities) {
for (var type in decodedEntities)
entities[type] = new decodedEntities[type]();
}
callback();
});
},
// Load openveo plugins under node_modules directory
function(callback) {
pluginLoader.loadPlugins(path.join(process.root), function(error, plugins) {
// An error occurred when loading plugins
// The server must not be launched, exit process
if (error) {
process.logger.error(error && error.message);
throw new Error(error);
} else {
applicationStorage.setPlugins(plugins);
plugins.forEach(function(loadedPlugin) {
// Found a list of web service scopes for the plugin
if (loadedPlugin.webServiceScopes) {
for (var scopeName in loadedPlugin.webServiceScopes)
webServiceScopes = webServiceScopes.concat(loadedPlugin.webServiceScopes[scopeName]);
}
// Found a list of entities for the plugin
if (loadedPlugin.entities) {
for (var type in loadedPlugin.entities)
entities[type] = new loadedPlugin.entities[type]();
}
server.onPluginLoaded(loadedPlugin);
process.logger.info('Plugin ' + loadedPlugin.name + ' successfully loaded');
});
applicationStorage.setWebServiceScopes(webServiceScopes);
applicationStorage.setEntities(entities);
}
callback();
});
},
// Execute migrations script
function(callback) {
var migrations = server.migrations;
migrationProcess.executeMigrationScript(migrations, callback);
},
// Create core indexes
function(callback) {
var database = openVeoAPI.applicationStorage.getDatabase();
var asyncFunctions = [];
var providers = [
new ClientProvider(database),
new RoleProvider(database),
new TaxonomyProvider(database),
new TokenProvider(database),
new UserProvider(database)
];
providers.forEach(function(provider) {
if (provider.createIndexes) {
asyncFunctions.push(function(callback) {
provider.createIndexes(callback);
});
}
});
async.parallel(asyncFunctions, function(error, results) {
callback(error);
});
},
// Intitializes plugins
function(callback) {
executePluginFunction('init', callback);
},
// Start plugins
function(callback) {
executePluginFunction('start', callback);
},
// Start server
function(callback) {
server.onPluginsLoaded();
server.startServer(callback);
}
],
function(error) {
if (error)
throw error;
});
|
JavaScript
| 0.000001 |
@@ -1801,16 +1801,47 @@
ws'%5D) %7B%0A
+ process.isWebService = true;%0A
proces
|
7d162867c86ae3c2952b167245898d78ee0f1468
|
Change URLs so they can live aside eachother.
|
server.js
|
server.js
|
var express = require('express');
var app = express();
var config = require('./config');
var bodyParser = require('body-parser');
var morgan = require('morgan')
var mongoose = require('mongoose');
var Recording = require('./models/measurement');
var Station = require('./models/station');
var measurements = require('./routes/measurements');
var stations = require('./routes/stations');
mongoose.connect(config.mongodb.url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('combined'))
var router = express.Router();
router.get('/wrm.aspx', measurements.saveMeasurement);
router.get('/measurements', measurements.allMeasurements)
router.get('/stations', stations.findAllStations);
router.get('/stations/:stationId', stations.findOneStation);
router.post('/stations', stations.saveStation);
app.use('', router);
app.listen(3000);
console.log('Listening on port 3000...');
|
JavaScript
| 0 |
@@ -621,16 +621,79 @@
ement);%0A
+router.post('/v2/measurements', measurements.saveMeasurement);%0A
router.g
@@ -697,16 +697,19 @@
r.get('/
+v2/
measurem
@@ -751,32 +751,35 @@
)%0A%0Arouter.get('/
+v2/
stations', stati
@@ -809,24 +809,27 @@
outer.get('/
+v2/
stations/:st
@@ -878,16 +878,19 @@
.post('/
+v2/
stations
@@ -949,17 +949,17 @@
.listen(
-3
+8
000);%0Aco
@@ -991,9 +991,9 @@
ort
-3
+8
000.
@@ -997,8 +997,9 @@
00...');
+%0A
|
2ad795be3ef5a1f9395105454d4beffc2164a0d7
|
change hello
|
server.js
|
server.js
|
var http = require('http')
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('Hello World!')
})
server.listen(process.env.PORT || 80, function() {
console.log('Docker DEMO with Node.js is running.')
})
|
JavaScript
| 0.998574 |
@@ -156,16 +156,20 @@
lo World
+ xxx
!')%0A%7D)%0A%0A
|
91882b80c10ad3cd2d6324993fb90be779dad5af
|
fix - prepare redirect for NGINX redirect update
|
server.js
|
server.js
|
const { join } = require('path');
const express = require('express');
const next = require('next');
const { keyBy } = require('lodash');
const morgan = require('morgan');
const { buildDataset } = require('./build-dataset');
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
function buildAliasesIndex(items) {
return items.reduce((aliasesIndex, item) => {
if (item.aliases) {
item.aliases.forEach(alias => {
aliasesIndex[alias] = item;
});
}
return aliasesIndex;
}, {});
}
app.prepare().then(async () => {
const server = express();
const { summary, apis, services } = await buildDataset();
const apisIndex = keyBy(apis, 'slug');
const servicesIndex = keyBy(services, 'slug');
const apisAliasesIndex = buildAliasesIndex(apis);
if (process.env.NODE_ENV !== 'production') {
server.use(morgan('dev'));
}
server.get('/apis/:apiId.json', (req, res) => {
if (req.params.apiId in apisIndex) {
return res.send(apisIndex[req.params.apiId]);
}
res.sendStatus(404);
});
server.get('/services/:serviceId.json', (req, res) => {
if (req.params.serviceId in servicesIndex) {
return res.send(servicesIndex[req.params.serviceId]);
}
res.sendStatus(404);
});
server.get('/api/v1/api.json', (req, res) => {
res.send(summary);
});
server.get('/api/:apiId', (req, res) => {
const { apiId } = req.params;
// Support des anciennes URL finissant par .html
if (apiId.endsWith('.html')) {
return res.redirect('/api/' + apiId.substring(0, apiId.indexOf('.html')));
}
// Alias
if (apiId in apisAliasesIndex) {
return res.redirect('/api/' + apisAliasesIndex[apiId].slug);
}
return app.render(req, res, '/api', { apiId });
});
server.get('/services/all', (req, res) => {
res.send(services);
});
server.get('/service/:serviceId', (req, res) => {
const { serviceId } = req.params;
// Support des anciennes URL finissant par .html
if (serviceId.endsWith('.html')) {
return res.redirect(
'/service/' + serviceId.substring(0, serviceId.indexOf('.html'))
);
}
return app.render(req, res, '/service', { serviceId });
});
server.get('/apropos', (req, res) => {
return app.render(req, res, '/about');
});
server.use(express.static(join(__dirname, 'public')));
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
|
JavaScript
| 0 |
@@ -1419,32 +1419,282 @@
ummary);%0A %7D);%0A%0A
+ server.get('/signup/api', (req, res) =%3E %7B%0A return res.redirect('/rechercher-api?filter=signup');%0A %7D);%0A%0A server.get('/les-api/:apiId', (req, res) =%3E %7B%0A const %7B apiId %7D = req.params;%0A return app.render(req, res, '/api', %7B apiId %7D);%0A %7D);%0A%0A
server.get('/a
|
c0d86fba0c00c1a5bb9af4ba5dc77f77b1ca0622
|
use template for main page
|
server.js
|
server.js
|
var fs = require('fs');
var https = require('https');
var compression = require('compression');
var express = require('express');
var helmet = require('helmet');
var Moonboots = require('moonboots');
var config = require('getconfig');
var templatizer = require('templatizer');
var oembed = require('oembed');
var async = require('async');
var app = express();
app.use(compression());
app.use(express.static(__dirname + '/public'));
app.use(helmet());
if (config.isDev) {
app.use(helmet.noCache());
}
oembed.EMBEDLY_URL = config.embedly.url || 'https://api.embed.ly/1/oembed';
oembed.EMBEDLY_KEY = config.embedly.key;
var clientApp = new Moonboots({
main: __dirname + '/clientapp/app.js',
templateFile: __dirname + '/clientapp/templates/main.html',
developmentMode: config.isDev,
cachePeriod: 0,
libraries: [
__dirname + '/clientapp/libraries/jquery.js',
__dirname + '/clientapp/libraries/ui.js',
__dirname + '/clientapp/libraries/resampler.js',
__dirname + '/clientapp/libraries/IndexedDBShim.min.js'
],
browserify: {
debug: true
},
stylesheets: [
__dirname + '/public/css/otalk.css'
],
server: app
});
if (config.isDev) {
clientApp.config.beforeBuildJS = function () {
var clientFolder = __dirname + '/clientapp';
templatizer(clientFolder + '/templates',
clientFolder + '/templates.js',
function (err, templates) { console.log(err || 'Success!'); });
};
}
clientApp.on('ready', function () {
console.log('Client app ready');
var pkginfo = JSON.parse(fs.readFileSync(__dirname + '/package.json'));
var manifestTemplate = fs.readFileSync(__dirname + '/clientapp/templates/misc/manifest.cache', 'utf-8');
var cacheManifest = manifestTemplate
.replace('#{version}', pkginfo.version + config.isDev ? ' ' + Date.now() : '')
.replace('#{jsFileName}', clientApp.jsFileName())
.replace('#{cssFileName}', clientApp.cssFileName());
console.log('Cache manifest generated');
app.get('/manifest.cache', function (req, res, next) {
res.set('Content-Type', 'text/cache-manifest');
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
res.send(cacheManifest);
});
app.get('/' + clientApp.jsFileName(),
function (req, res) {
clientApp.jsSource(function (err, js) {
res.set('Content-Type', 'application/javascript').send(js);
});
}
);
app.get('/' + clientApp.cssFileName(),
function (req, res) {
clientApp.cssSource(function (err, css) {
res.set('Content-Type', 'text/css').send(css);
});
}
);
// serves app on every other url
app.get('*', function (req, res) {
res.set('Content-Type', 'text/html; charset=utf-8').send(clientApp.htmlSource());
});
});
var webappManifest = fs.readFileSync('./public/x-manifest.webapp');
app.set('view engine', 'jade');
app.get('/login', function (req, res) {
res.render('login');
});
app.get('/logout', function (req, res) {
res.render('logout');
});
app.get('/oauth/login', function (req, res) {
res.redirect('https://apps.andyet.com/oauth/authorize?client_id=' + config.andyetAuth.id + '&response_type=token');
});
app.get('/oauth/callback', function (req, res) {
res.render('oauthLogin');
});
app.get('/manifest.webapp', function (req, res, next) {
res.set('Content-Type', 'application/x-web-app-manifest+json');
res.send(webappManifest);
});
app.get('/oembed', function (req, res) {
var callback = req.query.callback;
if (req.query.url) {
oembed.fetch(req.query.url, req.query, function (err, result) {
if (err || !result) {
return res.status(500).send();
}
res.status(200);
res.set('Content-Type', oembed.MIME_OEMBED_JSON);
if (callback) {
return res.send(callback + '(' + JSON.stringify(result) + ')');
} else {
return res.send(JSON.stringify(result));
}
});
} else if (req.query.urls) {
var cache = {};
var urls = req.query.urls.split(',');
delete req.query.urls;
async.forEach(urls, function (url, cb) {
oembed.fetch(url, req.query, function (err, result) {
if (err || !result) {
result = {type: 'error'};
}
cache[url] = result;
cb();
});
}, function () {
res.status(200);
var results = [];
urls.forEach(function (url) {
results.push(cache[url]);
});
if (callback) {
res.set('Content-Type', 'application/javascript');
res.send(callback + '(' + JSON.stringify(results) + ')');
} else {
res.set('Content-Type', 'application/json');
res.send(JSON.stringify(results));
}
});
} else {
res.status(400).send();
}
});
app.use(function handleError(err, req, res, next) {
var errorResult = {message: 'Something bad happened :('};
if (config.isDev) {
if (err instanceof Error) {
if (err.message) {
errorResult.message = err.message;
}
if (err.stack) {
errorResult.stack = err.stack;
}
}
}
res.status(500);
res.render('error', errorResult);
});
//https.createServer({
// key: fs.readFileSync(config.http.key),
// cert: fs.readFileSync(config.http.cert)
//}, app).listen(config.http.port);
app.listen(config.http.port);
console.log('demo.stanza.io running at: ' + config.http.baseUrl);
|
JavaScript
| 0 |
@@ -698,72 +698,8 @@
s',%0A
- templateFile: __dirname + '/clientapp/templates/main.html',%0A
@@ -733,28 +733,8 @@
ev,%0A
- cachePeriod: 0,%0A
@@ -2851,32 +2851,403 @@
on (req, res) %7B%0A
+ var html = '';%0A var prefix = clientApp.config.resourcePrefix;%0A var templateFile = __dirname + '/clientapp/templates/main.html';%0A html = fs.readFileSync(templateFile, 'utf-8');%0A html = html%0A .replace('#%7BjsFileName%7D', prefix + clientApp.jsFileName())%0A .replace('#%7BcssFileName%7D', prefix + clientApp.cssFileName());%0A%0A
res.set(
@@ -3293,36 +3293,31 @@
-8')
-.send(clientApp.htmlSource()
+%0A .send(html
);%0A
|
cfe3f7c03d292d0c37afc654ba327aecb184c041
|
add a bug reporting button
|
electron/main.js
|
electron/main.js
|
const { app, Menu, BrowserWindow, session } = require('electron')
const Store = require('electron-store')
const store = new Store()
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createMainWindow () {
let windowState = store.get('windowState') || {}
// Create the browser window.
mainWindow = new BrowserWindow({
show: true,
x: windowState.x,
y: windowState.y,
width: windowState.width || 1024,
height: windowState.height || 768,
maximized: !!windowState.maximized,
title: 'Agate'
})
createMenu(mainWindow)
loadMain()
mainWindow.on('close', saveWindowState);
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
function loadMain () {
mainWindow.loadFile('views/index.html')
}
function loadSettings () {
mainWindow.loadFile('views/settings.html')
}
function createMenu (mainWindow) {
const menu = Menu.buildFromTemplate([
{
label: 'Application',
submenu: [
{
label: 'Accueil',
accelerator: 'Ctrl+H',
click () { loadMain() }
},
{
label: 'Se déconnecter',
accelerator: 'Ctrl+D',
click () {
clearCasData(err => {
if (err) { console.error(err) }
loadMain()
})
}
},
{
label: 'Paramètres',
accelerator: 'Ctrl+,',
click () { loadSettings() }
},
{ type: 'separator' },
{ role: 'quit', label: 'Quitter' }
]
},
{
label: 'Affichage',
submenu: [
{ role: 'reload', label: 'Actualiser' },
{ role: 'resetzoom', label: 'Réinitialiser le zoom' },
{ role: 'zoomin', label: 'Zoom avant' },
{ role: 'zoomout', label: 'Zoom arrière' },
{ type: 'separator' },
{ role: 'togglefullscreen', label: 'Plein écran' }
]
},
{
label: 'Fenêtre',
submenu: [
{ role: 'minimize', label: 'Minimiser' }
]
},
{
label: 'Aide',
submenu: [
{ role: 'toggledevtools', label: 'Activer les outils de développement' }
]
}
])
Menu.setApplicationMenu(menu)
}
/**
* Save window position, size and maximized state
*/
function saveWindowState () {
if (mainWindow) {
const bounds = mainWindow.getBounds()
const maximized = mainWindow.isMaximized()
store.set('windowState', { ...bounds, maximized })
}
}
/**
* Clear CAS cookies, resulting in a disconnection
*/
function clearCasData (callback) {
if (mainWindow) {
session.fromPartition('persist:agate').clearStorageData({ storages: ['cookies'] }, callback)
}
}
/**
* Change expiration date of CAS cookies
* That way we can keep the session alive accross app restarts
*/
function persistCasCookies (callback) {
if (!mainWindow) { return callback() }
const sessionCookies = session.fromPartition('persist:agate').cookies
const casUrl = 'https://cas.cnrs.fr/cas/'
sessionCookies.get({ url: casUrl }, (error, cookies) => {
if (error) { return callback(error) }
(function nextCookie() {
const cookie = cookies.pop()
if (!cookie) {
// Writes any unwritten cookies before leaving
return sessionCookies.flushStore(callback)
}
cookie.expirationDate = parseInt(Date.now() / 1000) + (60 * 24 * 30)
cookie.url = casUrl
delete cookie.session
sessionCookies.set(cookie, (error) => {
if (error) { console.error(error) }
nextCookie()
})
})()
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createMainWindow)
let cookiesPersisted = false
app.on('before-quit', event => {
if (cookiesPersisted) { return }
cookiesPersisted = true
event.preventDefault()
persistCasCookies(err => {
if (err) { console.error(err) }
app.quit()
})
})
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createMainWindow()
}
})
|
JavaScript
| 0.000001 |
@@ -34,16 +34,23 @@
session
+, shell
%7D = req
@@ -2395,32 +2395,192 @@
submenu: %5B%0A
+ %7B%0A label: 'Signaler un probl%C3%A8me',%0A click () %7B shell.openExternal('https://github.com/nojhamster/agate-extension/issues') %7D%0A %7D,%0A
%7B role:
|
01d904e5e2b447ef5040631fd895d02d576ca0f7
|
remove logs
|
server.js
|
server.js
|
#! /usr/bin/env node
'use strict';
// Make sure that you enable unsecure localhost in chrome!
const https = require('https');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
const webpack = require('webpack');
const webpackConfig = require(__dirname + '/webpack.config.js');
const port = 8080;
let isFresh = true;
let entryPoint = webpackConfig.entry;
console.log("entryPoint ==", entryPoint);
// Check for a config file and use it
let loaderConfig;
try {
loaderConfig = JSON.parse(fs.readFileSync("./loader.config", "utf8"));
console.log("config ==", loaderConfig, typeof loaderConfig);
entryPoint = loaderConfig.entry;
} catch (e) {
/* continue */
}
// console.log(JSON.parse(loaderConfig))
// setup webpack
if (process.argv[2]) {
console.log("here")
entryPoint = process.argv[2];
}
console.log("entryPoint ==", entryPoint);
// Check to see if we can find the entry point
if (!fs.existsSync(entryPoint)) {
console.error("Could not find entry point. Failed to find:", entryPoint);
process.exit(1);
}
const compiler = webpack(webpackConfig);
const watching = compiler.watch({}, (err, stats) => {
if (err) {
console.error(err);
} else {
isFresh = true;
}
})
app.get('/', function(req, res) {
fs.readFile('./dist/script.js', (err, data) => {
if (err) {
console.log('error: ', err);
} else {
res.end(data);
}
})
isFresh = false;
});
app.get('/poll', function(req, res) {
res.send(isFresh);
})
const httpsOptions = {
key: fs.readFileSync(__dirname + '/key.pem'),
cert: fs.readFileSync(__dirname + '/cert.pem')
};
const server = https.createServer(httpsOptions, app).listen(port, () => {
console.log('server running at ' + port)
});
|
JavaScript
| 0.000001 |
@@ -434,50 +434,8 @@
try;
-%0Aconsole.log(%22entryPoint ==%22, entryPoint);
%0A%0A//
@@ -571,71 +571,8 @@
));%0A
- console.log(%22config ==%22, loaderConfig, typeof loaderConfig);%0A
en
@@ -720,30 +720,8 @@
) %7B%0A
- console.log(%22here%22)%0A
en
@@ -752,52 +752,10 @@
2%5D;%0A
+
%7D%0A
-console.log(%22entryPoint ==%22, entryPoint);%0A
// C
|
cacaf71f63131a0c58749c997ca7678a1e0adf9f
|
update Defs todo comment
|
elements/Defs.js
|
elements/Defs.js
|
import React, {
Children,
Component,
ART,
cloneElement,
PropTypes
} from 'react-native';
let {Group} = ART;
let map = {};
import LinearGradient from './LinearGradient';
import RadialGradient from './RadialGradient';
let onlyChild = Children.only;
class DefsItem extends Component{
static displayName = 'DefsItem';
static propType = {
visible: PropTypes.bool
};
static defaultProps = {
visible: false
};
constructor() {
super(...arguments);
this.id = this.props.id + ':' + this.props.svgId;
map[this.id] = cloneElement(onlyChild(this.props.children), {
id: null
});
}
componentWillReceiveProps = nextProps => {
let id = nextProps.id + ':' + nextProps.svgId;
if (id !== this.id) {
delete map[this.id];
}
map[id] = cloneElement(onlyChild(nextProps.children), {
id: null
});
};
componentWillUnmount = () => {
delete map[this.id];
};
render() {
return this.props.visible ? onlyChild(this.props.children) : <Group />;
}
}
let idReg = /^#(.+)/;
class DefsUse extends Component{
static displayName = 'DefsUse';
static propType = {
href: PropTypes.string
};
render() {
let href = this.props.href;
if (href) {
let matched = href.match(idReg);
if (matched) {
let template = map[matched[1] + ':' + this.props.svgId];
if (template) {
let props = {
...this.props,
href: null
};
return cloneElement(template, props);
}
}
}
console.warn(`Invalid href: '${href}' for Use element.\n Please check if '${href}' if defined`);
return <Group />;
}
}
// TODO: more details should be handled(different Svg namespace、(remove, add, update) Defs children)
class Defs extends Component{
static displayName = 'Defs';
static Item = DefsItem;
static Use = DefsUse;
getChildren = () => {
return Children.map(this.props.children, child => {
if (child.type === LinearGradient || child.type === RadialGradient) {
return cloneElement(child, {
svgId: this.props.svgId
});
}
if (child.props.id) {
return <DefsItem {...child.props} svgId={this.props.svgId}>{child}</DefsItem>;
}
});
};
render() {
return <Group>
{this.getChildren()}
</Group>;
}
}
export default Defs;
|
JavaScript
| 0 |
@@ -1914,99 +1914,42 @@
DO:
-more details should be handled(different Svg namespace%E3%80%81(remove, add, update) Defs children)
+defination scope, global or local?
%0Acla
|
f42acf8112607f24b6430ba99e780bf0329e176e
|
add body-parser and method-override
|
server.js
|
server.js
|
'use strict';
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const app = express(); // start express
const port = process.env.PORT || 3000;
const Note = mongoose.model('Notes', mongoose.Schema({ // model
title: String,
text: String
}));
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ // for parsing form
extended: false
}));
app.get('/', (req, res) => { // on request, send response
res.send('Server Running');
});
// ROUTES
app.get('/notes/new', (req, res) => { // for 'new' action
res.render('new-note'); // serve up the form
});
app.post('/notes', (req, res) => { // for 'post' action
Note.create(req.body, (err) => {
if (err) throw err;
console.log(req.body);
res.redirect('/');
});
});
mongoose.connect('mongodb://localhost:27017/evernode', (err) => {
if (err) throw err;
app.listen(port, () => {
console.log(`Evernode server running on port: ${port}`);
});
});
|
JavaScript
| 0.000002 |
@@ -98,220 +98,249 @@
st m
-ongoose = require('mongoose');%0A%0Aconst app = express(); // start express%0Aconst port = process.env.PORT %7C%7C 3000;%0Aconst Note = mongoose.model('Notes', mongoose.Schema(%7B // model%0A title: String,%0A text: String%0A%7D))
+ethodOverride = require('method-override');%0Aconst mongoose = require('mongoose');%0A%0Aconst logger = require('./lib/logger');%0Aconst note = require('./routes/note');%0A%0Aconst app = express(); // start express%0Aconst port = process.env.PORT %7C%7C 3000
;%0A%0Aa
@@ -446,16 +446,69 @@
lse%0A%7D));
+%0Aapp.use(methodOverride('_method'));%0Aapp.use(logger);
%0A%0Aapp.ge
@@ -599,306 +599,22 @@
);%0A%0A
-// ROUTES%0Aapp.get('/notes/new', (req, res) =%3E %7B // for 'new' action%0A res.render('new-note'); // serve up the form%0A%7D);%0A%0Aapp.post('/notes', (req, res) =%3E %7B // for 'post' action%0A Note.create(req.body, (err) =%3E %7B%0A if (err) throw err;%0A console.log(req.body);%0A res.redirect('/');%0A %7D);%0A%7D);%0A
+app.use(note);
%0A%0Amo
@@ -793,13 +793,12 @@
);%0A %7D);%0A%7D);
-%0A
|
12eba668a49eb3dbeccd31fcfcdcdc8ed501fe6e
|
fix notification error issue
|
app/views/directives/xuser-notifications.js
|
app/views/directives/xuser-notifications.js
|
define(['app','underscore','ionsound'], function(app,_) {
app.directive('xuserNotifications', function() {
return {
restrict: 'EAC',
replace: true,
templateUrl: '/app/views/directives/xuser-notifications.html',
controller: ['$scope', '$rootScope', 'IUserNotifications', '$timeout', '$filter','authentication',
function($scope, $rootScope, userNotifications, $timeout, $filter, authentication) {
var pageNumber = 0;
var pageLength = 10;
// var canQuery = true;
//============================================================
//
//
//============================================================
$scope.timePassed = function(createdOn) {
var timespan = moment(createdOn);
return timespan.startOf('hours').fromNow(true);
}
var notificationTimer;
//============================================================
//
//
//============================================================
getNotification = function() {
if ($rootScope.user && $rootScope.user.isAuthenticated) {
// if (canQuery) {
var queryMyNotifications;
queryMyNotifications = {$or:[{'state': 'read'},{'state': 'unread'}]};
if ($scope.notifications) {
var notification = _.first($scope.notifications);
if (notification)
queryMyNotifications = {
$and: [{
"createdOn": {
"$gt": new Date(notification.createdOn).toISOString()
},
$or:[{'state': 'read'},{'state': 'unread'}]
}]
};
}
//$and: [{"_id": {"$gt": notification._id}}]
var continueNotification = true;
userNotifications.query(queryMyNotifications, pageNumber, pageLength)
.then(function(data) {
if (!data || data.length === 0)
return;
var localNotifications;
if ($scope.notifications) {
localNotifications = _.clone($scope.notifications);
_.each(data, function(message) {
localNotifications.push(message);
});
if(ion)
ion.sound.play("bell_ring");
} else {
localNotifications = data;
}
$scope.notifications = [];
$scope.notifications = $filter("orderBy")(localNotifications, 'createdOn', true);
})
.catch(function(error){
if(error.data.statusCode==401){
// console.log('calling get fetch from notifications' );
//authentication.getUser(true);
continueNotification = false;
}
})
.finally(function() {
if(continueNotification)
notificationTimer = $timeout(function() { getNotification();}, 10000);
// notificationTimer.then(function(){
// //console.log('finished with timer');
// }).catch(function(){
// //console.log('rejected timer');
// });
});
//}
}
};
//============================================================
//
//
//============================================================
$scope.updateStatus = function(notification) {
if (notification && notification.state == 'unread') {
userNotifications.update(notification.id, {
'state': 'read'
})
.then(function() {
notification.state = 'read';
});
}
if (notification && notification.state == 'read') {
userNotifications.update(notification.id, {
'state': 'unread'
})
.then(function() {
notification.state = 'unread';
});
}
};
//============================================================
//
//
//============================================================
$scope.markAsRead = function(notification) {
if (notification && notification.state =='unread') {
userNotifications.update(notification.id, {
'state': 'read'
})
.then(function() {
notification.state = 'read';
});
}
};
//============================================================
//
//
//============================================================
$scope.isUnread = function(notification) {
return notification && notification.state == 'unread';
};
$scope.$on('$destroy', function(evt){
//console.log('$destroy');
$timeout.cancel(notificationTimer);
});
// $scope.$on('signIn', function(evt,user){
// $timeout(function(){
// console.log('notification after signin')
// getNotification();
// },5000);
// });
$scope.$on('signOut', function(evt,user){
//console.log('notification timer signout')
$timeout.cancel(notificationTimer);
});
getNotification();
$rootScope.$watch('user', function(newVla,oldVal){
//console.log(newVla,oldVal)
if(newVla && newVla!=oldVal){
console.log('user changed');
$timeout.cancel(notificationTimer);
if(newVla.isAuthenticated)
getNotification();
}
});
$scope.getURL = function(notification){
//console.log(notification)
if(notification.type=='documentNotification')
return '/register/requests/' + notification.data.workflowId;
else
return '/mailbox/' + notification.id;
}
$rootScope.$on('onNotificationStatusChanged', function(evt,data){
console.log('onNotificationStatusChanged',data)
var notification = _.first(_.where($scope.notifications, {id:data.id}));
if(notification){
notification.state = 'read';
}
});
ion.sound({
sounds: [
{
name: "bell_ring"
}
],
volume: 0.5,
path: "/app/libs/ionsound/sounds/",
preload: true
});
}
]
};
});
});
|
JavaScript
| 0 |
@@ -3715,16 +3715,30 @@
ror.data
+ && error.data
.statusC
|
f5f65501a758939e02d4c3453369c04831fde97e
|
Update diff2
|
src/helper/diff2.js
|
src/helper/diff2.js
|
var Diff;
Diff = (function() {
function Diff() {}
Diff.DIFFERENCE_TYPES = {
ADDED: 'added',
DELETED: 'deleted',
CHANGED: 'changed'
};
Diff.prototype.calculateDifferences = function(oldValue, newValue, key, path) {
var newValueType, oldValueType, pathElement;
if (key == null) {
key = '';
}
if (path == null) {
path = [];
}
newValueType = this._getType(newValue);
oldValueType = this._getType(oldValue);
if (key !== '') {
pathElement = {
key: key,
valueType: newValueType
};
path = path.concat([pathElement]);
}
if (!oldValue) {
return [this._createDifference(Diff.DIFFERENCE_TYPES.ADDED, path, newValue)];
} else if (!newValue) {
return [this._createDifference(Diff.DIFFERENCE_TYPES.DELETED, path)];
} else if (oldValueType !== newValueType) {
return [this._createDifference(Diff.DIFFERENCE_TYPES.CHANGED, path, newValue)];
} else if (typeof oldValue === 'object') {
return this._getNestedDifferences(oldValue, newValue, key, path);
} else if (newValue !== oldValue) {
return [this._createDifference(Diff.DIFFERENCE_TYPES.CHANGED, path, newValue)];
} else {
return [];
}
};
Diff.prototype._createDifference = function(type, path, value) {
return {
type: type,
path: path,
value: value
};
};
Diff.prototype._getNestedDifferences = function(oldObject, newObject, key, path) {
var allKeysToCheck, differences;
if (key == null) {
key = '';
}
if (path == null) {
path = [];
}
allKeysToCheck = this._union(Object.keys(oldObject), Object.keys(newObject));
differences = allKeysToCheck.map((function(_this) {
return function(key) {
return _this.calculateDifferences(oldObject[key], newObject[key], key, path);
};
})(this));
return this._flatten(differences);
};
Diff.prototype._union = function(array1, array2) {
return array1.concat(array2.filter(function(value) {
return array1.indexOf(value) === -1;
}));
};
Diff.prototype._flatten = function(arrayOfArrays) {
return arrayOfArrays.reduce((function(prev, current) {
return prev.concat(current);
}), []);
};
Diff.prototype._getType = function(input) {
var type;
type = typeof input;
if (type === 'object' && this._isArray(input)) {
return 'array';
} else {
return type;
}
};
Diff.prototype._isArray = function(input) {
return {}.toString.call(input) === "[object Array]";
};
Diff.prototype.applyDifferences = function(object, differences) {
differences.forEach((function(_this) {
return function(difference) {
var lastKey, lastReference;
lastKey = difference.path.pop().key;
lastReference = difference.path.reduce(function(object, pathElement) {
if (!object[pathElement.key]) {
_this._createValue(object, pathElement.key, pathElement.valueType);
}
return object[pathElement.key];
}, object);
if (difference.type === Diff.DIFFERENCE_TYPES.CHANGED || difference.type === Diff.DIFFERENCE_TYPES.ADDED) {
return lastReference[lastKey] = difference.value;
} else {
return delete lastReference[lastKey];
}
};
})(this));
return object;
};
Diff.prototype._createValue = function(object, key, type) {
return object[key] = this._createFromType(type);
};
Diff.prototype._createFromType = function(type) {
if (type === 'object') {
return {};
}
if (type === 'array') {
return [];
}
};
return Diff;
})();
module.exports = new Diff;
|
JavaScript
| 0 |
@@ -579,20 +579,18 @@
h =
-path
+%5B%5D
.concat(
%5Bpat
@@ -585,16 +585,22 @@
.concat(
+path,
%5BpathEle
@@ -2628,17 +2628,25 @@
object,
-d
+originalD
ifferenc
@@ -2647,24 +2647,97 @@
ferences) %7B%0A
+ var differences;%0A differences = this._clone(originalDifferences);%0A
differen
@@ -3741,16 +3741,425 @@
%7D%0A %7D;%0A%0A
+ Diff.prototype._clone = function(input) %7B%0A var output;%0A output = null;%0A if (typeof input === 'object') %7B%0A output = this._createFromType(this._getType(input));%0A Object.keys(input).forEach((function(_this) %7B%0A return function(key) %7B%0A return output%5Bkey%5D = _this._clone(input%5Bkey%5D);%0A %7D;%0A %7D)(this));%0A %7D else %7B%0A output = input;%0A %7D%0A return output;%0A %7D;%0A%0A
return
|
57a00dae889ccb2f1fd3f6874f0aa3ba340b597d
|
Remove universal require from child process
|
gpii/node_modules/spiSettingsHandler/src/GetHighContrastSchemeName.js
|
gpii/node_modules/spiSettingsHandler/src/GetHighContrastSchemeName.js
|
/**
* Child process to get localised high-contrast theme name.
*
* Copyright 2018 Raising the Floor - International
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* The R&D leading to these results received funding from the
* Department of Education - Grant H421A150005 (GPII-APCP). However,
* these results do not necessarily represent the policy of the
* Department of Education, and you should not assume endorsement by the
* Federal Government.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = require("gpii-universal"),
gpii = fluid.registerNamespace("gpii");
require("../../WindowsUtilities/WindowsUtilities.js");
var stringId = process.env.stringId;
var localizedName = gpii.windows.getIndirectString("@%SystemRoot%\\System32\\themeui.dll,-" + stringId);
if (localizedName === undefined) {
localizedName = "undefined";
}
process.send(localizedName);
|
JavaScript
| 0 |
@@ -648,20 +648,18 @@
;%0A%0Avar f
-luid
+fi
= requi
@@ -666,163 +666,538 @@
re(%22
-gpii-universal%22),%0A g
+ffi-napi%22);%0Avar ref = require(%22ref%22);%0A%0Avar shlwa
pi
-i
=
-fluid.registerNamespace(%22gpii%22);%0A%0Arequire(%22../../WindowsUtilities/WindowsUtilities.js%22);%0A%0Avar stringId = process.env.stringId;
+new ffi.Library(%22shlwapi%22, %7B%0A // https://docs.microsoft.com/en-us/windows/desktop/api/shlwapi/nf-shlwapi-shloadindirectstring%0A %22SHLoadIndirectString%22: %5B%0A %22uint32%22, %5B %22char*%22, %22char*%22, %22uint32%22, %22int%22 %5D%0A %5D%0A%7D);%0A%0A%0A// The localised string resources for the built-in theme names.%0Avar stringIds = %5B%0A %222107%22, // High Contrast #1%0A %222108%22, // High Contrast #2%0A %222103%22, // High Contrast Black%0A %222104%22 // High Contrast White%0A%5D;%0A%0Avar buf = Buffer.alloc(0xfff);%0A
%0Avar
@@ -1207,160 +1207,336 @@
cali
-z
+s
edName
+s
=
-gpii.windows.getIndirectString(%22@%25SystemRoot%25%5C%5CSystem32%5C%5Cthemeui.dll,-%22 + stringId);%0A%0Aif (localizedName === undefined)
+stringIds.map(function (stringId) %7B%0A var src = new Buffer(%22@%25SystemRoot%25%5C%5CSystem32%5C%5Cthemeui.dll,-%22 + stringId + %22%5Cu0000%22, %22ucs2%22);%0A var togo;%0A if (shlwapi.SHLoadIndirectString(src, buf, buf.length, 0) === 0) %7B%0A togo = ref.reinterpretUntilZeros(buf, 2, 0).toString(%22ucs2%22);%0A %7D else
%7B%0A
+
-localizedName
+ togo
=
-%22
unde
@@ -1544,12 +1544,38 @@
ined
-%22
;%0A
-%7D
+ %7D%0A%0A return togo;%0A%7D);%0A
%0Apro
@@ -1594,14 +1594,15 @@
cali
-z
+s
edName
+s
);%0A
|
0e3525116899a67c9b1d2c1f6bf99f7ae54e26c3
|
Add F11 note to Fullscreen settings option.
|
UWPWebBrowser/js/browser.js
|
UWPWebBrowser/js/browser.js
|
(function () {
"use strict";
// Enable nodelists to work with the spread operator
NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
// Event symbol
const EVENT_SYM = Symbol("events");
// Browser constructor
function Browser() {
this[EVENT_SYM] = {};
this.currentUrl = "";
this.documentTitle = "";
this.faviconLocs = new Map;
this.favorites = new Map;
this.loading = false;
this.isFullscreen = false;
this.roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
this.appView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView();
}
Browser.prototype = {
constructor: Browser,
// Simple event management - listen for a particular event
on (type, listener) {
let listeners = this[EVENT_SYM][type] || (this[EVENT_SYM][type] = []);
if (listeners.indexOf(listener) < 0) {
listeners.push(listener);
}
return this;
},
// Simple event management - stop listening for a particular event
off (type, listener) {
let listeners = this[EVENT_SYM][type],
index = listeners ? listeners.indexOf(listener) : -1;
if (index > -1) {
listeners.splice(index, 1);
}
return this;
},
// Simple event management - trigger a particular event
trigger (type) {
let event = { type };
let listeners = this[EVENT_SYM][type] || [];
listeners.forEach(listener => listener.call(this, event));
return this;
}
};
// Create browser instance
let browser = new Browser;
// Holds the fullscreen message timeout ID
let fullscreenMessageTimeoutId;
addEventListener("DOMContentLoaded", function () {
// Get the UI elements
Object.assign(this, {
"addFavButton": document.querySelector("#addFavButton"),
"backButton": document.querySelector("#backButton"),
"clearCacheButton": document.querySelector("#clearCacheButton"),
"clearFavButton": document.querySelector("#clearFavButton"),
"container": document.querySelector(".container"),
"element": document.querySelector("#browser"),
"favButton": document.querySelector("#favButton"),
"favicon": document.querySelector("#favicon"),
"favList": document.querySelector("#favorites"),
"favMenu": document.querySelector("#favMenu"),
"forwardButton": document.querySelector("#forwardButton"),
"fullscreenButton": document.querySelector("#goFullscreen"),
"fullscreenMessage": document.querySelector("#fullscreenMessage"),
"hideFullscreenLink": document.querySelector("#hideFullscreen"),
"progressRing": document.querySelector(".ring"),
"settingsButton": document.querySelector("#settingsButton"),
"settingsMenu": document.querySelector("#settingsMenu"),
"stopButton": document.querySelector("#stopButton"),
"tweetIcon": document.querySelector("#tweet"),
"urlInput": document.querySelector("#urlInput"),
"webview": document.querySelector("#WebView")
});
// Close the menu
this.closeMenu = () => {
if (!this.element.className.includes("animate")) {
return;
}
let onTransitionEnd = () => {
this.element.removeEventListener("transitionend", onTransitionEnd);
this.togglePerspective();
this.showFavMenu(true);
this.scrollFavoritesToTop();
this.showSettingsMenu(true);
};
this.element.addEventListener("transitionend", onTransitionEnd);
this.togglePerspectiveAnimation();
// Reset the title bar colors
this.setDefaultAppBarColors();
};
// Enter fullscreen mode
this.enterFullscreen = () => {
this.isFullscreen = true;
this.appView.tryEnterFullScreenMode();
this.element.classList.add("fullscreen");
this.fullscreenMessage.style.display = "block";
this.fullscreenMessage.classList.add("show");
this.fullscreenButton.textContent = "Exit full screen";
this.fullscreenButton.addEventListener("click", this.exitFullscreen);
this.fullscreenButton.removeEventListener("click", this.enterFullscreen);
fullscreenMessageTimeoutId = setTimeout(this.hideFullscreenMessage, 4000);
};
// Exit fullscreen mode
this.exitFullscreen = () => {
this.isFullscreen = false;
this.appView.exitFullScreenMode();
this.element.classList.remove("fullscreen");
this.fullscreenMessage.style.display = "none";
this.fullscreenButton.textContent = "Go full screen";
this.fullscreenButton.addEventListener("click", this.enterFullscreen);
this.fullscreenButton.removeEventListener("click", this.exitFullscreen);
this.hideFullscreenMessage();
};
// Handle keyboard shortcuts
this.handleShortcuts = keyCode => {
switch (keyCode) {
case this.KEYS.ESC:
if (this.isFullscreen) {
this.exitFullscreen();
}
break;
case this.KEYS.F11:
this[this.isFullscreen ? "exitFullscreen" : "enterFullscreen"]();
break;
case this.KEYS.L:
if (!this.isFullscreen) {
this.urlInput.focus();
this.urlInput.select();
}
break;
}
};
// Listen for the hide fullscreen link
this.hideFullscreenLink.addEventListener("click", () => this.exitFullscreen());
// Hide the fullscreen message
this.hideFullscreenMessage = () => {
clearTimeout(fullscreenMessageTimeoutId);
this.fullscreenMessage.classList.remove("show");
};
// Open the menu
this.openMenu = () => {
this.togglePerspective();
setImmediate(() => {
this.togglePerspectiveAnimation();
// Adjust AppBar colors to match new background color
this.setOpenMenuAppBarColors();
});
};
// Apply CSS transitions when opening and closing the menus
this.togglePerspective = () => {
this.element.classList.toggle("modalview");
};
this.togglePerspectiveAnimation = () => {
this.element.classList.toggle("animate");
};
// Hot key codes
this.KEYS = { "ESC": 27, "L": 76, "F11": 122 };
// Set the initial states
this.backButton.disabled = true;
this.forwardButton.disabled = true;
this.isFullscreen = false;
// Use a proxy to workaround a WinRT issue with Object.assign
this.titleBar = new Proxy(this.appView.titleBar, {
"get": (target, key) => target[key],
"set": (target, key, value) => (target[key] = value, true)
});
// Listen for fullscreen mode hot keys
addEventListener("keydown", e => {
let k = e.keyCode;
if (k === this.KEYS.ESC || k === this.KEYS.F11 || (e.ctrlKey && k === this.KEYS.L)) {
this.handleShortcuts(k);
}
});
// Listen for a click on the skewed container to close the menu
this.container.addEventListener("click", () => this.closeMenu());
// Navigate to the start page
this.webview.navigate("http://www.microsoft.com/");
// Fire event
this.trigger("init");
}.bind(browser));
// Export `browser`
window.browser = browser;
})();
|
JavaScript
| 0 |
@@ -4581,32 +4581,38 @@
Exit full screen
+ (F11)
%22;%0D%0A
@@ -5214,16 +5214,22 @@
l screen
+ (F11)
%22;%0D%0A
|
0d5877e3c01b53f4f1d2657809ef9ea88674931b
|
drop image
|
public/js/teacher/homework/views/homework-form.js
|
public/js/teacher/homework/views/homework-form.js
|
define('views/homework-form', [
'views/form',
'htmlToText'
], function (
Form,
htmlToText
) {
function HomeworkForm() {
Form.apply(this, arguments);
this.on('open', function (params) {
this.homework = params.homework;
this.model('homework').assign(params.homework, 'default');
});
this.on('save', function (data) {
data.id = this.homework.id;
data.course_id = this.homework.course_id;
data.title = htmlToText(this.ui.title);
data.description = htmlToText(this.ui.description);
data.is_public = Boolean(data.is_public);
});
}
Form.extend({
constructor: HomeworkForm,
ui: {
title: '[data-title]',
description: '[data-description]'
},
data: function () {
return {
homework: {
title: '',
description: ''
}
};
},
template: {
'@title': {
html: {
'@homework.title': htmlToText.undo
}
},
'@description': {
html: {
'@homework.description': htmlToText.undo
}
},
'[data-cancel]': {
click: 'cancel'
}
}
});
return HomeworkForm;
});
|
JavaScript
| 0 |
@@ -53,16 +53,27 @@
lToText'
+,%0A%09'jquery'
%0A%5D, func
@@ -97,16 +97,20 @@
mlToText
+,%0A%09$
%0A) %7B%0A%0A%09f
@@ -801,16 +801,417 @@
;%0A%09%09%7D,%0A%0A
+%09%09addImageFile: function (file) %7B%0A%09%09%09if (file.type !== 'image/png' && file.type !== 'image/jpeg') return;%0A%0A%09%09%09var view = this;%0A%09%09%09var reader = new FileReader();%0A%09%09%09reader.onload = function () %7B%0A%09%09%09%09view.addImage(reader.result);%0A%09%09%09%7D;%0A%09%09%09reader.readAsDataURL(file);%0A%09%09%7D,%0A%0A%09%09addImage: function (data) %7B%0A%09%09%09document.execCommand('insertHTML', false, $('%3Cimg%3E').attr('src', data).prop('outerHTML'));%0A%09%09%7D,%0A%0A
%09%09templa
@@ -1366,32 +1366,174 @@
htmlToText.undo%0A
+%09%09%09%09%7D,%0A%09%09%09%09on: %7B%0A%09%09%09%09%09'drop': function (e) %7B%0A%09%09%09%09%09%09e.preventDefault();%0A%09%09%09%09%09%09this.addImageFile(e.originalEvent.dataTransfer.files%5B0%5D);%0A%09%09%09%09%09%7D%0A
%09%09%09%09%7D%0A%09%09%09%7D,%0A%0A%09%09%09
|
20acc140d84a054b8c9fe9d85393008d559f0e5c
|
wrong capitalization
|
karma-common.conf.js
|
karma-common.conf.js
|
/* eslint no-var: 0, babel/object-shorthand: 0, vars-on-top: 0 */
require('babel-register')
var isCI = process.env.CONTINUOUS_INTEGRATION === 'true'
var reporters = ['mocha', 'Browserstack', 'coverage']
var singleRun = true
var webpack = require('./test/test.config.es6.js')
var sauceParams = {
testName: "react-selection-hoc unit tests",
username: process.env.SAUCEUSER,
accessKey: process.env.ACCESSSAUCE,
connectOptions: {
logfile: 'sauce_connect.log'
}
}
var coverageReporter = isCI ? {
reporters: [
{
type: 'lcov',
dir: 'coverage'
},
{
type: 'text'
}
]
} : {
reporters: [
{
type: 'lcov',
dir: 'coverage'
},
{
type: 'text'
},
{
type: 'html'
}
]
}
const frameworks = ['mocha', 'sinon-chai']
if (isCI) {
sauceParams.build = process.env.TRAVIS_BUILD_NUMBER
} else {
sauceParams.build = `Local Testing ${process.env.CURRENTTIME}`
sauceParams.startConnect = false
}
module.exports = function (config, extraoptions) {
config.set({
basePath: '',
frameworks,
files: [
'../../node_modules/babel-polyfill/dist/polyfill.js',
'../*.test.js'
],
preprocessors: {
'../*.test.js': ['webpack'],
},
webpack,
browserStack: {
username: process.env.BROWSER_STACK_USERNAME,
accessKey: process.env.BROWSER_STACK_ACCESS_KEY
},
webpackMiddleware: {
noInfo: true
},
reporters,
mochaReporter: {
output: 'autowatch'
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
sauceLabs: sauceParams,
coverageReporter,
browserDisconnectTolerance: 1, // default 0
browserNoActivityTimeout: 4 * 60 * 1000, // default 10000
captureTimeout: 4 * 60 * 1000, // default 60000
singleRun,
concurrency: 1,
...extraoptions
})
}
|
JavaScript
| 0.999972 |
@@ -177,17 +177,17 @@
'Browser
-s
+S
tack', '
|
aa387722a70d3a427101436547f119356b311283
|
Fix js error if url has no page param.
|
public/javascripts/common/hive.Pagination.js
|
public/javascripts/common/hive.Pagination.js
|
/**
* @(#)hive.Pagination 2013.03.21
*
* Copyright NHN Corporation.
* Released under the MIT license
*
* http://hive.dev.naver.com/license
*/
// Render pagination in the given target HTML element.
// Usage: Pagiation.updatePagination(target, totalPages);
// For more details, see docs/technical/pagination.md
/**
* TODO: 무한 스크롤 구현을 할 게 아니라면
* 굳이 페이징 링크를 굳이 동적으로 만들어야 할까? 개선 검토 필요
*/
hive.Pagination = (function(window, document) {
var htRegEx = {};
/**
* getQuery
* @param {String} url
*/
function getQuery(url){
var parser = document.createElement('a');
parser.href = url;
return parser.search;
}
/**
* valueFromQuery
* @param {String} key
* @param {String} query
*/
function valueFromQuery(key, query) {
htRegEx[key] = htRegEx[key] || new RegExp('(^|&|\\?)' + key + '=([^&]+)');
var result = htRegEx[key].exec(query);
return (result) ? result[2]: null;
}
/**
* urlWithQuery
* @param {String} url
* @param {String} query
*/
function urlWithQuery(url, query) {
var parser = document.createElement('a');
parser.href = url;
parser.search = '?' + query;
return parser.href;
}
/**
* urlWithPageNum
* @param {String} url
* @param {Number} pageNum
* @param {String} paramNameForPage
*/
function urlWithPageNum(url, pageNum, paramNameForPage) {
var query = getQuery(url);
var regex = new RegExp('(^|&|\\?)' + paramNameForPage + '=[^&]+');
var result = regex.exec(query);
query = query.replace(regex, result[1] + paramNameForPage + '=' + pageNum);
return urlWithQuery(url, query);
}
/**
* validateOptions
*/
function validateOptions(options) {
if (!Number.isFinite(options.current)) {
throw new Error("options.current is not valid: " + options.current);
}
}
/**
* window.updatePagination
*/
window.updatePagination = function(target, totalPages, options) {
if (totalPages <= 0){
return;
}
var target = $(target);
var linkToPrev, linkToNext, urlToPrevPage, urlToNextPage;
var options = options || {};
options.url = options.url || document.URL;
options.firstPage = options.firstPage || 1;
options.hasPrev = (typeof options.hasPrev == "undefined") ? options.current > options.firstPage : options.hasPrev;
options.hasNext = (typeof options.hasNext == "undefined") ? options.current < totalPages : options.hasNext;
var paramNameForPage = options.paramNameForPage || 'pageNum';
var pageNumFromUrl;
if (!Number.isFinite(options.current)) {
query = getQuery(options.url);
pageNumFromUrl = parseInt(valueFromQuery(paramNameForPage, query));
options.current = pageNumFromUrl || options.firstPage;
}
validateOptions(options);
target.html('');
target.addClass('page-navigation-wrap');
// previous page exists
var welPagePrev;
if (options.hasPrev) {
linkToPrev = $('<a>').append($('<i class="ico btn-pg-prev">')).append($('<span>').text('PREV'));
if (typeof (options.submit) == 'function') {
linkToPrev.attr('href', 'javascript: void(0);').click(function(e) {
options.submit(options.current - 1);
});
} else {
urlToPrevPage = urlWithPageNum(options.url, options.current - 1, paramNameForPage);
linkToPrev.attr('href', urlToPrevPage);
}
welPagePrev = $('<li class="page-num ikon">').append(linkToPrev);
} else {
welPagePrev = $('<li class="page-num ikon">').append($('<i class="ico btn-pg-prev off">')).append($('<span class="off">').text('PREV'));
}
// on submit event handler
if (typeof (options.submit) == 'function') {
var keydownOnInput = function(e) {
options.submit($(target).val());
};
} else {
var keydownOnInput = function(e) {
var target = e.target || e.srcElement;
if (e.which == 13) {
document.location.href = urlWithPageNum(options.url, $(target).val(), paramNameForPage);
}
}
}
// page input box
var elInput = $('<input name="pageNum" type="number" min="1" max="' + totalPages + '" class="input-mini" value="' + options.current + '">').keydown(keydownOnInput);
var welPageInputContainer = $('<li class="page-num">').append(elInput);
var welDelimiter = $('<li class="page-num">').text('/');
var welTotalPages = $('<li class="page-num">').text(totalPages);
// next page exists
var welPageNext;
if (options.hasNext) {
linkToNext = $('<a>').append($('<span>').text('NEXT')).append($('<i class="ico btn-pg-next">'));
if (typeof (options.submit) == 'function') {
linkToNext.attr('href', 'javascript: void(0);').click(function(e) { options.submit(options.current + 1);});
} else {
urlToNextPage = urlWithPageNum(options.url, options.current + 1, paramNameForPage);
linkToNext.attr('href', urlToNextPage);
}
welPageNext = $('<li class="page-num ikon">').append(linkToNext);
} else {
welPageNext = $('<li class="page-num ikon">').append($('<i class="ico btn-pg-next off">')).append($('<span class="off">').text('NEXT'));
}
// fill #pagination
var welPageList = $('<ul class="page-nums">').append([welPagePrev, welPageInputContainer, welDelimiter, welTotalPages, welPageNext]);
target.append(welPageList);
};
return {
"update" : updatePagination
};
})(window, document);
|
JavaScript
| 0 |
@@ -1222,32 +1222,142 @@
urlWithPageNum%0D%0A
+ *%0A * Create a url whose query has a paramNameForPage parameter whose value is%0A * pageNum.%0A *%0A
%09 * @param %7BStri
@@ -1637,90 +1637,320 @@
);%0D%0A
-%09%09query = query.replace(regex, result%5B1%5D + paramNameForPage + '=' + pageNum);%0D%0A%09%09%0D
+ if (result) %7B%0A // if paramNameForPage parameter already exists, update it.%0A query = query.replace(regex, result%5B1%5D + paramNameForPage + '=' + pageNum);%0A %7D else %7B%0A // if not add new one.%0A query = query + '&' + paramNameForPage + '=' + pageNum;%0A %7D%0A
%0A%09%09r
|
423689a9ec4afdfc52bcfc7b32e23a6f4b9ce42d
|
update delay plugin
|
vendor/assets/javascripts/jquery.datatables.fnSetFilteringDelay.js
|
vendor/assets/javascripts/jquery.datatables.fnSetFilteringDelay.js
|
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
var _that = this;
this.each( function ( i ) {
$.fn.dataTableExt.iApiIndex = i;
iDelay = (iDelay && (/^[0-9]+$/.test(iDelay))) ? iDelay : 250;
var $this = this, oTimerId;
var anControl = $( 'input', _that.fnSettings().aanFeatures.f );
anControl.unbind( 'keyup' ).bind( 'keyup', function(event) {
window.clearTimeout(oTimerId);
if (event.keyCode == '13') {
// cr, we filter immedately
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter( $(this).val() );
} else {
// not cr, set new timer
oTimerId = window.setTimeout(function() {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter( $(this).val() );
}, iDelay);
}
});
return this;
} );
return this;
};
|
JavaScript
| 0 |
@@ -80,86 +80,105 @@
) %7B%0A
- var _that = this;%0A this.each( function ( i ) %7B%0A
+%0A /*%0A * Type: Plugin for DataTables (www.datatables.net) JQuery plugin.%0A * Name:
$.fn
@@ -165,37 +165,32 @@
* Name:
-$.fn.
dataTableExt.iAp
@@ -190,166 +190,259 @@
Ext.
-iApiIndex = i;%0A iDelay = (iDelay && (/%5E%5B0-9%5D+$/.test(iDelay))) ? iDelay : 250;%0A %0A var $this = this, oTimerId;
+oApi.fnSetFilteringDelay%0A * Version: 1.0.0%0A * Description: Enables filtration delay for keeping the browser more%0A * responsive while searching for a longer keyword.%0A * Inputs: object:oSettings - dataTables settings object
%0A
+*
@@ -455,607 +455,692 @@
-var anControl = $( 'input', _that.fnSettings().aanFeatures.f );%0A %0A anControl.unbind( 'keyup' ).bind( 'keyup', function(event) %7B%0A window.clearTimeout(oTimerId);%0A %0A if (event.keyCode == '13') %7B%0A // cr, we filter immedately%0A $.fn.dataTableExt.iApiIndex = i;%0A _that.fnFilter( $(this).val() );%0A %7D else %7B%0A // not cr, set new timer%0A
+integer:iDelay - delay in miliseconds%0A * Returns: JQuery%0A * Usage: $('#example').dataTable().fnSetFilteringDelay(250);%0A *%0A * Author: Zygimantas Berziunas (www.zygimantas.com)%0A * Created: 7/3/2009%0A * Language: Javascript%0A * License: GPL v2 or BSD 3 point style%0A * Contact: [email protected]%0A */%0A%0A iDelay = (iDelay && (/%5E%5B0-9%5D+$/.test(iDelay))) ? iDelay : 250; %0A%0A var $this = this, oTimerId;%0A%0A // Unfortunately there is no nFilter inside oSettings.%0A var anControl = $( 'div.dataTables_filter input:text' );%0A%0A anControl.unbind( 'keyup' ).bind( 'keyup', function() %7B%0A%0A var $$this = $this;%0A window.clearTimeout(oTimerId);%0A%0A
@@ -1185,126 +1185,21 @@
) %7B%0A
-
+%0A
- $.fn.dataTableExt.iApiIndex = i;%0A _that
+$$this
.fnF
@@ -1209,15 +1209,17 @@
er(
-$(this)
+anControl
.val
@@ -1232,184 +1232,27 @@
- %7D, iDelay);%0A %7D%0A %0A %7D);%0A %0A return this;%0A %7D );%0A
+%7D, iDelay);%0A %7D);%0A%0A
re
@@ -1263,9 +1263,8 @@
this;%0A%7D
-;
|
d80a68506d81aa169b16948e45ab01bd44c9b4de
|
add onReject function callback
|
s3-event-handler/index.js
|
s3-event-handler/index.js
|
'use strict';
console.log('Loading function');
let firebase = require('firebase');
let crypto = require('crypto');
let moment = require('moment');
let aws = require('aws-sdk');
let s3 = new aws.S3({ apiVersion: '2006-03-01' });
let id3 = require('id3-parser');
aws.config.setPromisesDependency(require('q').Promise);
firebase.initializeApp({
serviceAccount: JSON.parse(process.env.SERVICE_ACCOUNT),
databaseURL: process.env.DATABASE_URL
});
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false
console.log(JSON.stringify(event, null, 2));
const s3Data = event.Records[0].s3;
const eventName = event.Records[0].eventName;
const bucket = s3Data.bucket.name;
const key = decodeURIComponent(s3Data.object.key.replace(/\+/g, ' '));
const fileUrl = 'https://s3.amazonaws.com/' + bucket + '/' + s3Data.object.key;
const databaseKey = 'sermons/' + crypto.createHash('md5').update(s3Data.object.key).digest("hex");
function persistSermon(sermonData, label) {
console.log(sermonData);
firebase.database().ref(databaseKey).set(sermonData).then(function(data) {
callback(null, fileUrl + " : " + label);
}).catch(function (error) {
callback('Database set error ' + error);
});
}
function formatDate(date) {
console.log('formatDate');
var formattedDate = moment(date.substring(0,10), 'MM/DD/YYYY').format();
if ('Invalid date' === formattedDate) {
formattedDate = moment().format();
}
return formattedDate;
}
if (eventName.includes('ObjectRemoved')) {
console.log(fileUrl + ' [DELETING]');
persistSermon(null, 'DELETED');
}
else if (eventName.includes('ObjectCreated')) {
console.log(fileUrl + ' [CREATING]');
s3.getObject({Bucket: bucket, Key: key}).promise()
.then(function(data) {
console.log('parsing mp3 tag');
id3.parse(new Buffer(data.Body)).then(function (tag) {
console.log('parsed mp3 tag');
const sermonData = {
bucketID : bucket,
minister : tag.artist ? tag.artist : '',
bibleText : tag.album ? tag.album : '',
comments : tag.comment ? tag.comment : '',
date : formatDate(tag.title ? tag.title : ''),
published : false,
fileUrl : fileUrl
};
persistSermon(sermonData, 'CREATED');
});
}).catch(function(err) {
console.log(err);
const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
console.log(message);
const sermonData = {
bucketID : bucket,
minister : '',
bibleText : '',
comments : '',
date : moment().format(),
published : false,
fileUrl : fileUrl
};
persistSermon(sermonData, 'CREATED');
});
}
};
|
JavaScript
| 0 |
@@ -1290,24 +1290,331 @@
%7D);%0A %7D%0A%0A
+ function persistEmptySermon() %7B%0A const sermonData = %7B%0A bucketID : bucket,%0A minister : '',%0A bibleText : '',%0A comments : '',%0A date : moment().format(),%0A published : false,%0A fileUrl : fileUrl%0A %7D;%0A persistSermon(sermonData, 'CREATED');%0A %7D%0A%0A
function
@@ -1629,24 +1629,24 @@
ate(date) %7B%0A
-
consol
@@ -2288,16 +2288,27 @@
a.Body))
+%0A
.then(fu
@@ -2780,32 +2780,166 @@
ta, 'CREATED');%0A
+ %7D,%0A function(err) %7B%0A console.log('unable to parse mp3 tag : ' + err);%0A persistEmptySermon();%0A
%7D);%0A%0A
@@ -2936,17 +2936,16 @@
%7D);%0A
-%0A
@@ -3200,299 +3200,27 @@
-const sermonData = %7B%0A bucketID : bucket,%0A minister : '',%0A bibleText : '',%0A comments : '',%0A date : moment().format(),%0A published : false,%0A fileUrl : fileUrl%0A %7D;%0A persistSermon(sermonData, 'CREATED'
+persistEmptySermon(
);%0A
|
3ae4beee68d1d674a8966d523c03717225051acc
|
Add kalabox binary to prepackaged downloads
|
grunt/deps.js
|
grunt/deps.js
|
'use strict';
/**
* This file/module contains helpful download config.
*/
// Node modules
var path = require('path');
var fs = require('fs');
// NPM modules
var _ = require('lodash');
// Kalabox modzz
var kbox = require('kalabox');
var yaml = kbox.util.yaml;
// Config files that hold our deps
// @todo: can we use srcroot here?
var kboxPath = path.resolve(__dirname, '..', 'node_modules', 'kalabox');
// Get engine conf path
var enginePath = path.join(kboxPath, 'plugins', 'kalabox-engine-docker');
var engineConf = path.join(enginePath, 'provider', 'docker', 'config.yml');
// Get sycnthing conf path
var syncthingPath = path.join(kboxPath, 'plugins', 'kalabox-syncthing');
var syncthingConf = path.join(syncthingPath, 'lib', 'config.yml');
// get actual conf
var engine = yaml.toJson(engineConf);
var syncthing = yaml.toJson(syncthingConf);
/*
* Helper function to get the images we want to export
*/
var getDockerImages = function() {
// Get the image tag and home directory
// @todo: we need a way to get this for pantheon images, right now we assume
// the pantheon image version is the same as the core image version
var imgVersion = kbox.core.config.getEnvConfig().imgVersion;
// Images we want to prepackage
// @todo: figure out a better way to handle this
return [
['kalabox/proxy', imgVersion].join(':'),
['kalabox/dns', imgVersion].join(':'),
['kalabox/syncthing', imgVersion].join(':'),
['kalabox/cli', imgVersion].join(':'),
['kalabox/pantheon-solr', imgVersion].join(':'),
['kalabox/pantheon-redis', imgVersion].join(':'),
['kalabox/terminus', imgVersion].join(':'),
['kalabox/pantheon-mariadb', imgVersion].join(':'),
['kalabox/pantheon-edge', imgVersion].join(':'),
['kalabox/pantheon-appserver', imgVersion].join(':'),
'busybox'
];
};
/*
* Helper function to get docker-machine bin
*/
var getDockerMachineBin = function() {
// This is where our docker-machine bin should exist if we've installed
// kalabox
var binDir = path.join(kbox.core.config.getEnvConfig().sysConfRoot, 'bin');
var dockerMachine = path.join(binDir, 'docker-machine');
// Use the kalabox shipped docker-machine if it exists, else assume
// it exists in the path
return (fs.existsSync(dockerMachine)) ? dockerMachine : 'docker-machine';
};
/*
* Helper function to get docker-machine ssh prefix
* @todo: for now we assume the created name is "kbox-gui-helper"
*/
var runDockerCmd = function(cmd) {
return [getDockerMachineBin(), 'ssh', 'kbox-gui-helper', cmd].join(' ');
};
/*
* Helper function to build pull commands
* NOTE: we need to do this because docker pull only runs with a single
* argument
*/
var dockerPull = function(images) {
return _.map(images, function(image) {
return runDockerCmd(['docker', 'pull', image].join(' '));
}).join(' && ');
};
/*
* Helper function to build export command
*/
var dockerExport = function(images) {
return runDockerCmd(['docker', 'save', images.join(' ')].join(' '));
};
module.exports = {
/*
* Download admin deps to package with GUI
*/
downloads: {
osx64Deps: {
src: [
engine.virtualbox.pkg.darwin,
engine.machine.pkg.darwin,
engine.compose.pkg.darwin,
//syncthing.pkg.darwin,
syncthing.configfile
],
dest: './deps/osx64'
},
win64Deps: {
src: [
engine.virtualbox.pkg.win32,
engine.machine.pkg.win32,
engine.compose.pkg.win32,
engine.msysgit.pkg.win32,
//syncthing.pkg.win32,
syncthing.configfile
],
dest: './deps/win64'
},
linux64Deps: {
src: [
engine.machine.pkg.linux,
engine.compose.pkg.linux,
//syncthing.pkg.linux,
syncthing.configfile
],
dest: './deps/linux64'
},
/*
* Downlaod the iso image for our kalabox VM
* @todo: get this from Kalabox as well
*/
// jscs:disable
iso: {
src: [
'https://github.com/kalabox/kalabox-iso/releases/download/v0.11.0/boot2docker.iso'
],
dest: './deps/iso'
}
// jscs:enable
},
/**
* Clean out the build dirs
*/
clean: {
all: ['./deps'],
deps: [
'./deps/osx64',
'./deps/win64',
'./deps/linux64'
],
iso: ['./deps/iso'],
images: ['./deps/images']
},
/**
* The `copy` task just copies files from A to B. We use it here to copy
* our project assets (images, fonts, etc.) and javascripts into
* `build_dir`, and then to copy the assets to `compile_dir`.
*/
copy: {
deps: {
files: [
{
src: ['**/*'],
dest: '<%= buildDir %>/deps/',
cwd: 'deps/',
expand: true
}
]
}
},
/*
* Helpers shell commands
*/
shell: {
/*
* Export images to deps/images/images.tar.gz
* NOTE: For now we assume the following
*
* 1. docker-machine binary exists in PATH or at ~/.kalabox/bin
*
*/
exportImages: {
command: [
'mkdir -p deps/images',
'cd deps/images',
getDockerMachineBin() + ' create -d virtualbox kbox-gui-helper',
dockerPull(getDockerImages()),
dockerExport(getDockerImages()) + ' | gzip -9c > images.tar.gz',
getDockerMachineBin() + ' rm -f kbox-gui-helper'
].join(' && ')
}
},
};
|
JavaScript
| 0 |
@@ -746,16 +746,159 @@
yml');%0A%0A
+// Get core conf path%0Avar corePath = path.join(kboxPath, 'plugins', 'kalabox-core');%0Avar coreConf = path.join(corePath, 'lib', 'config.yml');%0A%0A
// get a
@@ -989,16 +989,50 @@
ngConf);
+%0Avar core = yaml.toJson(coreConf);
%0A%0A/*%0A *
@@ -3473,33 +3473,66 @@
thing.configfile
+,%0A core.kalabox.pkg.darwin
%0A
-
%5D,%0A d
@@ -3778,32 +3778,64 @@
thing.configfile
+,%0A core.kalabox.pkg.win32
%0A %5D,%0A
@@ -3985,32 +3985,32 @@
hing.pkg.linux,%0A
-
syncthin
@@ -4021,16 +4021,48 @@
nfigfile
+,%0A core.kalabox.pkg.linux
%0A %5D
|
86a1fc455f64d516313c1b0164f172fb7e764ef0
|
fix for JQUI deprecation
|
octoprint_filemanager/static/js/ko.single_double_click.js
|
octoprint_filemanager/static/js/ko.single_double_click.js
|
ko.bindingHandlers.singleOrDoubleClick = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
var singleHandler = undefined,
doubleHandler = undefined,
delay = 250,
clicks = 0;
if (_.isObject(value)) {
singleHandler = value.click;
doubleHandler = value.dblclick;
delay = ko.utils.unwrapObservable(value.delay) || delay;
}
else {
singleHandler = value;
}
$(element).click(function(e) {
var sel = getSelection().toString();
if(sel)
return;
clicks++;
if (clicks === 1) {
$(element).disableSelection();
setTimeout(function () {
$(element).enableSelection();
if (clicks === 1) {
if (singleHandler !== undefined) {
singleHandler.call(this, bindingContext.$data, e);
}
} else {
if (doubleHandler !== undefined) {
doubleHandler.call(this, bindingContext.$data, e);
}
}
clicks = 0;
}, delay);
}
});
}
};
|
JavaScript
| 0 |
@@ -798,25 +798,35 @@
nt).
-disableSelection(
+style('user-select', 'none'
);%0A
@@ -900,24 +900,35 @@
nt).
-enableSelection(
+style('user-select', 'auto'
);%0A
|
634273ccf92f423db665465dfb2fa8705c1b0df2
|
model needs to be overwritable
|
lib/pipeline.js
|
lib/pipeline.js
|
'use strict';
var EventBroker = require('broker');
function Pipeline(Context) {
this.Context = Context || require('hoist-context');
this.eventBroker = new EventBroker();
}
Pipeline.prototype.raise = function raise(eventName, payload) {
return this.Context.get().bind(this).then(function (context) {
var cid;
if (context.event) {
cid = context.event.correlationId;
}
cid = cid || require('uuid').v4();
var ev = new EventBroker.events.ApplicationEvent({
applicationId: context.application._id,
eventName: eventName,
environment: context.environment,
correlationId: cid,
payload: payload
});
return this.eventBroker.send(ev).then(function () {
return ev;
});
});
};
module.exports = function (hoistContext) {
return new Pipeline(hoistContext);
};
module.exports.Pipeline = Pipeline;
|
JavaScript
| 0.999933 |
@@ -66,24 +66,31 @@
line(Context
+, Model
) %7B%0A this.C
@@ -135,16 +135,109 @@
text');%0A
+ this.Model = Model %7C%7C require('hoist-model');%0A EventBroker.ModelResolver.set(this.Model);%0A
this.e
@@ -877,24 +877,31 @@
hoistContext
+, Model
) %7B%0A return
@@ -926,16 +926,23 @@
tContext
+, Model
);%0A%7D;%0Amo
|
0f077bd8eaf30107a691b60c9500fe0c71d0dad0
|
Switch to a truly unique key
|
src/docs/ComponentPage.js
|
src/docs/ComponentPage.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Example from './Example';
import Props from './Props';
const ComponentPage = ({component}) => {
const {name, description, props, examples} = component;
return (
<div className="componentpage">
<h2>{name}</h2>
<p>{description}</p>
<h3>Example{examples.length > 1 && "s"}</h3>
{
examples.length > 0 ?
examples.map( example => <Example key={example.name} example={example} componentName={name} /> ) :
"No examples exist."
}
<h3>Props</h3>
{
props ?
<Props props={props} /> :
"This component accepts no props."
}
</div>
)
};
ComponentPage.propTypes = {
component: PropTypes.object.isRequired
};
export default ComponentPage;
|
JavaScript
| 0 |
@@ -460,19 +460,19 @@
example.
-nam
+cod
e%7D examp
|
f5092b73747372b5861fed9719f0a66718b6cfa1
|
Fix command state updating.
|
ui/CommandManager.js
|
ui/CommandManager.js
|
import { forEach, Registry, without } from '../util'
/*
Listens to changes on the document and selection and updates the commandStates
accordingly.
The contract is that the CommandManager maintains a state for each
command contributing to the global application state.
*/
export default class CommandManager {
constructor(context, commands) {
const editorSession = context.editorSession
if (!editorSession) {
throw new Error('EditorSession required.')
}
this.editorSession = context.editorSession
// commands by name
this.commands = commands
// a context which is provided to the commands
// for evaluation of state and for execution
this.context = Object.assign({}, context, {
// for convenienve we provide access to the doc directly
doc: this.editorSession.getDocument()
})
// some initializations such as setting up a registry
this._initialize()
// on any update we will recompute
this.editorSession.onUpdate(this._onSessionUpdate, this)
// compute initial command states and
// promote to editorSession
this._updateCommandStates(this.editorSession)
}
dispose() {
this.editorSession.off(this)
}
/*
Execute a command, given a context and arguments.
Commands are run async if cmd.isAsync() returns true.
*/
executeCommand(commandName, userParams, cb) {
let cmd = this._getCommand(commandName)
if (!cmd) {
console.warn('command', commandName, 'not registered')
return
}
let commandStates = this.editorSession.getCommandStates()
let commandState = commandStates[commandName]
let params = Object.assign(this._getCommandParams(), userParams, {
commandState: commandState
})
if (cmd.isAsync) {
// TODO: Request UI lock here
this.editorSession.lock()
cmd.execute(params, this._getCommandContext(), (err, info) => {
if (err) {
if (cb) {
cb(err)
} else {
console.error(err)
}
} else {
if (cb) cb(null, info)
}
this.editorSession.unlock()
})
} else {
let info = cmd.execute(params, this._getCommandContext())
return info
}
}
_initialize() {
this.commandRegistry = new Registry()
forEach(this.commands, (command) => {
this.commandRegistry.add(command.name, command)
})
}
_getCommand(commandName) {
return this.commandRegistry.get(commandName)
}
/*
Compute new command states object
*/
_updateCommandStates(editorSession) {
const commandContext = this._getCommandContext()
const params = this._getCommandParams()
const surface = params.surface
const commandRegistry = this.commandRegistry
// TODO: discuss, and maybe think about optimizing this
// by caching the result...
let commandStates = {}
let commandNames = commandRegistry.names.slice()
// first assume that all of the commands are disabled
commandNames.forEach((name) => {
commandStates[name] = { disabled: true }
})
// EXPERIMENTAL: white-list and black-list support via Surface props
if (surface) {
let included = surface.props.commands
let excluded = surface.props.excludedCommands
if (included) {
commandNames = included.map((name) => {
return commandRegistry.contains(name)
})
} else if (excluded) {
commandNames = without(commandNames, ...excluded)
}
}
const commands = commandNames.map(name => commandRegistry.get(name))
commands.forEach((cmd) => {
if (cmd) {
commandStates[cmd.getName()] = cmd.getCommandState(params, commandContext)
}
})
// NOTE: We previously did a check if commandStates were actually changed
// before updating them. However, we currently have complex objects
// in the command state (e.g. EditInlineNodeCommand) so we had to remove it.
// See Issue #1004
this.commandStates = commandStates
editorSession.setCommandStates(commandStates)
}
_onSessionUpdate(editorSession) {
if (editorSession.hasChanged('change') || editorSession.hasChanged('selection') || editorSession.hasChanged('commandStates')) {
this._updateCommandStates(editorSession)
}
}
_getCommandContext() {
return this.context
}
_getCommandParams() {
let editorSession = this.context.editorSession
let selectionState = editorSession.getSelectionState()
let sel = selectionState.getSelection()
let surface = this.context.surfaceManager.getFocusedSurface()
return {
editorSession: editorSession,
selectionState: selectionState,
surface: surface,
selection: sel,
}
}
}
|
JavaScript
| 0 |
@@ -3318,19 +3318,22 @@
ncluded.
-map
+filter
((name)
|
869df76e5a5e2e473a189638977b3c6cea48f7d0
|
Remove exec.hallo
|
grunt/exec.js
|
grunt/exec.js
|
module.exports = function(grunt){
var exec = {
echo: {
cmd: 'echo "hallo"'
},
nyc: {
cmd: './node_modules/.bin/nyc grunt test'
}
};
return exec;
};
|
JavaScript
| 0.000001 |
@@ -49,52 +49,8 @@
= %7B%0A
- %09%09echo: %7B%0A %09%09%09cmd: 'echo %22hallo%22'%0A %09%09%7D,%0A
%09%09ny
|
849da459ff494b09541cb8efe886350758aefe77
|
Change server.js
|
server.js
|
server.js
|
/**
* Introduction to Human-Computer Interaction
* Lab 2
* --------------
* Created by: Michael Bernstein
* Last updated: December 2013
*/
var PORT = 3000;
// Express is a web framework for node.js
// that makes nontrivial applications easier to build
var express = require('express');
// Create the server instance
var app = express();
// Print logs to the console and compress pages we send
app.use(express.logger());
app.use(express.compress());
// Return all pages in the /static directory
// whenever they are requested at '/'
// e.g., http://localhost:3000/index.html
// maps to /static/index.html on this machine
app.use(express.static(__dirname + '/views'));
// Start the server
var port = process.env.PORT || PORT; // 80 for web, 3000 for development
app.listen(port, function() {
console.log("Node.js server running on port %s", port);
});
|
JavaScript
| 0.000002 |
@@ -688,13 +688,8 @@
+ '/
-views
'));
|
f84472e54f57c4bb92c0a6c07c880ae8d0e81dc6
|
Enable HTML report of puppeteer results (#5053)
|
e2e/jest.config.js
|
e2e/jest.config.js
|
const { defaults } = require('jest-config');
const { TEST_MODE } = process.env;
module.exports = {
verbose: false,
preset: 'jest-puppeteer',
testTimeout: 1200000,
testRunner: 'jest-circus/runner',
testEnvironment: '<rootDir>/puppeteer-custom-environment.ts',
setupFilesAfterEnv: ['<rootDir>/jest-circus.setup.ts', '<rootDir>/jest.test-setup.ts'],
setupFiles: ['dotenv/config'],
reporters: [
'default',
[
'jest-stare',
{
resultDir: 'logs',
resultJson: 'test-results.json',
reportTitle: 'AoU integration tests',
report: false
}
],
[
'jest-junit',
{
outputDirectory: './logs/junit',
outputName: 'test-results.xml',
classNameTemplate: '{filepath}',
suiteNameTemplate: '{filepath}',
suiteName: 'AoU integration tests'
}
],
[
'<rootDir>/libs/jest-reporter.js',
{
outputdir: 'logs/jest',
filename: 'test-results-summary.json'
}
]
],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest'
},
globals: {
'ts-jest': {
tsconfig: 'tsconfig.jest.json'
}
},
testPathIgnorePatterns: ['/node_modules/', '/tsc-out/'],
testMatch:
TEST_MODE === 'nightly-integration'
? ['<rootDir>/tests/nightly/**/*.spec.ts']
: ['<rootDir>/tests(?!/nightly)/**/*.spec.ts'],
transformIgnorePatterns: ['<rootDir>/node_modules/(?!tests)'],
moduleFileExtensions: [...defaults.moduleFileExtensions],
modulePaths: ['<rootDir>']
};
|
JavaScript
| 0 |
@@ -518,16 +518,67 @@
.json',%0A
+ resultHtml: 'puppeteer-test-results.html',%0A
@@ -631,20 +631,19 @@
report:
-fals
+tru
e%0A
|
d6aed9f87a26f91ce6cb1e9ccfdb4c8194c9ce82
|
simplify listening on a port
|
server.js
|
server.js
|
/*eslint-env node, express */
// Initialize Express
var express = require('express');
var app = express();
// Set up a simple static server for the public directory
app.use('/', express.static(__dirname + "/public"));
// Get IP of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application
var host = process.env.VCAP_APP_HOST || 'localhost';
// Get the port on the DEA for communication with the application
var port = process.env.VCAP_APP_PORT || 3000;
// Serve the application
//TODO - print when the server is ready
app.listen(port, host);
|
JavaScript
| 0.000081 |
@@ -72,17 +72,17 @@
ire(
-'
+%22
express
-'
+%22
);%0Av
@@ -222,101 +222,46 @@
%0A//
-Get IP of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application
+Listen for requests on a prort
%0Avar
-hos
+por
t =
@@ -285,227 +285,141 @@
APP_
-HOS
+POR
T %7C%7C
-'localhost';%0A%0A// Get the port on the DEA for communication with the application%0Avar port = process.env.VCAP_APP_PORT %7C%7C 3000;%0A%0A// Serve the
+process.env.PORT %7C%7C process.env.port %7C%7C 3000;%0A
app
+.
li
-cation%0A//TODO - print when the server is ready%0Aapp.listen(port, host
+sten(port, function() %7B%0A%09console.log(%22Server running on port: %25d%22, port);%0A%7D
);
|
0179c20ce8fde993169579d4837682dde47121d1
|
update playround with onAuthFailed callback
|
demo/app.js
|
demo/app.js
|
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import GooglePicker from '../';
const CLIENT_ID = '206339496672-eie1j7vvr0plioslt41l2qsddmdjloqj.apps.googleusercontent.com';
const DEVELOPER_KEY = 'AIzaSyChPXI8ByCl68kcpy0zwjrfjEc_8mtwH_w';
const SCOPE = ['https://www.googleapis.com/auth/drive.readonly'];
function App() {
return (
<div className="container">
<GooglePicker clientId={CLIENT_ID}
developerKey={DEVELOPER_KEY}
scope={SCOPE}
onChange={data => console.log('on change:', data)}
multiselect={true}
navHidden={true}
authImmediate={false}
mimeTypes={['image/png', 'image/jpeg', 'image/jpg']}
viewId={'DOCS'}>
<span>Click me!</span>
<div className="google"></div>
</GooglePicker>
<br/>
<hr/>
<br/>
<GooglePicker clientId={CLIENT_ID}
developerKey={DEVELOPER_KEY}
scope={SCOPE}
onChange={data => console.log('on change:', data)}
multiselect={true}
navHidden={true}
authImmediate={false}
viewId={'FOLDERS'}
createPicker={ (google, oauthToken) => {
const googleViewId = google.picker.ViewId.FOLDERS;
const docsView = new google.picker.DocsView(googleViewId)
.setIncludeFolders(true)
.setMimeTypes('application/vnd.google-apps.folder')
.setSelectFolderEnabled(true);
const picker = new window.google.picker.PickerBuilder()
.addView(docsView)
.setOAuthToken(oauthToken)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(()=>{
console.log('Custom picker is ready!');
});
picker.build().setVisible(true);
}}
>
<span>Click to build a picker which shows folders and you can select folders</span>
<div className="google"></div>
</GooglePicker>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
|
JavaScript
| 0 |
@@ -574,32 +574,112 @@
hange:', data)%7D%0A
+ onAuthFailed=%7Bdata =%3E console.log('on auth failed:', data)%7D%0A
@@ -1219,32 +1219,114 @@
hange:', data)%7D%0A
+ onAuthFailed=%7Bdata =%3E console.log('on auth failed:', data)%7D%0A
|
1857bfbd392609a56cbc0041455304861983c5e2
|
Fix children proptype of `Medallion` being too restrictive
|
components/Medallion/Medallion.js
|
components/Medallion/Medallion.js
|
import React, { PropTypes } from 'react';
import cx from 'classnames';
import css from './Medallion.css';
const Medallion = ({ className, variant, children, ...rest }) => (
<span
{ ...rest }
className={ cx(
css.root,
css[variant],
className,
) }
>
{ children }
</span>
);
Medallion.propTypes = {
className: PropTypes.string,
children: PropTypes.string,
variant: PropTypes.oneOf(['light', 'dark']),
};
Medallion.defaultProps = {
variant: 'light',
};
export default Medallion;
|
JavaScript
| 0.0001 |
@@ -381,30 +381,28 @@
: PropTypes.
-string
+node
,%0A variant:
|
a3cc74ea23596e3a5846665b970c3a5ed7fbad86
|
Fix this.type #2
|
lib/property.js
|
lib/property.js
|
/**
* vCard Property
* @constructor
* @memberOf vCard
* @param {String} field
* @param {String} value
* @param {Object} params
* @return {Property}
*/
function Property( field, value, params ) {
if( !(this instanceof Property) )
return new Property( value )
if( params != null )
Object.assign( this, params )
this._field = field
this._data = value
Object.defineProperty( this, '_field', { enumerable: false })
Object.defineProperty( this, '_data', { enumerable: false })
}
/**
* Constructs a vCard.Property from jCard data
* @param {Array} data
* @return {Property}
*/
Property.fromJSON = function( data ) {
var field = data[0]
var params = data[1]
if( !/text/i.test( data[2] ) )
params.value = data[2]
var value = Array.isArray( data[3] ) ?
data[3].join( ';' ) : data[3]
return new Property( field, value, params )
}
/**
* Turn a string into capitalized dash-case
* @internal used by `Property#toString()`
* @param {String} value
* @return {String}
* @ignore
*/
function capitalDashCase( value ) {
return value.replace( /([A-Z])/g, '-$1' ).toUpperCase()
}
/**
* Property prototype
* @type {Object}
*/
Property.prototype = {
constructor: Property,
/**
* Check whether the property is of a given type
* @param {String} type
* @return {Boolean}
*/
is: function( type ) {
type = ( type + '' ).toLowerCase()
return Array.isArray( type ) ?
this.type.indexOf( type ) >= 0 :
this.type === type
},
/**
* Check whether the property is empty
* @return {Boolean}
*/
isEmpty: function() {
return this._data == null &&
Object.keys( this ).length === 0
},
/**
* Clone the property
* @return {Property}
*/
clone: function() {
return new Property( this._field, this._data, this )
},
/**
* Format the property as vcf with given version
* @param {String} version
* @return {String}
*/
toString: function( version ) {
var propName = (this.group ? this.group + '.' : '') + capitalDashCase( this._field )
var keys = Object.keys( this )
var params = []
for( var i = 0; i < keys.length; i++ ) {
if (keys[i] === 'group') continue
params.push( capitalDashCase( keys[i] ) + '=' + this[ keys[i] ] )
}
return propName +
( params.length ? ';' + params.join( ';' ) : params ) + ':' +
( Array.isArray( this._data ) ? this._data.join( ';' ) : this._data )
},
/**
* Get the property's value
* @return {String}
*/
valueOf: function() {
return this._data
},
/**
* Format the property as jCard data
* @return {Array}
*/
toJSON: function() {
var params = Object.assign({},this)
if( params.value === 'text' ) {
params.value = void 0
delete params.value
}
var data = [ this._field, params, this.value || 'text' ]
switch( this._field ) {
default: data.push( this._data ); break
case 'adr':
case 'n':
data.push( this._data.split( ';' ) )
}
return data
},
}
// Exports
module.exports = Property
|
JavaScript
| 0.999999 |
@@ -1425,16 +1425,21 @@
sArray(
+this.
type ) ?
|
66279e7bc4778f8f7ac41e855661910466e9ce10
|
delete unimportant,double line
|
functions.js
|
functions.js
|
$(document).ready(function() {
//--- check if pressed enter ---
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e) {
if(e.keyCode == 13) {
$(this).trigger("enterPress");
}
})
});
};
//---reload a image
$.fn.reloadimg = function(fn) {
return this.each(function(index) {
var src = $(this).attr('src');
$(this).attr('src', src);
console.log("reload image:\nimg="+index+"\nsrc='"+src+"'");
});
};
});
//--- function basename (like PHP) ---
function basename(path) {
var b = path;
var lastChar = b.charAt(b.length - 1);
if (lastChar === '/' || lastChar === '\\') {
b = b.slice(0, -1);
}
b = b.replace(/^.*[\/\\]/g, '');
return b;
}
//--- function empty (like PHP) ---
function empty(str) {
return (!str || 0 === str.length);
}
//--- emailpattern ---
var emailpattern = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,4})$');
//--- Scroll to place ---
$(document).ready(function() {
$("a[href^='#']").click(function(event) {
event.preventDefault();
var target = $(this).attr('href');
$('html,body').animate({
scrollTop: $(target).offset().top
}, 1000);
console.log("Scroll to "+target);
});
});
function scrollto(place, valuetype) {
if(typeof valuetype == "undefined") {
var valuetype = object;
}
if(valuetype == "position") {
$('html,body').animate({
scrollTop: place
}, 1000);
return false;
}
if(valuetype == "object") {
$('html,body').animate({
scrollTop: $(place).offset().top
}, 1000);
return false;
}
}
//--- images first show after load --------------------------------------------
var images_show_after_laod = true;
$(document).ready(function() {
if(images_show_after_laod) {
$('img').each(function(){
if(!$(this).hasClass("nojsload")) {
$(this).hide();
$(this).load(function() {
$(this).fadeIn(400);
});
}
})
}
});
|
JavaScript
| 0.999728 |
@@ -1,35 +1,4 @@
-$(document).ready(function() %7B%0A
%09//-
@@ -245,16 +245,47 @@
; %0A%09%7D;%0A
+$(document).ready(function() %7B%0A
%09%0A%09//---
|
f2de19c536afd9b22124a51259037000bf049a4c
|
Add for...of and for...in loops to js demo
|
demos/js.js
|
demos/js.js
|
class Banana {
constructor(goodOrNah) {
this.quality = goodOrNah;
}
eat() {
// omnomomnomom
const om = 'om\nnom';
}
static peelTime(length) {
const magicNumber = 123;
return length * magicNumber;
}
}
const banana = new Banana(10);
banana.eat();
console.log(Banana.peelTime(100));
function makeBanana(num) {}
for (let i = 0; i < 10; i++) {
makeBanana();
}
const regex = /banana/;
const regexdos = /[.*+?^${}()|[\]\\]/g;
if (true) {}
while (true) {}
switch (fruit) {
case 'banana':
break;
default:
break;
}
const asyncFetchBananas = async () => {
let bananas = await findBananas();
const specialBanana = new Banana(11);
bananas.push(specialBanana);
}
|
JavaScript
| 0 |
@@ -386,16 +386,74 @@
ana();%0A%7D
+%0Afor (const thing of stuff) %7B%7D%0Afor (let thing in stuff) %7B%7D
%0A%0Aconst
|
dde25da7854642c85573c5b487be2d762fc5d189
|
fix #622
|
ember/app/components/settings-panels/choose-club.js
|
ember/app/components/settings-panels/choose-club.js
|
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { task } from 'ember-concurrency';
export default Component.extend({
ajax: service(),
account: service(),
classNames: ['panel', 'panel-default'],
clubs: null,
clubId: null,
messageKey: null,
error: null,
clubsWithNull: computed('clubs.[]', function() {
return [{ id: null }].concat(this.get('clubs'));
}),
club: computed('clubId', {
get() {
return this.get('clubsWithNull').findBy('id', this.get('clubId') || null);
},
set(key, value) {
this.set('clubId', value.id);
return value;
},
}),
saveTask: task(function * () {
let club = this.get('club');
let json = { clubId: club.id };
try {
yield this.get('ajax').request('/api/settings/', { method: 'POST', json });
this.setProperties({
messageKey: 'club-has-been-changed',
error: null,
});
this.get('account').set('club', (club.id === null) ? {} : club);
} catch (error) {
this.setProperties({ messageKey: null, error });
}
}).drop(),
});
|
JavaScript
| 0.000215 |
@@ -772,31 +772,113 @@
json
- = %7B clubId: club.id %7D;
+;%0A%0A if (club.id) %7B%0A json = %7B clubId: club.id %7D;%0A %7D else %7B%0A json = %7B clubId: null %7D;%0A %7D
%0A%0A
|
c09d9e82fbb1a4378026fa34a903e978df9cb5cb
|
Fix warning in DropdownButton (#380)
|
packages/components/components/dropdown/DropdownButton.js
|
packages/components/components/dropdown/DropdownButton.js
|
import React from 'react';
import PropTypes from 'prop-types';
import DropdownCaret from './DropdownCaret';
import { classnames } from 'react-components';
const DropdownButton = ({
buttonRef,
className = 'pm-button',
hasCaret = false,
isOpen,
children,
caretClassName,
...rest
}) => {
return (
<button
ref={buttonRef}
type="button"
className={classnames(['flex-item-noshrink', className])}
aria-expanded={isOpen}
{...rest}
>
<span className="mauto">
<span className={classnames([hasCaret && children && 'mr0-5'])}>{children}</span>
{hasCaret && <DropdownCaret className={caretClassName} isOpen={isOpen} />}
</span>
</button>
);
};
DropdownButton.propTypes = {
buttonRef: PropTypes.object,
caretClassName: PropTypes.string,
hasCaret: PropTypes.bool,
isOpen: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string
};
export default DropdownButton;
|
JavaScript
| 0 |
@@ -287,16 +287,59 @@
ssName,%0A
+ disabled = false,%0A loading = false,%0A
...r
@@ -538,16 +538,97 @@
isOpen%7D%0A
+ aria-busy=%7Bloading%7D%0A disabled=%7Bloading ? true : disabled%7D%0A
@@ -1145,16 +1145,75 @@
s.string
+,%0A disabled: PropTypes.bool,%0A loading: PropTypes.bool
%0A%7D;%0A%0Aexp
|
4e247c80b759c1bf1500899d199c9a5e13d9bedc
|
Fix to bug in gulp web
|
build/task.web.js
|
build/task.web.js
|
/**
* Author: Jeff Whelpley
* Date: 5/1/15
*
* Livereload for website
*/
var _ = require('lodash');
var nodemon = require('nodemon');
var livereload = require('gulp-livereload');
module.exports = function (gulp, opts) {
var startScript = opts.targetDir + '/start.js';
var shouldLiveReload = opts.livereload && opts.livereload === 'true';
var clientPlugin = (opts.pancakesConfig && opts.pancakesConfig.clientPlugin) || {};
var clientPluginLib = (opts.deploy ? clientPlugin.clientLibPath : clientPlugin.clientLibMinPath) || '';
return function () {
livereload.listen();
nodemon({
script: startScript,
watch: ['middleware', 'dist']
})
.on('restart', function () {
if (shouldLiveReload) {
setTimeout(function () {
livereload.reload();
}, 2000);
}
});
//gulp.watch(['middleware/**/*.js', 'services/**/*.js', 'utils/**/*.js'], ['test']);
gulp.watch(['app/common/**/*.less'], ['cssbuild']);
gulp.watch([clientPluginLib], ['jsbuild.pluginUtils']);
gulp.watch(['utils/*.js'], ['jsbuild.utils']);
gulp.watch(['services/resources/**/*.resource.js'], ['jsbuild.api']);
_.each(opts.pancakesConfig.modulePlugins, function (plugin) {
// gutil.log('got in plug with ' + plugin.rootDir + '/utils/*.js');
gulp.watch([plugin.rootDir + '/utils/*.js'], ['jsbuild.utils']);
});
_.each(opts.appConfigs, function (appConfig, appName) {
gulp.watch(['app/' + appName + '/**/*.less'], ['cssbuild']);
gulp.watch([
'app/' + appName + '/' + appName + '.app.js',
'app/' + appName + '/ng.config/*.js',
'app/' + appName + '/' + appName + '.app.js'
], ['jsbuild.' + appName + 'Core']);
gulp.watch([
'app/' + appName + '/partials/*.partial.js',
'app/' + appName + '/pages/*.page.js'
], ['jsbuild.' + appName + 'UI', 'jsbuild.' + appName + 'App']);
gulp.watch(['app/' + appName + '/utils/*.js'], ['jsbuild.' + appName + 'Utils']);
gulp.watch([
'app/' + appName + '/filters/*.js',
'app/' + appName + '/ng.directives/*.js',
'app/' + appName + '/jng.directives/*.js'
], ['jsbuild.' + appName + 'Other']);
});
};
};
|
JavaScript
| 0 |
@@ -1929,12 +1929,11 @@
+ '
-Core
+App
'%5D);
|
5193925993c0a5805eb769c83b8a149db8570e39
|
Clean up
|
server.js
|
server.js
|
var express = require('express');
var request = require('request-promise');
var cheerio = require('cheerio');
var app = express();
var HOME_URL = "http://www.laundryview.com/lvs.php";
var ROOM_URL = "http://classic.laundryview.com/laundry_room.php?view=c&lr=ROOM_ID";
function getLaundryRooms() {
return request(HOME_URL)
.then(function(html) {
// Utilize cheerio to 'jQuerify' the returned HTML
var $ = cheerio.load(html);
var rooms = {};
var i = 0;
// Generate a Javascript object mapping laundry room id to its name
$('.a-room').each(function() {
var room = $(this);
// Grab the laundry room's ID from each room's URL
var roomId = room.attr('href').replace(/\D/g, '');
rooms[roomId] = {
location: room.text().trim()
}
i++;
});
return rooms;
})
.catch(function(err) {
return err;
});
}
app.get('/laundry', function(req, res) {
getLaundryRooms()
.then(function(response) {
res.json(response);
})
.catch(function(err) {
res.send(err);
});
});
app.get('/laundry/:id', function(req, res) {
getLaundryRooms()
.then(function(response) {
var rooms = response;
var roomName = rooms[req.params.id].location;
if (roomName) {
request(ROOM_URL.replace('ROOM_ID', req.params.id))
.then(function(html) {
var $ = cheerio.load(html);
// Returns an array of laundry machine id DOM elements
var machineIds = $('.desc');
// Returns an array of laundry machine image DOM elements
var machineTypes = $('img', '.bgicon');
// Returns an array of laundry machine status DOM elements
var machineStatuses = $('.stat');
// LaundryView has a div containing info regarding machine availabilities
var availabilities = $('.monitor-total').text().match(/^\d+|\d+\b|\d+(?=\w)/g);
var availableWashers = parseInt(availabilities[0], 10);
var availableDryers = parseInt(availabilities[2], 10);
var statuses = {
location: roomName,
washers: 0,
dryers: 0,
total_machines: 0,
available_washers: 0,
available_dryers: 0,
out_of_service: 0,
machines: {}
};
// Determine number of washers, dryers, and out of service machines
for (var i = 0; i < machineTypes.length; i++) {
var mt = $(machineTypes.get(i)).attr('src');
if (mt.indexOf('washer_unavailable') > -1 ||
mt.indexOf('dryer_unavailable') > -1) {
statuses.out_of_service++;
}
else if (mt.indexOf('washer') > -1) {
statuses.washers += 1;
}
else {
statuses.dryers += 1;
}
}
statuses.available_washers += availableWashers;
statuses.available_dryers += availableDryers;
statuses.total_machines += (statuses.washers + statuses.dryers);
for (var i = 0; i < machineIds.length; i++) {
var machineId = $(machineIds.get(i)).text().trim();
var machineStatus = $(machineStatuses.get(i)).text().trim();
var isWasher = $(machineTypes.get(i)).attr('src').indexOf('washer') > -1;
var machineType = isWasher ? 'washer' : 'dryer';
statuses['machines'][machineId] = {
type: machineType,
status: machineStatus
};
}
res.json(statuses);
})
.catch(function(err) {
res.send(err);
});
}
})
.catch(function(err) {
res.send(err);
});
});
app.listen('4000');
exports = module.exports = app;
|
JavaScript
| 0.000002 |
@@ -357,64 +357,8 @@
) %7B%0A
- // Utilize cheerio to 'jQuerify' the returned HTML
%0A
@@ -440,82 +440,8 @@
0;%0A%0A
- // Generate a Javascript object mapping laundry room id to its name%0A
@@ -490,16 +490,18 @@
ar room
+
= $(this
@@ -506,68 +506,8 @@
is);
-%0A%0A // Grab the laundry room's ID from each room's URL
%0A
@@ -522,19 +522,16 @@
roomId
-
= room.a
@@ -558,24 +558,25 @@
/%5CD/g, '');%0A
+%0A
room
@@ -588,26 +588,16 @@
mId%5D = %7B
-%0A
locatio
@@ -617,24 +617,16 @@
).trim()
-%0A
%7D%0A
@@ -1025,19 +1025,16 @@
r rooms
-
= respon
@@ -1037,16 +1037,53 @@
sponse;%0A
+%0A if (rooms%5Breq.params.id%5D) %7B%0A
va
@@ -1125,16 +1125,24 @@
ocation;
+%0A %7D
%0A%0A
@@ -2941,24 +2941,25 @@
able_dryers
+
+= available
@@ -3002,16 +3002,19 @@
achines
+
+= (stat
@@ -3277,16 +3277,21 @@
sWasher
+
= $(mach
@@ -3373,16 +3373,18 @@
ineType
+
= isWash
@@ -3605,24 +3605,95 @@
%7D)%0A
+ // Something went wrong with the request to laundry room URL%0A
.c
@@ -3762,26 +3762,197 @@
%7D%0A
-%7D)
+ else %7B%0A res.status(404).send(%7B error: %22Received an invalid laundry room id%22 %7D);%0A %7D%0A %7D)%0A // Something went wrong with the request to LaundryView home page
%0A .catch(
|
0b2426d9cff15318cf4a03d94e1c1dbd7a57d514
|
Fix jslint issues
|
server.js
|
server.js
|
var http = require("http");
var wkhtmltopdf = require('wkhtmltopdf');
var qs = require('querystring');
http.createServer(function(request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var post = qs.parse(body);
if ('html' in post) {
response.writeHead(200, {
'Content-Type': 'application/pdf',
});
var html = post['html'];
delete post['html'];
wkhtmltopdf(html, post, function(code, signal) {
console.log(code);
console.log(signal);
if (code !== null) {
response.writeHead(500, "Internal Server Error", {'Content-Type': 'text/html'});
response.end();
console.log(code);
}
}).pipe(response);
} else {
response.writeHead(400, "Bad Request", {'Content-Type': 'text/html'});
response.end();
};
});
} else {
response.writeHead(200, "OK", {'Content-Type': 'text/html'});
response.end();
};
}).listen(5001);
console.log("Server is running at http://127.0.0.1:5001")
|
JavaScript
| 0.000002 |
@@ -1,12 +1,27 @@
+%22use strict%22;%0A%0A
var http = r
@@ -138,16 +138,17 @@
function
+
(request
@@ -161,16 +161,18 @@
onse) %7B%0A
+
if (re
@@ -186,16 +186,17 @@
ethod ==
+=
'POST')
@@ -198,24 +198,28 @@
OST') %7B%0A
+
+
var body = '
@@ -221,24 +221,28 @@
y = '';%0A
+
+
request.on('
@@ -262,24 +262,30 @@
on (data) %7B%0A
+
body +
@@ -300,13 +300,21 @@
+
+
%7D);%0A%0A
+
@@ -347,24 +347,30 @@
() %7B%0A
+
+
var post = q
@@ -386,38 +386,90 @@
ody)
-;%0A
+,%0A html = post.html;%0A
+
if (
-'
html
-' in post) %7B%0A
+ !== undefined) %7B%0A
@@ -508,16 +508,26 @@
+
+
'Content
@@ -553,16 +553,24 @@
n/pdf',%0A
+
@@ -585,41 +585,16 @@
-var html = post%5B'html'%5D;%0A
+
-
dele
@@ -604,18 +604,23 @@
post
-%5B'
+.
html
-'%5D
;%0A
+
@@ -659,21 +659,14 @@
tion
+
(code
-, signal
) %7B%0A
@@ -679,58 +679,8 @@
-console.log(code);%0A console.log(signal);%0A
@@ -702,24 +702,36 @@
!== null) %7B%0A
+
@@ -815,32 +815,44 @@
%7D);%0A
+
+
response.end();%0A
@@ -863,16 +863,28 @@
+
+
console.
@@ -908,10 +908,28 @@
+
-%7D%0A
+ %7D%0A
@@ -947,24 +947,30 @@
(response);%0A
+
%7D else
@@ -972,32 +972,40 @@
else %7B%0A
+
+
response.writeHe
@@ -1051,32 +1051,40 @@
'text/html'%7D);%0A
+
response
@@ -1095,25 +1095,34 @@
();%0A
+
%7D
-;
%0A
+
%7D);%0A
%7D
@@ -1117,16 +1117,18 @@
%7D);%0A
+
%7D else
@@ -1130,24 +1130,28 @@
else %7B%0A
+
+
response.wri
@@ -1196,24 +1196,28 @@
xt/html'%7D);%0A
+
response
@@ -1230,10 +1230,11 @@
;%0A
+
%7D
-;
%0A%7D).
@@ -1305,9 +1305,10 @@
1:5001%22)
+;
%0A
|
7426715d3b1d5f4bfd6511f8523b2f0af9878918
|
scale entities before adding to canvas
|
site/source/javascripts/pages/index/entity_processor.js
|
site/source/javascripts/pages/index/entity_processor.js
|
/* Omega Index Page Entity Processor Mixin
*
* Copyright (C) 2014 Mohammed Morsi <[email protected]>
* Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt
*/
Omega.Pages.IndexEntityProcessor = {
/// Process entity retrieved from server
process_entity : function(entity){
var user_owned = this.session != null &&
entity.user_id == this.session.user_id;
var same_scene = this.canvas.root &&
this.canvas.root.id == entity.system_id;
var in_scene = this.canvas.has(entity.id);
/// store entity locally
entity = this._store_entity(entity);
/// load system entity is in
this._load_entity_system(entity);
if(entity.alive()){
/// add to navigation
this._add_nav_entity(entity);
/// add to scene if appropriate
if(same_scene && !in_scene){
this.canvas.add(entity);
this._scale_entity(entity)
}
/// start tracking entity
/// TODO only if not already tracking
if(user_owned || same_scene) this.track_entity(entity);
}
},
/// Add entity to entities list if not present
_add_nav_entity : function(entity){
if(!this.canvas.controls.entities_list.has(entity.id)){
var item = {id: entity.id, text: entity.id, data: entity};
this.canvas.controls.entities_list.add(item);
}
},
/// Add system to locations list if not present
_add_nav_system : function(system){
if(!this.canvas.controls.locations_list.has(system.id)){
var sitem = {id: system.id, text: system.name,
data: system, index: 1};
this.canvas.controls.locations_list.add(sitem);
}
},
/// Add galaxy to locations list if no present
_add_nav_galaxy : function(galaxy){
if(!this.canvas.controls.locations_list.has(galaxy.id)){
var gitem = {id: galaxy.id, text: galaxy.name,
data: galaxy, color : 'blue'};
this.canvas.controls.locations_list.add(gitem);
}
},
/// Store entity in registry, copying locally-initialized
/// attributes from original entity
_store_entity : function(entity){
var local = this.entity(entity.id);
if(local) local.update(entity);
else this.entity(entity.id, entity);
return local || entity;
},
/// Process entities retrieved from server
process_entities : function(entities){
for(var e = 0; e < entities.length; e++){
var entity = entities[e];
this.process_entity(entity);
}
},
/// Load system which entity is in
_load_entity_system : function(entity){
var _this = this;
var system = Omega.UI.Loader.load_system(entity.system_id, this,
function(solar_system) { _this.process_system(solar_system); });
if(system && system != Omega.UI.Loader.placeholder)
entity.update_system(system);
},
/// Update references to/from system
_update_system_references : function(system){
for(var e in this.entities){
/// Set system on entities whose system_id == system.id
if(this.entities[e].system_id == system.id)
this.entities[e].update_system(system);
/// Update all system's children from entities list
/// (will update jg & other references to system)
else if(this.entities[e].json_class == 'Cosmos::Entities::SolarSystem')
this.entities[e].update_children_from(this.all_entities());
}
},
/// Load galaxy which system is in
_load_system_galaxy : function(system){
var _this = this;
var galaxy = Omega.UI.Loader.load_galaxy(system.parent_id, this,
function(galaxy) { _this.process_galaxy(galaxy) });
if(galaxy && galaxy != Omega.UI.Loader.placeholder)
galaxy.set_children_from(this.all_entities());
},
/// Load all the systems the specified system has interconnections to
_load_system_interconns : function(system){
var _this = this;
var gates = system.jump_gates();
for(var j = 0; j < gates.length; j++){
var gate = gates[j];
Omega.UI.Loader.load_system(gate.endpoint_id, this,
function(system){
_this.process_system(system);
});
}
},
/// Helper to wire up system refresh callback if not already wired up
_process_system_on_refresh : function(system){
/// If we've already registered callback just return
if(system._process_on_refresh) return;
/// Register callback to invoke process system on system refresh
var _this = this;
system._process_on_refresh = function(){ _this.process_system(system); }
system.removeEventListener('refreshed', system._process_on_refresh);
system.addEventListener('refreshed', system._process_on_refresh);
},
/// Process system retrieved from server
process_system : function(system){
if(system == null) return;
/// add system to navigation & update references
this._add_nav_system(system);
this._update_system_references(system);
this._load_system_galaxy(system);
/// load missing jump gate endpoints, update children
this._load_system_interconns(system);
system.update_children_from(this.all_entities());
/// process system whenever refreshed from server
this._process_system_on_refresh(system);
},
/// Helper to wire up galaxy refresh callback if not already wired up
_process_galaxy_on_refresh : function(galaxy){
/// If we've already registered allback just return
if(galaxy._process_on_refresh) return;
/// Register callback to invoke process galaxy on galaxy refresh
var _this = this;
galaxy._process_on_refresh = function(){ _this.process_galaxy(galaxy); }
galaxy.removeEventListener('refreshed', galaxy._process_on_refresh);
galaxy.addEventListener('refreshed', galaxy._process_on_refresh);
},
/// Load all interconnections under galaxy
_load_galaxy_interconns : function(galaxy){
Omega.UI.Loader.load_interconnects(galaxy, this, function(){});
},
/// Process galaxy retrieved from server
process_galaxy : function(galaxy){
if(galaxy == null) return;
/// add galaxy to navigation
this._add_nav_galaxy(galaxy);
/// update galaxy children
galaxy.set_children_from(this.all_entities());
/// load interconnections
this._load_galaxy_interconns(galaxy);
/// this process galaxy whenever refreshed from server
this._process_galaxy_on_refresh(galaxy);
}
};
|
JavaScript
| 0 |
@@ -862,26 +862,29 @@
his.
-canvas.add
+_scale_entity
(entity)
;%0A
@@ -875,25 +875,24 @@
tity(entity)
-;
%0A thi
@@ -893,37 +893,34 @@
this.
-_scale_entity
+canvas.add
(entity)
%0A %7D
@@ -907,24 +907,25 @@
.add(entity)
+;
%0A %7D%0A%0A
|
755acb4a0e6ea8861e6f26018ef8a7ef948f4426
|
add test proving get() decrypts activities
|
packages/plugin-conversation/test/integration/spec/get.js
|
packages/plugin-conversation/test/integration/spec/get.js
|
/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
import '../..';
import CiscoSpark from '@ciscospark/spark-core';
import {assert} from '@ciscospark/test-helper-chai';
import sinon from '@ciscospark/test-helper-sinon';
import testUsers from '@ciscospark/test-helper-test-users';
import fh from '@ciscospark/test-helper-file';
import makeLocalUrl from '@ciscospark/test-helper-make-local-url';
import {map} from 'lodash';
describe(`plugin-conversation`, function() {
this.timeout(120000);
let mccoy, participants, spark, spock;
before(() => testUsers.create({count: 3})
.then((users) => {
participants = [spock, mccoy] = users;
spark = new CiscoSpark({
credentials: {
authorization: spock.token
}
});
return spark.mercury.connect();
}));
after(() => spark && spark.mercury.disconnect());
describe(`#download()`, () => {
let sampleImageSmallOnePng = `sample-image-small-one.png`;
let conversation;
before(() => spark.conversation.create({participants})
.then((c) => {conversation = c;}));
before(() => fh.fetch(sampleImageSmallOnePng)
.then((res) => {sampleImageSmallOnePng = res;}));
it(`downloads and decrypts an encrypted file`, () => spark.conversation.share(conversation, [sampleImageSmallOnePng])
.then((activity) => spark.conversation.download(activity.object.files.items[0]))
.then((f) => assert.eventually.isTrue(fh.isMatchingFile(f, sampleImageSmallOnePng))));
it(`emits download progress events for encrypted files`, () => spark.conversation.share(conversation, [sampleImageSmallOnePng])
.then((activity) => {
const spy = sinon.spy();
return spark.conversation.download(activity.object.files.items[0])
.on(`progress`, spy)
.then(() => assert.called(spy));
}));
it(`downloads and decrypts a non-encrypted file`, () => spark.conversation.download({url: makeLocalUrl(`/sample-image-small-one.png`)})
.then((f) => assert.eventually.isTrue(fh.isMatchingFile(f, sampleImageSmallOnePng))));
it(`emits download progress events for non-encrypted files`, () => {
const spy = sinon.spy();
return spark.conversation.download({url: makeLocalUrl(`/sample-image-small-one.png`)})
.on(`progress`, spy)
.then((f) => assert.eventually.isTrue(fh.isMatchingFile(f, sampleImageSmallOnePng)))
.then(() => assert.called(spy));
});
});
describe(`#get()`, () => {
let conversation;
before(() => spark.conversation.create({participants: [mccoy.id]})
.then((c) => {conversation = c;}));
it(`retrieves a single conversation by url`, () => spark.conversation.get({url: conversation.url})
.then((c) => {
assert.equal(c.id, conversation.id);
assert.equal(c.url, conversation.url);
}));
it(`retrieves a single conversation by id`, () => spark.conversation.get({id: conversation.id})
.then((c) => {
assert.equal(c.id, conversation.id);
assert.equal(c.url, conversation.url);
}));
it(`retrieves a 1:1 conversation by userId`, () => spark.conversation.get({user: mccoy})
.then((c) => {
assert.equal(c.id, conversation.id);
assert.equal(c.url, conversation.url);
}));
});
describe(`#list()`, () => {
let conversation1, conversation2;
before(() => Promise.all([
spark.conversation.create({participants})
.then((c) => {conversation1 = c;}),
spark.conversation.create({participants})
.then((c) => {conversation2 = c;})
]));
it(`retrieves a set of conversations`, () => spark.conversation.list({
conversationsLimit: 2
})
.then((conversations) => {
assert.include(map(conversations, `url`), conversation1.url);
assert.include(map(conversations, `url`), conversation2.url);
}));
});
describe(`#listLeft()`, () => {
let conversation;
before(() => spark.conversation.create({participants})
.then((c) => {conversation = c;}));
it(`retrieves the conversations the current user has left`, () => spark.conversation.listLeft()
.then((c) => {
assert.lengthOf(c, 0);
return spark.conversation.leave(conversation);
})
.then(() => spark.conversation.listLeft())
.then((c) => {
assert.lengthOf(c, 1);
assert.equal(c[0].url, conversation.url);
}));
});
describe(`#listActivities()`, () => {
let conversation;
before(() => spark.conversation.create({participants})
.then((c) => {
conversation = c;
assert.lengthOf(conversation.participants.items, 3);
return spark.conversation.post(conversation, {displayName: `first message`});
}));
it(`retrieves activities for the specified conversation`, () => spark.conversation.listActivities({conversationId: conversation.id})
.then((activities) => {
assert.isArray(activities);
assert.lengthOf(activities, 2);
}));
});
describe(`#listMentions()`, () => {
let spark2;
before(() => {
spark2 = new CiscoSpark({
credentials: {
authorization: mccoy.token
}
});
return spark2.mercury.connect();
});
after(() => spark2 && spark2.mercury.disconnect());
let conversation;
before(() => spark.conversation.create({participants})
.then((c) => {
conversation = c;
assert.lengthOf(conversation.participants.items, 3);
}));
it(`retrieves activities in which the current user was mentioned`, () => spark2.conversation.post(conversation, {
displayName: `Green blooded hobgloblin`,
content: `<spark-mention data-object-type="person" data-object-id="${spock.id}">Green blooded hobgloblin</spark-mention>`,
mentions: {
items: [{
id: `${spock.id}`,
objectType: `person`
}]
}
})
.then((activity) => {
return spark.conversation.listMentions({sinceDate: Date.parse(activity.published) - 1})
.then((mentions) => {
assert.lengthOf(mentions, 1);
assert.equal(mentions[0].url, activity.url);
});
}));
});
});
|
JavaScript
| 0.000001 |
@@ -3303,32 +3303,509 @@
url);%0A %7D));
+%0A%0A it(%60decrypts the contents of activities in the retrieved conversation%60, () =%3E spark.conversation.post(conversation, %7B%0A displayName: %60Test Message%60%0A %7D)%0A .then(() =%3E spark.conversation.get(%7Burl: conversation.url%7D, %7BactivitiesLimit: 50%7D))%0A .then((c) =%3E %7B%0A const posts = c.activities.items.filter((activity) =%3E activity.verb === %60post%60);%0A assert.lengthOf(posts, 1);%0A assert.equal(posts%5B0%5D.object.displayName, %60Test Message%60);%0A %7D));
%0A %7D);%0A%0A descri
|
05c5aad49bfee8925e1768cfc69484744fc289bd
|
Fix it to accept whole pattern objects and rename findPartialKey to findPartials
|
packages/patternengine-node-twig/lib/engine_handlebars.js
|
packages/patternengine-node-twig/lib/engine_handlebars.js
|
/*
* handlebars pattern engine for patternlab-node - v0.15.1 - 2015
*
* Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
* Licensed under the MIT license.
*
* Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
*
*/
/*
* ENGINE SUPPORT LEVEL:
*
* Full. Partial calls and lineage hunting are supported. Handlebars does not
* support the mustache-specific syntax extensions, style modifiers and pattern
* parameters, because their use cases are addressed by the core Handlebars
* feature set.
*
*/
"use strict";
var Handlebars = require('handlebars');
var engine_handlebars = {
engine: Handlebars,
engineName: 'handlebars',
engineFileExtension: '.hbs',
// partial expansion is only necessary for Mustache templates that have
// style modifiers or pattern parameters (I think)
expandPartials: false,
// regexes, stored here so they're only compiled once
findPartialsRE: /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g,
findListItemsRE: /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g,
// render it
renderPattern: function renderPattern(template, data, partials) {
if (partials) {
Handlebars.registerPartial(partials);
}
var compiled = Handlebars.compile(template);
return compiled(data);
},
registerPartial: function (oPattern) {
Handlebars.registerPartial(oPattern.key, oPattern.template);
},
// find and return any {{> template-name }} within pattern
findPartials: function findPartials(pattern) {
var matches = pattern.template.match(this.findPartialsRE);
return matches;
},
findPartialsWithStyleModifiers: function () {
// TODO: make the call to this from oPattern objects conditional on their
// being implemented here.
return [];
},
// returns any patterns that match {{> value(foo:"bar") }} or {{>
// value:mod(foo:"bar") }} within the pattern
findPartialsWithPatternParameters: function () {
// TODO: make the call to this from oPattern objects conditional on their
// being implemented here.
return [];
},
findListItems: function (pattern) {
var matches = pattern.template.match(this.findListItemsRE);
return matches;
},
// given a pattern, and a partial string, tease out the "pattern key" and
// return it.
findPartialKey: function (partialString) {
var partialKey = partialString.replace(this.findPartialsRE, '$1');
return partialKey;
}
};
module.exports = engine_handlebars;
|
JavaScript
| 0 |
@@ -1224,24 +1224,23 @@
Pattern(
-template
+pattern
, data,
@@ -1359,17 +1359,33 @@
compile(
-t
+pattern.extendedT
emplate)
@@ -2436,19 +2436,16 @@
dPartial
-Key
: functi
@@ -2480,19 +2480,16 @@
partial
-Key
= parti
@@ -2555,11 +2555,8 @@
tial
-Key
;%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.