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
|
---|---|---|---|---|---|---|---|
d8d0bf35cde7c21176f5c8e2acd713c87538f778 | Set the real boards sizes | js/index.js | js/index.js | (function () {
var game = null
, $aboutWindow = $(".window-about")
, $closeAboutBtn = $(".close-about")
, $game = $(".game-info")
, $enterName = $(".enter-name")
, $congrats = $(".congrats")
, $nameInput = $("form input.user-name")
, $time = $(".time")
, $pairsCount = $(".pairs-count")
, $highscores = $(".highscores")
, $body = $(document.body)
, $skillSelect = $("select")
, $gameSkillType = $("span.game-skill-type")
;
function closeAbout() {
if (game === null) {
newGame();
}
$aboutWindow.addClass("hide");
}
$closeAboutBtn.on("click", closeAbout);
function newGame() {
if (game) {
clearInterval(game.timer);
clearInterval(game.winInterval);
$congrats.addClass("hide");
$game.removeClass("bg-win-purple", "bg-win");
$time.html(0);
$pairsCount.html(0);
}
var gameSize = gameSkill === "little" ? {
x: 1//6
, y: 2 //5
} : {
x: 2// 10
, y: 2// 6
};
game = new Match(".game", {
templateElm: ".templates > div"
, autoremove: false
, size: gameSize
, step: {
x: 115
, y: 105
}
}, [
{
img: "images/1-star.png"
}
, {
img: "images/10-musical-note.png"
}
, {
img: "images/11-sun.png"
}
, {
img: "images/12-peace-sign.png"
}
, {
img: "images/13-moon.png"
}
, {
img: "images/14-heart.png"
}
, {
img: "images/15-zig-zag.png"
}
, {
img: "images/16-colors.png"
}
, {
img: "images/17-clover.png"
}
, {
img: "images/17-star.png"
}
, {
img: "images/18-apple.png"
}
, {
img: "images/19-castle.png"
}
, {
img: "images/2-butterfly.png"
}
, {
img: "images/20-dolar.png"
}
, {
img: "images/21-circles.png"
}
, {
img: "images/22-bars.png"
}
, {
img: "images/23-ball.png"
}
, {
img: "images/24-carpet.png"
}
, {
img: "images/25-rectangle.png"
}
, {
img: "images/26-grey-park.png"
}
, {
img: "images/27-question-mark.png"
}
, {
img: "images/28-tree.png"
}
, {
img: "images/29-sandtime.png"
}
, {
img: "images/3-chinese.png"
}
, {
img: "images/30-diode.png"
}
, {
img: "images/4-potion.png"
}
, {
img: "images/5-happy-face.png"
}
, {
img: "images/6-stop.png"
}
, {
img: "images/7-house.png"
}
, {
img: "images/8-black-sign.png"
}
, {
img: "images/8-chees.png"
}
]);
closeAbout();
game.on("win", function () {
setTimeout(function () {
var time = game.passedTime
, pairs = game.flippedPairs
;
$game.addClass("bg-win");
game.winInterval = setInterval(function () {
$game.toggleClass("bg-win-purple");
}, 500);
if (Highscores.check(pairs, time, gameSkill)) {
$enterName.removeClass("hide");
setTimeout(function() {
$nameInput.focus();
}, 10);
} else {
$enterName.addClass("hide");
}
$congrats.removeClass("hide");
}, 1500);
});
game.on("activate", function (elm) {
$(elm).removeClass("unspin").addClass("spin");
});
game.on("deactivate", function (elm) {
$(elm).removeClass("spin").addClass("unspin");
});
game.on("success", function (elm1, elm2) {
var $elm1 = $(elm1)
, $elm2 = $(elm2)
;
setTimeout(function() {
$elm1.addClass("spinned-zoom-out");
$elm2.addClass("spinned-zoom-out");
setTimeout(function() {
$elm1.remove();
$elm2.remove();
}, 900);
}, 1000);
});
game.on("time", function (time) {
var sec = Math.floor(time / 1000);
$time.html(sec);
game.passedTime = sec;
});
game.on("pair-flip", function () {
$pairsCount.html(game.flippedPairs + 1);
});
game.start();
}
function showHighscores() {
var hScores = Highscores.get(gameSkill);
function forTable(selector, scores) {
var elms = $(selector + " table tbody tr");
elms.each(function (cRow, i) {
var $cRow = $(cRow)
, $tds = $("td", $cRow)
;
scores[i] = scores[i] || {
name: ""
, time: ""
, pairs: ""
, timestamp: ""
};
$tds.eq(1).text(scores[i].name);
$tds.eq(2).text(scores[i].time);
$tds.eq(4).text(scores[i].pairs);
$cRow.attr("data-timestamp", scores[i].timestamp.toString());
$cRow.removeClass("selected");
});
}
forTable(".fastest-times", hScores.fastestTimes);
forTable(".fewest-pairs", hScores.fewestPairs);
$highscores.show();
}
$(".highscores .ok-btn").on("click", function () {
$highscores.hide();
});
// Restart game
$(".restart").on("click", newGame);
// Toggle colors
$(".toggle-colors").on("click", function () {
$body.toggleClass("grayscale");
});
// Show highscores
$(".show-highscores").on("click", showHighscores);
// Reset highscores
$(".reset-btn").on("click", function () {
Highscores.reset(gameSkill);
showHighscores();
});
// Form submit
$("form").on("submit", function (e) {
var name = $nameInput.val()
, inserted = Highscores.insert(name, game.passedTime, game.flippedPairs, gameSkill)
;
$enterName.addClass("hide");
showHighscores();
var $toSelect = $("[data-timestamp='" + inserted.timestamp + "']");
$toSelect.addClass("selected");
e.preventDefault();
});
$(".btn-about").on("click", function (e) {
$aboutWindow.toggleClass("hide");
});
$skillSelect.on("change", function () {
gameSkill = this.value;
$body.attr("game-skill", gameSkill);
$gameSkillType.text(gameSkill.charAt(0).toUpperCase() + gameSkill.substring(1));
if (game) {
newGame();
}
}).trigger("change");
})();
| JavaScript | 0.000001 | @@ -1048,11 +1048,8 @@
x:
-1//
6%0A
@@ -1065,12 +1065,8 @@
y:
-2 //
5%0A
@@ -1091,20 +1091,16 @@
x:
- 2//
10%0A
@@ -1113,12 +1113,8 @@
, y:
- 2//
6%0A
|
f26666814594722a92215166234e08d5ff073125 | Update index.js | js/index.js | js/index.js | $(document).ready(function() {
getWeather(); //Get the initial weather.
setInterval(getWeather, 600000); //Update the weather every 10 minutes.
});
// var d = new Date();
// document.getElementById("currentDate").innerHTML = d;
// 22721202
function getWeather() {
$.simpleWeather({
woeid: '1096823',
location: '',
unit: 'c',
success: function(weather) {
var newDate = new Date();
var formattedDate = newDate.format("dddd, mmmm dS");
html = '<div class="weatherimage"><img src="' + weather.image + '"> </div>'
html += '<div class="currentweather">' + weather.temp + '°' + weather.units.temp + '</div>';
html += '<div class="currentDate">' + formattedDate + '</div>';
html += '<div class="forecast">'
for (var i = 0; i < 5; i++) {
html += '<div class="forecast' + [i] + '"><img src="' + weather.forecast[i].thumbnail + '"> <br>' + weather.forecast[i].day + ' - ' + weather.forecast[i].text + '<br> High: ' + weather.forecast[i].high + '°C <br> Low: ' + weather.forecast[i].low + '°C <br> </div>';
}
html += '</div>'
$("#mainDiv").html(html);
},
error: function(error) {
$("#mainDiv").html('<p>' + error + '</p>');
}
});
}
/*
for (var i = 0; i < 4; i++) {
html += '<div class="forecast' + [i] + '"><img src="' + weather.forecast[i].thumbnail + '"> <br>' + weather.forecast[i].day + ' - ' + weather.forecast[i].text + '<br> High: ' + weather.forecast[i].high + '°C <br> Low: ' + weather.forecast[i].low + '°C <br> </div>';
}
*/
/*
function getWeather() {
$.simpleWeather({
woeid: '1096823',
location: '',
unit: 'c',
success: function(weather) {
var newDate = new Date();
var formattedDate = newDate.format("dddd, mmmm dS");
html = '<div class="weatherimage"><img src="' + weather.image + '"> </div>'
html += '<div class="currentweather"><h2>' + weather.temp + '°' + weather.units.temp + '</h2> </div>';
html += '<div class="currentDate">' + formattedDate + '</div>';
// html += '<ul><li>'+weather.city+', '+weather.region+'</li>';
// html += '<li class="currently">'+weather.currently+'</li></div>';
html += '<div class="forecast">'
for (var i = 0; i < 4; i++) {
html += '<div class="'+[i]+'"><img src="' + weather.forecast[i].thumbnail + '"> <br>' + weather.forecast[i].day + ' - ' + weather.forecast[i].text + '<br> High: ' + weather.forecast[i].high + '°C <br> Low: ' + weather.forecast[i].low + '°C <br> </div>';
}
html += '</div>'
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
}
*/
| JavaScript | 0.000002 | @@ -154,101 +154,8 @@
);%0A%0A
-// var d = new Date();%0A// document.getElementById(%22currentDate%22).innerHTML = d;%0A// 22721202%0A%0A
func
@@ -214,32 +214,49 @@
eid: '1096823',
+// WOEID Location
%0A locatio
@@ -694,28 +694,16 @@
/div%3E';%0A
- %0A
@@ -1086,29 +1086,17 @@
%7D%0A
-
%0A
+
@@ -1117,17 +1117,16 @@
/div%3E'%0A%0A
-%0A
@@ -1277,1654 +1277,6 @@
%7D);%0A
+
%7D%0A
-%0A%0A/*%0A for (var i = 0; i %3C 4; i++) %7B%0A html += '%3Cdiv class=%22forecast' + %5Bi%5D + '%22%3E%3Cimg src=%22' + weather.forecast%5Bi%5D.thumbnail + '%22%3E %3Cbr%3E' + weather.forecast%5Bi%5D.day + ' - ' + weather.forecast%5Bi%5D.text + '%3Cbr%3E High: ' + weather.forecast%5Bi%5D.high + '°C %3Cbr%3E Low: ' + weather.forecast%5Bi%5D.low + '°C %3Cbr%3E %3C/div%3E';%0A %7D%0A*/%0A%0A%0A/*%0Afunction getWeather() %7B%0A $.simpleWeather(%7B%0A woeid: '1096823', %0A location: '',%0A unit: 'c',%0A success: function(weather) %7B%0A var newDate = new Date();%0A var formattedDate = newDate.format(%22dddd, mmmm dS%22);%0A html = '%3Cdiv class=%22weatherimage%22%3E%3Cimg src=%22' + weather.image + '%22%3E %3C/div%3E'%0A html += '%3Cdiv class=%22currentweather%22%3E%3Ch2%3E' + weather.temp + '°' + weather.units.temp + '%3C/h2%3E %3C/div%3E';%0A html += '%3Cdiv class=%22currentDate%22%3E' + formattedDate + '%3C/div%3E';%0A %0A // html += '%3Cul%3E%3Cli%3E'+weather.city+', '+weather.region+'%3C/li%3E';%0A // html += '%3Cli class=%22currently%22%3E'+weather.currently+'%3C/li%3E%3C/div%3E';%0A%0A html += '%3Cdiv class=%22forecast%22%3E'%0A for (var i = 0; i %3C 4; i++) %7B%0A html += '%3Cdiv class=%22'+%5Bi%5D+'%22%3E%3Cimg src=%22' + weather.forecast%5Bi%5D.thumbnail + '%22%3E %3Cbr%3E' + weather.forecast%5Bi%5D.day + ' - ' + weather.forecast%5Bi%5D.text + '%3Cbr%3E High: ' + weather.forecast%5Bi%5D.high + '°C %3Cbr%3E Low: ' + weather.forecast%5Bi%5D.low + '°C %3Cbr%3E %3C/div%3E';%0A %7D%0A html += '%3C/div%3E'%0A%0A $(%22#weather%22).html(html);%0A %7D,%0A error: function(error) %7B%0A $(%22#weather%22).html('%3Cp%3E' + error + '%3C/p%3E');%0A %7D%0A %7D);%0A%7D%0A*/%0A
|
2b61723b9c1bd3a2b0fff7fb04b70b97bc1fea24 | Update modal.js | js/modal.js | js/modal.js | /*$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
$('#myModal').on('show.bs.modal', function () {
$(this).find('.modal-body').css({
width:'auto', //probably not needed
height:'auto', //probably not needed
'max-height':'100%'
});
});*/
var $modal = $('.modal');
// Show loader & then get content when modal is shown
$modal.on('show.bs.modal', function(e) {
var paragraphs = $(e.relatedTarget).data('paragraphs');
$(this)
//.addClass('modal-scrollfix')
.find('.modal-body')
.html('loading...')
.load('https://neuroimagem-pucrs.github.io/team/' + paragraphs, function() {
// Use Bootstrap's built-in function to fix scrolling (to no avail)
//$modal
//.removeClass('modal-scrollfix')
//.modal('handleUpdate');
});
});
| JavaScript | 0.000001 | @@ -850,18 +850,91 @@
e');
+%0A
+ $('body').css('overflow','hidden');%0A$('body').css('position','fixed');
%0A %7D);
|
bdd5d8ad898cbf720f9dfc698fa04cacb95787fa | 삭제 버튼 클릭 시 트윗이 삭제되지 않는 버그 수정 | js/popup.js | js/popup.js | (function() {
var tweetFormatStr =
'<div class="outerbox" id="{0}">'
+ '<img class="icon" src="{1}">'
+ '<div class="msgbox">'
+ '<div class="header">'
+ '<span class="userId">{2}</span>'
+ ' '
+ '<span class="name">{3}</span>'
+ ' '
+ '<a class="deleteLink" userId={2} href="#" onclick="deleteTweet({0})">'
+ '<img class="trashcan" src="http://intra1.synap.co.kr/season2/images/trashcan_icon.gif" alt="delete"/>'
+ '</a>'
+ '</div>'
+ '<div class="msg">{4}</div>'
+ '<div class="time">{5}</div>'
+ '</div>'
+ '</div>';
document.addEventListener("keydown", checkEnterKey);
tweet();
function tweet() {
var req = new XMLHttpRequest();
req.open("POST", "http://intra1.synap.co.kr/season2/tweet/index.ss", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onload = function () {
try {
var resJson = JSON.parse(req.responseText);
localStorage["userId"] = resJson.userId;
showTweets(resJson.msgList);
addDeleteButton();
updateMrtTs();
chrome.browserAction.setBadgeText({text:""});
chrome.browserAction.setIcon({path: "/images/icon_on.png"});
} catch (x) {
showLoginMsg();
}
};
var msg, ts;
try {
msg = document.getElementById("tweetMsg").value;
ts = document.getElementById("list").firstChild.id;
} catch (x) {
msg = "";
ts = "0";
}
var params = "blahblah="+encodeURIComponent(msg)+"&recentTimestamp="+ts;
setTimeout(function(){req.send(params);}, 0);
}
function showTweets(tweets) {
var tweetHtml = [];
for(var i=0; i<tweets.length; i++) {
tweetHtml.unshift(getTweetHtml(tweets[i]));
}
if (tweetHtml.length > 50) {
tweetHtml.splice(50);
}
document.getElementById("list").innerHTML = tweetHtml.join("");
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) { icons.item(0).onerror = defaultIcon(); }
document.getElementById("mainPopup").style.display = "block";
}
function updateMrtTs() {
var mrt = document.getElementById("list").firstChild; // most recent tweet
var ts = (mrt)?mrt.id:"0";
localStorage["mrtTs"] = ts;
}
function showLoginMsg() {
document.body.innerHTML
= '<div style="text-align:center;">'
+ 'Login required.'
+ 'Visit <b><a id="loginLink" href="http://intra1.synap.co.kr/season2/login.ss?cmd=loginForm">Synapsoft Intra1</a></b> and Login, first.'
+ '</div>';
document.getElementById("loginLink").onclick = function(e) {
chrome.tabs.create({url: e.srcElement.href});
};
}
function deleteTweet(id) {
if(!confirm("Are you sure you want to delete this tweet?"))
return;
var req = new XMLHttpRequest();
req.open("POST", "http://intra1.synap.co.kr/season2/tweet/index.ss", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onload = function() {
var tweet = document.getElementById(id);
tweet.parentNode.removeChild(tweet);
};
var params = "cmd=delete×tamp="+id;
req.send(params);
}
function addDeleteButton() {
var loginUserId = localStorage["userId"];
var deleteLinks = document.getElementsByClassName("deleteLink");
for (var i=0; i<deleteLinks.length; i++) {
var linkUserId = deleteLinks[i].getAttribute("userId");
if (linkUserId != loginUserId) {
deleteLinks[i].style.display = "none";
}
}
}
function defaultIcon() {
return "http://intra1.synap.co.kr/season2/images/no_avatar.png";
}
function getTweetHtml(tweet) {
return String.format(tweetFormatStr,
tweet.timestamp,
getPictureUrl(tweet.id),
tweet.id,
tweet.userName,
tweet.blahblah.replace(/(\r\n|\n)/g, "<br/>"),
getTsStr(tweet.date));
}
function getPictureUrl(id) {
return "http://intra1.synap.co.kr/season2/images/userphoto/" + id;
}
String.format = function(text) {
if ( arguments.length <= 1 ) {
return text;
}
var tokenCount = arguments.length - 2;
for( var token = 0; token <= tokenCount; token++ ) {
text = text.replace(new RegExp( "\\{" + token + "\\}", "gi" ),
arguments[ token + 1 ].replace("$", "$$$$") );
}
return text;
};
function getTsStr(dateStr) {
var date = new Date(dateStr);
var delta = (new Date() - date) / 1000; // in seconds
if (delta < (60*60)) { // less than 1 hour
var m = parseInt(delta / 60);
return m + " minute" + ((m<=1)?"":"s") + " ago";
} else if (delta < (24*60*60)) { // less than 24 hours
var h = parseInt(delta / 60 / 60);
return h +" hour" + ((h<=1)?"":"s") + " ago";
} else {
var m = date.getMonth()+1;
var d = date.getDate();
return (m<10?"0":"") + m + "/" + (d<10?"0":"") + d;
}
}
function checkEnterKey(e) {
if (e.srcElement.getAttribute("id") !== "tweetMsg") { // event src is not msg textarea
return;
}
if (e.keyCode !== 13 || !(e.shiftKey || e.ctrlKey)) { // not Ctrl+Enter or Shift+Enter
return;
}
tweet();
var t = document.getElementById("tweetMsg");
t.blur();
t.value = "";
}
})();
| JavaScript | 0 | @@ -381,35 +381,8 @@
=%22#%22
- onclick=%22deleteTweet(%7B0%7D)%22
%3E'%0A
@@ -659,16 +659,27 @@
div%3E';%0A%0A
+ tweet();%0A
docume
@@ -726,26 +726,16 @@
rKey);%0A
- tweet();%0A
%0A funct
@@ -2862,16 +2862,18 @@
weet?%22))
+ %7B
%0A r
@@ -2875,24 +2875,30 @@
return;%0A
+ %7D%0A
var req
@@ -3620,16 +3620,173 @@
%22none%22;%0A
+ %7D else %7B%0A deleteLinks%5Bi%5D.onclick = function(e) %7B%0A deleteTweet(e.srcElement.parentNode.parentNode.parentNode.parentNode.id);%0A %7D;%0A
%7D%0A
|
cfb03854bf3373109dacadff5044ac4498654756 | Change fields affected by expander, refs #9266 | js/qubit.js | js/qubit.js | var Qubit = Qubit || {};
// Usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function()
{
log.history = log.history || [];
log.history.push(arguments);
if (this.console)
{
console.log( Array.prototype.slice.call(arguments) );
}
};
// jQuery expander
Drupal.behaviors.expander = {
attach: function (context)
{
jQuery('div.field:not(:has(div.field)) > div:not(:has(ul, li))')
.expander({
slicePoint: 255,
expandText: '»',
expandPrefix: '... ',
userCollapseText: '«',
widow: 4,
expandEffect: 'show'
});
}
};
| JavaScript | 0 | @@ -476,37 +476,278 @@
div
-:not(:has(ul, li))')%0A
+').each(function (index, element) %7B%0A var $element = jQuery(element);%0A // Don't apply expander to fields with only one child, if that child is a list%0A if ($element.children().length !== 1 %7C%7C !$element.children().first().is('ul')) %7B%0A $element
.exp
@@ -754,16 +754,18 @@
ander(%7B%0A
+
@@ -783,16 +783,18 @@
t: 255,%0A
+
@@ -824,24 +824,26 @@
,%0A
+
expandPrefix
@@ -852,16 +852,18 @@
'... ',%0A
+
@@ -903,16 +903,18 @@
+
widow: 4
@@ -915,16 +915,18 @@
dow: 4,%0A
+
@@ -950,16 +950,38 @@
show'%0A
+ %7D);%0A %7D%0A
%7D)
|
995d7090a899506b9800c4549a02b413bebc3323 | Save As causes a navigate action, and updates the available history items. | js/store.js | js/store.js | "use strict";
/*global module, require*/
var _ = require("lodash"),
helpers = require("./helpers.js"),
isNum = helpers.isNum,
noop = helpers.noop,
callbacks = helpers.callbackHandler,
versionCacheFactory = require("./version-cache.js");
/*
Operates on a single collection. Keeps track of the open sharejs document for that collection.
*/
module.exports = function(maintainConnection, collection, backend, serialize, deserialize, getModel, setModelToObject, freshModel) {
var title = null,
version = null,
onNavigate = callbacks(),
navigate = function(newTitle, newVersion) {
if (title === newTitle && version === newVersion) {
return;
}
title = newTitle;
if (isNum(newVersion)) {
version = parseInt(newVersion);
} else {
version = newVersion;
}
onNavigate(title, version);
},
autosave = false,
onAutosaveChanged = callbacks(),
setAutosave = function(newAutoSave) {
autosave = newAutoSave;
onAutosaveChanged(newAutoSave);
},
doc,
context,
// Manual mechanism to track when we're making changes, so that we don't write out own events.
writing = false,
versionCache = versionCacheFactory(collection, backend.getVersionsList),
/*
A helpful wrapper to make sure that we poke the version when we change the model.
*/
setModel = function(obj, name, version, latestAvailableVersion) {
setModelToObject(obj);
navigate(name, version);
versionCache.updateVersions(name, latestAvailableVersion);
},
onOp = callbacks(),
setDoc = function(newDoc) {
if (doc === newDoc) {
return;
} else {
if (doc) {
doc.destroy();
context = null;
}
doc = newDoc;
setAutosave(false);
if (doc) {
doc.on("after op", function(ops, context) {
versionCache.updateVersions(title);
if (!writing && autosave) {
ops.forEach(function(op) {
onOp(op);
});
}
});
}
}
},
saveDoc = function(model) {
writing = true;
var snapshot = doc.getSnapshot(),
serialized = serialize(model);
if (!snapshot) {
doc.create("json0", serialized);
} else {
doc.submitOp(
[{
p: [],
oi: serialized
}],
function() {
versionCache.updateVersions(
title
);
}
);
}
context = doc.createContext();
writing = false;
},
loadFromCollection = function(name, f) {
backend.load(collection, name, f);
},
newDocument = function() {
setDoc(null);
setModel(freshModel());
};
return {
getTitle: function() {
return title;
},
getVersion: function() {
return version;
},
onNavigate: onNavigate.add,
getAutosave: function() {
return autosave;
},
onAutosaveChanged: onAutosaveChanged.add,
onVersionsListUpdated: versionCache.onVersionsUpdated,
newDocument: newDocument,
openDocument: function(name, version) {
if (isNum(version)) {
backend.loadVersion(
collection,
name,
version,
function(historical) {
setDoc(null);
setModel(
deserialize(historical.doc),
name,
version,
historical.latestV
);
},
function(error) {
throw error;
}
);
} else if (!maintainConnection) {
backend.loadSnapshot(
collection,
name,
function(snapshot) {
setDoc(null);
setModel(
deserialize(snapshot),
name,
null,
null
);
},
function(error) {
throw new Error(error);
}
);
} else {
loadFromCollection(
name,
function(loaded) {
setDoc(loaded);
var snapshot = doc.getSnapshot();
if (snapshot) {
setModel(
deserialize(snapshot),
name,
null,
doc.version
);
context = doc.createContext();
} else {
var model = freshModel();
setModel(
model,
name,
null,
doc.version
);
}
}
);
}
},
saveDocument: function(name) {
if (doc && doc.name === name) {
saveDoc(getModel());
} else {
loadFromCollection(
name,
function(loaded) {
setDoc(loaded);
saveDoc(getModel());
});
}
},
deleteDocument: function(name) {
backend.deleteDoc(collection, name);
if (name === title) {
newDocument();
}
},
writeOp: function(op) {
if (autosave) {
writing = true;
try {
// If we don't have a document context yet, there's no point trying to send operations to it.
if (context) {
context.submitOp(
op instanceof Array ? op : [op],
function() {
versionCache.updateVersions(
title
);
}
);
}
} finally {
writing = false;
}
}
},
onOp: onOp.add,
loadSnapshot: function(name, callback, errback) {
loadFromCollection(
name,
function(loaded) {
try {
var snapshot = loaded.getSnapshot();
if (snapshot) {
callback(
deserialize(snapshot));
} else {
errback();
}
} finally {
loaded.destroy();
}
}
);
}
};
};
| JavaScript | 0 | @@ -2138,18 +2138,90 @@
rialized
-);
+, function() %7B%0A%09%09 versionCache.updateVersions(%0A%09%09%09title%0A%09%09 );%0A%09%09%7D);%0A
%0A%09 %7D
@@ -4227,16 +4227,41 @@
oaded);%0A
+%09%09%09navigate(name, null);%0A
%09%09%09saveD
|
4c77e1046933e15f0d9e5a17856ab7cd470dc0f7 | Update theme.js | js/theme.js | js/theme.js | $( document ).ready(function() {
// Shift nav in mobile when clicking the menu.
$(document).on('click', "[data-toggle='wy-nav-top']", function() {
$("[data-toggle='wy-nav-shift']").toggleClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
});
// Close menu when you click a link.
$(document).on('click', ".wy-menu-vertical .current ul li a", function() {
$("[data-toggle='wy-nav-shift']").removeClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
});
$(document).on('click', "[data-toggle='rst-current-version']", function() {
$("[data-toggle='rst-versions']").toggleClass("shift-up");
});
// Make tables responsive
$("table.docutils:not(.field-list)").wrap("<div class='wy-table-responsive'></div>");
});
window.SphinxRtdTheme = (function (jquery) {
var stickyNav = (function () {
var navBar,
win,
stickyNavCssClass = 'stickynav',
applyStickNav = function () {
if (navBar.height() <= win.height()) {
navBar.addClass(stickyNavCssClass);
} else {
navBar.removeClass(stickyNavCssClass);
}
},
enable = function () {
applyStickNav();
win.on('resize', applyStickNav);
},
init = function () {
navBar = jquery('nav.wy-nav-side:first');
win = jquery(window);
};
jquery(init);
return {
enable : enable
};
}());
return {
StickyNav : stickyNav
};
}($));
| JavaScript | 0.000001 | @@ -528,24 +528,224 @@
%22);%0A %7D);%0A
+ // color background of current menu items%0A $(document).on('click', %22.wy-nav-shift a%22, function() %7B%0A $(%22.wy-nav-shift a%22).removeClass(%22current%22);%0A $(this).addClass(%22current%22);%0A %7D);%0A
$(docume
|
1318a9975573ddf9c7d1ae61af3ca0c50dc165e6 | remove unused functions | js/utils.js | js/utils.js |
import { api as router } from 'abyssa'
export const requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame
export const pxToRem = (val) => {
const toInt = parseInt(val, 10)
const toRem = toInt / 16
return `${toRem}rem`
}
export const pxToRemDims = (val) => {
return {
width: pxToRem(val),
height: pxToRem(val)
}
}
export const addTabIndex = item => item.tabIndex = 0
export const removeTabIndex = item => item.tabIndex = -1
export const handleLink = (e, dest) => {
// ideally, this function would not be needed...except we live in a IE11 world
e.preventDefault()
router.transitionTo(dest)
} | JavaScript | 0.000009 | @@ -557,119 +557,8 @@
%0A%7D%0A%0A
-export const addTabIndex = item =%3E item.tabIndex = 0%0A%0Aexport const removeTabIndex = item =%3E item.tabIndex = -1%0A
%0Aexp
|
cf081feb8420e96589caad88eb4a297b09a7667d | remove unused dep | actStub.js | actStub.js | 'use strict'
const Sinon = require('sinon')
const strictEquals = require('assert').deepStrictEqual
/**
*
*
* @class ActStub
*/
class ActStub {
/**
* Creates an instance of ActStub.
*
* @memberOf ActStub
*/
constructor (hemera) {
this.s = null
this.hemera = hemera
}
/**
*
*
* @param {any} pattern
* @param {any} error
* @param {any} args
* @returns
*
* @memberOf ActStub
*/
stub (pattern, error, args) {
if (!this.s) {
this.s = Sinon.stub(this.hemera, 'act')
}
this.s.withArgs(pattern).callsFake((pattern, cb) => {
if (cb) {
return cb.call(this.hemera, error, args)
}
})
this.s.callThrough()
return this.s
}
/**
*
*
* @param {any} pattern
* @param {any} error
* @param {any} args
* @returns
* @memberof ActStub
*/
stubPartial (pattern, error, args) {
if (!this.s) {
this.s = Sinon.stub(this.hemera, 'act')
}
this.s.withArgs(Sinon.match(pattern)).callsFake((pattern, cb) => {
if (cb) {
return cb.call(this.hemera, error, args)
}
})
this.s.callThrough()
return this.s
}
/**
*
*
*
* @memberOf ActStub
*/
restore () {
if (this.s) {
this.s.restore()
}
}
}
module.exports = ActStub
| JavaScript | 0.000002 | @@ -41,63 +41,8 @@
on')
-%0Aconst strictEquals = require('assert').deepStrictEqual
%0A%0A/*
|
0395747912e44b24cd38a5fc4b87a192c2f321e3 | update i18n logic | javascript/dojo-1.1.1-lib/trunk/src/main/webapp/js/org/ppwcode/dojo/dijit/i18n/LocalizedField.js | javascript/dojo-1.1.1-lib/trunk/src/main/webapp/js/org/ppwcode/dojo/dijit/i18n/LocalizedField.js | dojo.provide("org.ppwcode.dojo.dijit.i18n.LocalizedField");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.i18n");
dojo.declare(
"org.ppwcode.dojo.dijit.i18n.LocalizedField",
[dijit._Widget, dijit._Templated],
{
//summary:
// todo
//description:
// PeriodForm is a dijit
//
templateString: '<label>${value}</label>',
property: 'none',
bundle: null,
value: '',
constructor: function(arguments) {
this.bundle = arguments.bundle;
this.property = arguments.property;
eval('this.value = this.bundle.' + this.property);
}
}
);
| JavaScript | 0 | @@ -380,16 +380,33 @@
'%3Clabel
+ for=%22$%7Bfieldid%7D%22
%3E$%7Bvalue
@@ -413,17 +413,16 @@
%7D%3C/label
-%3E
',%0D%0A
@@ -427,24 +427,23 @@
%0D%0A
-property
+fieldid
: 'none'
@@ -568,24 +568,23 @@
%09 this.
-property
+fieldid
= argum
@@ -588,24 +588,23 @@
guments.
-property
+fieldid
;%0D%0A%09 ev
@@ -645,16 +645,15 @@
his.
-property
+fieldid
);%0D%0A
@@ -666,10 +666,8 @@
%0A %7D%0D%0A);
-%0D%0A
|
9772a3539bb2dc9a3af1d2ec5d022dee2cc24595 | Remove debug statement | website/src/app/project/experiments/experiment/components/notes/mc-experiment-notes.component.js | website/src/app/project/experiments/experiment/components/notes/mc-experiment-notes.component.js | class MCExperimentNotesComponentController {
/*@ngInject*/
constructor($scope, $mdDialog, notesService, $stateParams, toast, editorOpts) {
$scope.editorOptions = editorOpts({height: 67, width: 59});
this.notesService = notesService;
this.$mdDialog = $mdDialog;
this.toast = toast;
this.projectID = $stateParams.project_id;
this.experimentID = $stateParams.experiment_id;
if (this.experiment.notes.length) {
this.experiment.notes.forEach((n) => n.selectedClass = '');
this.currentNote = this.experiment.notes[0];
this.currentNote.selectedClass = 'task-selected';
} else {
this.currentNote = null;
}
}
addNote() {
console.log('addNote');
this.$mdDialog.show({
templateUrl: 'app/project/experiments/experiment/components/notes/new-note-dialog.html',
controller: NewExperimentNoteDialogController,
controllerAs: 'ctrl',
bindToController: true
}).then(
(note) => {
this.setCurrent(note);
this.experiment.notes.push(note);
this.currentNote = note;
}
);
}
updateNote() {
if (!this.projectID || !this.currentNote.id) {
return;
}
if (!this.currentNote.note) {
this.currentNote.note = '';
}
let note = this.currentNote;
this.notesService.updateNote(this.projectID, this.experimentID, note.id, {note: note.note})
.then(
() => null,
() => this.toast.error('Unable to update note')
);
}
setCurrent(note) {
$('.mc-experiment-outline-task').removeClass('task-selected');
this.experiment.notes.forEach((n) => n.selectedClass = '');
note.selectedClass = 'task-selected';
}
}
class NewExperimentNoteDialogController {
/*@ngInject*/
constructor($mdDialog, notesService, $stateParams, toast) {
this.$mdDialog = $mdDialog;
this.notesService = notesService;
this.toast = toast;
this.projectID = $stateParams.project_id;
this.experimentID = $stateParams.experiment_id;
this.name = '';
}
submit() {
if (this.name !== '') {
let note = {
name: this.name,
note: `<h2>${this.name}</h2>`
};
this.notesService.createNote(this.projectID, this.experimentID, note)
.then(
(n) => this.$mdDialog.hide(n),
() => this.toast.error('Failed to create note')
);
}
}
cancel() {
this.$mdDialog.cancel();
}
}
angular.module('materialscommons').component('mcExperimentNotes', {
templateUrl: 'app/project/experiments/experiment/components/notes/mc-experiment-notes.html',
controller: MCExperimentNotesComponentController,
bindings: {
experiment: '='
}
});
| JavaScript | 0.000021 | @@ -747,40 +747,8 @@
) %7B%0A
- console.log('addNote');%0A
|
da781a93b615b32b6edfe45a0c90383f7cf51cda | Add note about handling over int'l date line | local_modules/gridfilter/MarkerGrid.js | local_modules/gridfilter/MarkerGrid.js | const Mapper = require('./Mapper')
const circle = require('./circle')
// Build key strings for cells to help putting them into dictionary.
// Define the structure of the key here.
const stringify = (x, y) => x + ';' + y
const MarkerGrid = function (latLngBounds, gridSize) {
// Parameters:
// latLngBounds is a google.maps.LatLngBoundsLiteral
// Is the grid area in geographical coordinates.
// Has structure { east, north, south, west }
// gridSize is { width, height } in integers.
// Store size
this.width = gridSize.width
this.height = gridSize.height
// Maps from geo coords to grid coords
this.lngToWidth = new Mapper(
latLngBounds.west,
latLngBounds.east,
0,
gridSize.width
)
this.latToHeight = new Mapper(
latLngBounds.north,
latLngBounds.south,
0,
gridSize.height
)
// Maintain an index of filled cells. A map from Key to Marker
this.cells = {}
// Maintain a list of added markers.
// It would be a pain to extract the list from cells object.
this.addedMarkers = []
}
const proto = MarkerGrid.prototype
module.exports = MarkerGrid
proto.add = function (marker) {
const self = this
const lnglat = marker.geom.coordinates // array [lng, lat]
// Map to grid coords. Floating point.
const x = this.lngToWidth.map(lnglat[0])
const y = this.latToHeight.map(lnglat[1])
// Marker radius, the area the marker reserves.
const r = 1
// Find grid index. Use it to test if the grid cell is taken.
const i = Math.floor(x)
const j = Math.floor(y)
// Skip markers outside the boundary.
// TODO: leave some margin to prevent hysteria in child count
if (i < 0 || i >= this.width || j < 0 || j >= this.height) {
return
}
// Find cell by key
const key = stringify(i, j)
if (this.cells[key]) {
// The cell is already taken. Marker is not added.
// Mark that the occupying marker has a child.
this.cells[key].childrenCount += 1
} else {
// Add the marker.
this.addedMarkers.push(marker)
// Init children counting.
marker.childrenCount = 0
// The marker reserves a circular area.
// Determine circle indices. Attach marker to each index.
const circleIndices = circle.getIndices(x, y, r)
circleIndices.forEach(index => {
const ci = index[0]
const cj = index[1]
if (ci >= 0 && ci < self.width && cj >= 0 && cj < self.height) {
const k = stringify(index[0], index[1])
self.cells[k] = marker
}
})
}
}
proto.getMarkers = function () {
// List of filtered markers
return this.addedMarkers
}
proto.toString = function () {
let str = ''
for (let j = 0; j < this.height; j += 1) {
for (let i = 0; i < this.width; i += 1) {
const m = this.cells[stringify(i, j)]
// Output number of stacked markers.
if (m) {
// a marker
str += '' + (m.childrenCount + 1)
} else {
// no marker in this cell
str += '0'
}
// If last in row
if (i === this.width - 1) {
str += '\n'
} else {
str += ', '
}
}
}
return str
}
| JavaScript | 0 | @@ -581,16 +581,172 @@
height%0A%0A
+ // Ensure correct handling over map edges.%0A // For example, usually west %3C east, except when east goes over%0A // the international date line.%0A // TODO%0A%0A
// Map
|
21baa1d9add34cb832ca94974cd73b9cfb2f26a5 | add redirect to simple example | examples/index.js | examples/index.js | import React from "react";
import ReactDOM from "react-dom";
import { HashRouter as Router, Route, Link, Switch } from "react-router-dom";
import App from "./containers/App";
import Simple from "./examples/simple";
import Standard from "./examples/standard";
const examples = [
{
to: "/simple",
label: "Simple",
component: Simple
},
{
to: "/standard",
label: "Standard",
component: Standard
}
];
ReactDOM.render(
<Router>
<App examples={examples} />
</Router>,
document.getElementById("root")
);
| JavaScript | 0.000001 | @@ -5,16 +5,30 @@
rt React
+, %7B Fragment %7D
from %22r
@@ -110,20 +110,16 @@
te,
-Link, Switch
+Redirect
%7D f
@@ -462,16 +462,105 @@
Router%3E%0A
+ %3CFragment%3E%0A %3CRoute exact path=%22/%22 render=%7B() =%3E %3CRedirect to=%22/simple%22 /%3E%7D /%3E%0A
%3CApp
@@ -583,16 +583,32 @@
les%7D /%3E%0A
+ %3C/Fragment%3E%0A
%3C/Rout
|
06291110313fdba2556a971305066274c936d335 | Resolve image icon path relative to module | examples/swing.js | examples/swing.js | var {JFrame, JButton, ImageIcon, JLabel} = javax.swing;
var {setInterval} = require('ringo/scheduler');
var n = 0;
function main() {
var frame = new JFrame("Swing Demo");
var button = new JButton(new ImageIcon("img/ringo-drums.png"));
button.addActionListener(function(e) {
setInterval(function() {
if (n++ > 200) system.exit();
frame.setLocation(200 + random(), 200 + random());
}, 5);
});
frame.add("Center", button);
frame.add("South", new JLabel("Click Button for Visual Drumroll!"));
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
function random() (Math.random() - 0.5) * 50;
if (require.main == module) {
main();
}
| JavaScript | 0 | @@ -212,16 +212,31 @@
ageIcon(
+module.resolve(
%22img/rin
@@ -250,16 +250,17 @@
s.png%22))
+)
;%0A bu
|
ba8dffbe83e78910242c0723feb0746519014780 | Update comparison.js | routes/comparison.js | routes/comparison.js | const express = require('express')
const router = express.Router()
const wrap = fn => (...args) => fn(...args).catch(args[2])
router.get('/:items', wrap(async (req, res) => {
const items = req.params.items.split('--').map(e => parseInt(e, 10))
const db = req.app.locals.db
const goods = db.collection('offers')
res.json({
status: true,
data: await goods.find({ id: { $in: items } }).toArray(),
params: await goods.distinct('param.name', { id: { $in: items } }),
})
}))
module.exports = router
| JavaScript | 0.000001 | @@ -250,18 +250,22 @@
const
-db
+%7B db %7D
= req.a
@@ -277,11 +277,8 @@
cals
-.db
%0A c
|
b76055bb539b5e8a6ca1a0e35001ef1264efe030 | fix error handling in github raw file request | routes/github-api.js | routes/github-api.js | var Github = require("github-api");
var request = require('request');
var User = require('../models/users.js');
var File = require('../models/composeFiles.js');
//Wrapper to get the list of repositories of the user
function listUserRepos(accessToken, username, callback){
var github = new Github({
token: accessToken
});
var userGH = github.getUser();
userGH.userRepos(username, function(err, repos) {
if(err){
callback(err, null);
} else {
callback(null, repos);
}
});
}
function listBranches(accessToken, username, reponame, callback){
var github = new Github({
token: accessToken
});
var repo = github.getRepo(username, reponame);
repo.listBranches(function(err, branches) {
if(err){
callback(err, null);
} else {
callback(null, branches);
}
});
}
function listOrgs(accessToken, callback){
var github = new Github({
token: accessToken
});
var userGH = github.getUser();
userGH.orgs(function(err, orgs){
if(err){
callback(err, null);
} else {
callback(null, orgs);
}
});
}
function listOrgRepos(accessToken, name, callback){
var github = new Github({
token: accessToken
});
var userGH = github.getUser();
userGH.orgRepos(name, function(err, repos) {
if(err){
callback(err, null);
} else {
callback(null, repos);
}
});
}
//Wrapper to get tutum.yml from repository
function getYAML(username, repositoryName, branch, path, callback){
var github = new Github({});
path = path.substr(1);
var headers = {
'Content-Type': 'text/x-yaml; charset=utf-8'
};
var options = {
url: "https://github.com/" + username + "/" + repositoryName + "/raw/" + branch + "/" + path + "/tutum.yml",
method: 'GET',
headers: headers
};
request.get(options, function(err, data){
if(data.statusCode == 404){
request.get("https://github.com/" + username + "/" + repositoryName + "/raw/" + branch + "/" + path + "/docker-compose.yml", function(err, data){
if(data.statusCode == 404){
callback("File not found", null);
} else {
callback(null, data.body);
}
});
} else {
callback(null, data.body);
}
});
}
//Wrapper to get README.md from repository
function getREADME(username, repositoryName, callback){
var github = new Github({});
var repo = github.getRepo(username, repositoryName);
repo.read('master', 'README.md', function(err, data) {
callback(null, data);
});
}
module.exports = function(app) {
app.get('/api/v1/user', function(req, res){
if(req.user !== undefined){
res.json(req.user);
} else {
res.statusCode = 400;
}
});
//GET ORGS LIST AT CREATION
app.get('/api/v1/user/orgs', function(req, res){
User.findOne({username: req.user.username}, function(err, user){
if(err){
return next(new Error(err));
}
listOrgs(user.accessToken, function(err, orgs){
if(err){
res.json(err);
} else {
res.json(orgs);
}
});
});
});
//GET REPOS LIST AT CREATION
app.get('/api/v1/user/repos', function(req, res){
User.findOne({username: req.user.username}, function(err, user){
if(err){
return next(new Error(err));
}
if(req.query.name == req.user.username){
listUserRepos(user.accessToken, user.username, function(err, repos){
if(err){
res.json(err);
} else {
res.json(repos);
}
});
} else {
listOrgRepos(user.accessToken, req.query.name, function(err, repos){
if(err){
res.json(err);
} else {
res.json(repos);
}
});
}
});
});
//GET BRANCHES LIST AT CREATION
app.get('/api/v1/user/repos/branches', function(req, res){
var repositoryName = req.query.repo;
var organization = req.query.orgname;
User.findOne({username: req.user.username}, function(err, user){
if(err){
return next(new Error(err));
}
listBranches(user.accessToken, organization, repositoryName, function(err, branches){
if(err){
res.json(err);
} else {
res.json(branches);
}
});
});
});
//GET YAML FOR PREVIEW AT CREATION
app.post('/api/v1/user/repos/new', function(req, res){
var organization = req.body.params.orgname;
var repositoryName = req.body.params.repo;
var repositoryPath = req.body.params.path;
var branch = req.body.params.branch;
getYAML(organization, repositoryName, branch, repositoryPath, function(err, yaml){
if(err){
res.send(err);
} else {
res.writeHead(200, {'Content-Type': 'text/x-yaml; charset=utf-8'});
res.end(yaml);
}
});
});
//GET YAML FROM REGISTRY
app.post('/api/v1/user/repos/file', function(req, res){
var repositoryName = req.body.params.repo;
var repositoryPath = req.body.params.path;
File.findOne({_id: req.body.params.id}, function(err, file){
if(err){
res.json(new Error(err));
res.redirect('/404');
} else {
getYAML(file.user, repositoryName, file.branch, repositoryPath, function(err, yaml){
if(err){
res.send('"Unable to fetch stackfile from Github. The file might have been moved or the repository deleted by its owner."');
} else {
res.writeHead(200, {'Content-Type': 'text/x-yaml; charset=utf-8'});
res.end(yaml);
}
});
}
});
});
app.get('/api/v1/user/repos/embed', function(req, res){
var user = req.query.user;
var repoName = req.query.repository;
var branch = req.query.branch;
var path = req.query.path;
getYAML(user, repoName, branch, path, function(err, file){
if(err){
res.end('Unable to fetch stackfile');
} else {
res.writeHead(200, {'Content-Type': 'text/x-yaml; charset=utf-8'});
res.end(file);
}
});
});
};
| JavaScript | 0 | @@ -2005,32 +2005,100 @@
ion(err, data)%7B%0A
+ if(err)%7B%0A callback(err, null);%0A %7D%0A if(data)%7B%0A
if(data.
@@ -2537,32 +2537,39 @@
ody);%0A %7D%0A
+ %7D
%0A %7D);%0A%7D%0A%0A%0A//W
|
aaf54df6917f1e0e358b6d07879110bcade318b8 | Fix me Music Object | app/objects/Music.js | app/objects/Music.js | const fs = require('fs');
const mm = require('musicmetadata');
// var iconv = require('iconv-lite');
class Music {
constructor(path = '', coverPath = '', cb = ()=>{}){
let me = this;
let read_stream = fs.createReadStream(path);
let parser = mm(read_stream,{duration : true}, (err, data) => {
if(err){
me.valid = false;
throw err;
}
me.path = path;
me.valid = true;
me.title = data.title;
me.artist = data.artist;//array
me.album = data.album;
me.album_artist = data.albumartist;//array
me.year = data.year;
me.track_num = data.track.no;
me.disk_num = data.disk.no;
me.gerne = data.gerne;//array
me.art_format = data.picture[0].format;//picture is an array
me.duration = data.duration;
me.coverPath = coverPath+me.title +'.'+ me.art_format;
me.cover = me.title +'.'+ me.art_format;
fs.writeFileSync( me.coverPath, data.picture[0].data);
read_stream.close();
cb(me);
});
}
}
module.exports = Music;
| JavaScript | 0.000025 | @@ -168,25 +168,8 @@
%7D)%7B%0A
-%09%09let me = this;%0A
%09%09le
@@ -293,18 +293,20 @@
r)%7B%0A%09%09%09%09
-me
+this
.valid =
@@ -336,18 +336,20 @@
%09%09%09%7D%0A%09%09%09
-me
+this
.path =
@@ -357,18 +357,20 @@
ath;%0A%09%09%09
-me
+this
.valid =
@@ -379,18 +379,20 @@
rue;%0A%09%09%09
-me
+this
.title =
@@ -403,26 +403,28 @@
a.title;%0A%09%09%09
-me
+this
.artist = da
@@ -440,26 +440,28 @@
;//array%0A%09%09%09
-me
+this
.album = dat
@@ -472,18 +472,20 @@
bum;%0A%09%09%09
-me
+this
.album_a
@@ -520,18 +520,20 @@
rray%0A%09%09%09
-me
+this
.year =
@@ -546,18 +546,20 @@
ear;%0A%09%09%09
-me
+this
.track_n
@@ -581,18 +581,20 @@
.no;%0A%09%09%09
-me
+this
.disk_nu
@@ -614,18 +614,20 @@
.no;%0A%09%09%09
-me
+this
.gerne =
@@ -649,18 +649,20 @@
rray%0A%09%09%09
-me
+this
.art_for
@@ -715,18 +715,20 @@
rray%0A%09%09%09
-me
+this
.duratio
@@ -745,26 +745,28 @@
uration;%0A%09%09%09
-me
+this
.coverPath =
@@ -776,18 +776,20 @@
verPath+
-me
+this
.title +
@@ -785,34 +785,36 @@
his.title +'.'+
-me
+this
.art_format;%0A%09%09%09
@@ -813,18 +813,20 @@
mat;%0A%09%09%09
-me
+this
.cover =
@@ -826,18 +826,20 @@
cover =
-me
+this
.title +
@@ -843,18 +843,20 @@
e +'.'+
-me
+this
.art_for
@@ -881,18 +881,20 @@
leSync(
-me
+this
.coverPa
@@ -950,18 +950,20 @@
;%0A%09%09%09cb(
-me
+this
);%0A%09%09%7D);
|
2e0cf03be836f03a8c0b475b5f5d0ca35adb0332 | Add doc link | pr/gp2/pr.js | pr/gp2/pr.js | /* exported onBuyClicked */
/**
* Initializes the payment request object.
* @return {PaymentRequest} The payment request object.
*/
function buildPaymentRequest() {
if (!window.PaymentRequest) {
return null;
}
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0,
};
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'stripe',
'stripe:publishableKey': 'pk_live_lNk21zqKM2BENZENh3rzCUgo',
'stripe:version': '2016-07-06',
},
};
const allowedCardNetworks = ['AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'VISA',
'MASTERCARD'];
const allowedCardAuthMethods = ['PAN_ONLY', 'CRYPTOGRAM_3DS'];
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks,
},
};
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification,
},
);
const googleIsReadyToPayRequest = Object.assign(
{},
baseRequest,
{
allowedPaymentMethods: [baseCardPaymentMethod],
},
);
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = {
countryCode: 'US',
currencyCode: 'USD',
totalPriceStatus: 'FINAL',
totalPrice: '1.00',
};
paymentDataRequest.merchantInfo = {
merchantName: 'Rouslan Solomakhin',
merchantId: '00184145120947117657',
};
const supportedInstruments = [{
supportedMethods: 'https://google.com/pay',
data: paymentDataRequest,
}];
const details = {
total: {
label: 'Tots',
amount: {
currency: 'USD',
value: '1.00',
},
},
};
let request = null;
try {
request = new PaymentRequest(supportedInstruments, details);
if (request.canMakePayment) {
request.canMakePayment().then(function(result) {
info(result ? "Can make payment" : "Cannot make payment");
}).catch(function(err) {
error(err);
});
}
if (request.hasEnrolledInstrument) {
request.hasEnrolledInstrument().then(function(result) {
info(result ? "Has enrolled instrument" : "No enrolled instrument");
}).catch(function(err) {
error(err);
});
}
} catch (e) {
error('Developer mistake: \'' + e + '\'');
}
return request;
}
let request = buildPaymentRequest();
/**
* Launches payment request for Android Pay.
*/
function onBuyClicked() {
if (!window.PaymentRequest || !request) {
error('PaymentRequest API is not supported.');
return;
}
try {
request.show()
.then(function(instrumentResponse) {
instrumentResponse.complete('success')
.then(function() {
done('This is a demo website. No payment will be processed.',
instrumentResponse);
})
.catch(function(err) {
error(err);
request = buildPaymentRequest();
});
})
.catch(function(err) {
error(err);
request = buildPaymentRequest();
});
} catch (e) {
error('Developer mistake: \'' + e + '\'');
request = buildPaymentRequest();
}
}
| JavaScript | 0 | @@ -216,16 +216,99 @@
l;%0A %7D%0A%0A
+ // Documentation:%0A // https://developers.google.com/pay/api/web/guides/tutorial%0A
const
|
1fa2657138fca62291238ed82202554d180dd8a3 | fix bugs | resources/assets/js/app.js | resources/assets/js/app.js |
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
import Vue from 'vue';
import _ from 'lodash';
import Buefy from 'buefy';
import AsyncComputed from 'vue-async-computed'
import Spinner from 'vue-loading-spinner/src/components/RotateSquare2';
import 'buefy/lib/buefy.css';
Vue.use(Buefy);
Vue.use(AsyncComputed);
window.Vue = Vue;
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
import Column from '../../components/column';
import List from '../../components/list';
const app = new Vue({
el: '#app',
data: {
table: [],
loading: true,
ajaxLoading: false,
routePrefix: 'stage-setup',
activeTab: 0,
list: {},
columns: {}
},
methods: {
startAjaxLoading() {
this.ajaxLoading = true;
},
finishAjaxLoading() {
this.ajaxLoading = false;
},
url(uri) {
return '/' + this.routePrefix + '/' + _.trim(uri, '/');
},
selectTable() {
this.loading = true;
axios.get(this.url('/column/' + this.table))
.then( (response) => {
history.pushState({}, null, this.url('?table=' + this.table));
if (response.data.list) {
this.list = response.data.list;
}
if (response.data.columns) {
this.columns = response.data.columns;
}
this.loading = false;
});
},
empty(obj) {
return Object.keys(obj).length === 0;
}
},
mounted() {
this.loading = false;
},
components: {Column, List, Spinner},
});
window.app = app; | JavaScript | 0.000001 | @@ -1595,36 +1595,16 @@
able));%0A
-
%0A
@@ -1608,36 +1608,44 @@
-if (
+this.list =
response.data.li
@@ -1650,407 +1650,204 @@
list
-) %7B%0A this.list = response.data.list;%0A %7D%0A %0A if (response.data.columns) %7B%0A this.columns = response.data.columns;%0A %7D%0A %0A this.loading = false;%0A %7D);%0A %7D,%0A empty(obj) %7B%0A return Object.keys(obj).length === 0
+ ? response.data.list : %7B%7D;%0A this.columns = response.data.columns ? response.data.columns : %7B%7D;%0A %0A this.loading = false;%0A %7D)
;%0A
|
df3c76fa72c79dc0f84c41548d1782deb382f822 | Remove useless statement. | packages/xen-api/src/cli.js | packages/xen-api/src/cli.js | #!/usr/bin/env node
import blocked from 'blocked'
import Bluebird, {coroutine} from 'bluebird'
import eventToPromise from 'event-to-promise'
import execPromise from 'exec-promise'
import minimist from 'minimist'
import pw from 'pw'
import {start as createRepl} from 'repl'
import {createClient} from './'
// ===================================================================
Bluebird.longStackTraces()
import createDebug from 'debug'
const debug = createDebug('xen-api:cli')
import sourceMapSupport from 'source-map-support'
sourceMapSupport.install()
// ===================================================================
const usage = `Usage: xen-api <url> <user>`
const main = coroutine(function * (args) {
const opts = minimist(args, {
boolean: ['help', 'verbose'],
alias: {
help: 'h',
verbose: 'v'
}
})
if (opts.help) {
return usage
}
if (opts.verbose) {
// Does not work perfectly.
//
// https://github.com/visionmedia/debug/pull/156
createDebug.enable('xen-api,xen-api:*')
}
const [url, user] = opts._
if (!url || !user) {
throw new Error('missing arguments')
}
process.stdout.write('Password: ')
const password = yield new Bluebird(resolve => {
pw(resolve)
})
{
const debug = createDebug('xen-api:perf')
blocked(ms => {
debug('blocked for %sms', ms | 0)
})
}
const xapi = createClient({url, auth: {user, password}})
yield xapi.connect()
const repl = createRepl({
prompt: `${xapi._humanId}> `
})
repl.context.xapi = xapi
// Make the REPL waits for promise completion.
{
const evaluate = Bluebird.promisify(repl.eval)
repl.eval = (cmd, context, filename, cb) => {
evaluate(cmd, context, filename)
// See https://github.com/petkaantonov/bluebird/issues/594
.then(result => result)
.nodeify(cb)
}
}
yield eventToPromise(repl, 'exit')
try {
yield xapi.disconnect()
} catch (error) {}
})
export default main
if (!module.parent) {
execPromise(main)
}
| JavaScript | 0.000028 | @@ -436,49 +436,8 @@
bug'
-%0Aconst debug = createDebug('xen-api:cli')
%0A%0Aim
|
77ea0fb8257b7e193964919d5b2cc9d7690e6c43 | Fix KeystoneJS routes to enable pretty URLs. | www/routes/index.js | www/routes/index.js | var babelify = require('babelify');
var browserify = require('browserify-middleware');
var keystone = require('keystone');
var passport = require('passport');
var importRoutes = keystone.importer(__dirname);
var routes = {
views: importRoutes('./views'),
api: importRoutes('./api'),
auth: importRoutes('./auth')
};
function isAuthenticated(req, res, next)
{
// FIXME: users should be able to login without FranceConnect for offline dev
if (!req.isAuthenticated() || !req.user.sub)
return res.status(401).apiResponse({ 'error': 'not logged in' });
next();
}
function checkCSRFToken(req, res, next)
{
if (!keystone.security.csrf.validate(req))
return res.status(400).apiResponse({ 'error': 'invalid CSRF token' });
next();
}
// Setup Route Bindings
exports = module.exports = function(app) {
app.use(passport.initialize());
app.use(passport.session());
app.get('/', routes.views.index);
app.get('/auth/login', keystone.middleware.api, routes.auth.index.login);
app.get('/auth/logout', keystone.middleware.api, routes.auth.index.logout);
app.get('/auth/connectCallback', keystone.middleware.api, routes.auth.index.connectCallback);
// FIXME: only in dev environment
app.get('/auth/fakeLogin', keystone.middleware.api, routes.auth.index.fakeLogin);
app.get('/api/text/list', keystone.middleware.api, routes.api.text.list);
app.get('/api/text/latest', keystone.middleware.api, routes.api.text.latest);
app.get('/api/text/:id', keystone.middleware.api, routes.api.text.get);
app.get('/api/text/getBySlug/:slug', keystone.middleware.api, routes.api.text.getBySlug);
app.get('/api/text/ballot/:id', keystone.middleware.api, isAuthenticated, routes.api.text.getBallot);
app.get('/api/text/vote/yes/:id', keystone.middleware.api, isAuthenticated, routes.api.text.voteYes);
app.get('/api/text/vote/blank/:id', keystone.middleware.api, isAuthenticated, routes.api.text.voteBlank);
app.get('/api/text/vote/no/:id', keystone.middleware.api, isAuthenticated, routes.api.text.voteNo);
app.get('/api/text/unvote/:id', keystone.middleware.api, isAuthenticated, routes.api.text.unvote);
app.post('/api/text/save', keystone.middleware.api, isAuthenticated, routes.api.text.save);
// app.get('/api/text/delete/:id', keystone.middleware.api, isAuthenticated, routes.api.text.delete);
app.get('/api/text/status/:id/:status', keystone.middleware.api, isAuthenticated, routes.api.text.status);
app.get('/api/text/like/add/:id/:value', keystone.middleware.api, isAuthenticated, routes.api.text.addLike);
app.get('/api/text/like/remove/:id', keystone.middleware.api, isAuthenticated, routes.api.text.removeLike);
app.get('/api/vote/result/:textId', keystone.middleware.api, routes.api.vote.result);
app.get('/api/source/list/:textId', keystone.middleware.api, routes.api.source.list);
app.post('/api/source/add', keystone.middleware.api, isAuthenticated, routes.api.source.add);
app.get('/api/source/like/add/:id/:value', keystone.middleware.api, isAuthenticated, routes.api.source.addLike);
app.get('/api/source/like/remove/:id', keystone.middleware.api, isAuthenticated, routes.api.source.removeLike);
app.get('/api/page/list', keystone.middleware.api, routes.api.page.list);
app.get('/api/page/navbar', keystone.middleware.api, routes.api.page.navbar);
app.get('/api/page/:id', keystone.middleware.api, routes.api.page.get);
app.get('/api/page/getBySlug/:slug', keystone.middleware.api, routes.api.page.getBySlug);
app.get('/api/user/me', keystone.middleware.api, isAuthenticated, routes.api.user.me);
app.get('/api/user/texts', keystone.middleware.api, isAuthenticated, routes.api.user.texts);
};
| JavaScript | 0 | @@ -871,43 +871,8 @@
);%0A%0A
-%09app.get('/', routes.views.index);%0A
%0A%09ap
@@ -3588,12 +3588,48 @@
.texts);
+%0A%0A%09app.get('*', routes.views.index);
%0A%7D;%0A
|
f7aa3b39ff1b72066dc502d78a97e3366f507e3f | Remove the unnecessary comment about private socket variable | public/javascript/pump/socket.js | public/javascript/pump/socket.js | // pump/socket.js
//
// Socket module for the pump.io client UI
//
// @licstart The following is the entire license notice for the
// JavaScript code in this page.
//
// Copyright 2011-2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// @licend The above is the entire license notice
// for the JavaScript code in this page.
(function(_, $, Backbone, Pump) {
"use strict";
// Private instance
var _socket = {
reconnecting: false,
retryTimeout: 30000,
retryAttempts: 0
};
Pump.getStreams = function() {
var streams = {};
if (Pump.body) {
if (Pump.body.content) {
_.extend(streams, Pump.body.content.getStreams());
}
if (Pump.body.nav) {
_.extend(streams, Pump.body.nav.getStreams());
}
}
return streams;
};
// Refreshes the current visible streams
Pump.refreshStreams = function() {
var streams = Pump.getStreams();
_.each(streams, function(stream, name) {
stream.getPrev();
});
};
Pump.updateStream = function(url, activity) {
var streams = Pump.getStreams(),
target = _.find(streams, function(stream) { return stream.url() == url; }),
act;
if (target) {
act = Pump.Activity.unique(activity);
target.items.unshift(act);
}
};
// When we get a challenge from the socket server,
// We prepare an OAuth request and send it
Pump.riseToChallenge = function(url, method) {
var message = {action: url,
method: method,
parameters: [["oauth_version", "1.0"]]};
Pump.ensureCred(function(err, cred) {
var pair, secrets;
if (err) {
Pump.error("Error getting OAuth credentials.");
return;
}
message.parameters.push(["oauth_consumer_key", cred.clientID]);
secrets = {consumerSecret: cred.clientSecret};
pair = Pump.getUserCred();
if (pair) {
message.parameters.push(["oauth_token", pair.token]);
secrets.tokenSecret = pair.secret;
}
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, secrets);
Pump.socket.send(JSON.stringify({cmd: "rise", message: message}));
});
};
// Our socket.io socket
Pump.socket = null;
Pump.setupSocket = function() {
var here = window.location,
sock;
if (Pump.socket) {
Pump.socket.close();
Pump.socket = null;
}
sock = new SockJS(here.protocol + "//" + here.host + "/main/realtime/sockjs");
sock.onopen = function() {
Pump.socket = sock;
Pump.followStreams();
// Reset reconnect
if (_socket.retryTimer) {
clearTimeout(_socket.retryTimer);
_socket.retryTimer = null;
}
_socket.reconnecting = false;
_socket.retryAttempts = 0;
};
sock.onmessage = function(e) {
var data = JSON.parse(e.data);
switch (data.cmd) {
case "update":
Pump.updateStream(data.url, data.activity);
break;
case "challenge":
Pump.riseToChallenge(data.url, data.method);
break;
}
};
sock.onclose = function(error) {
Pump.socket = null;
// Reconnect on broken connections, not for normal close
if (error.code !== 1000) {
sock.reconnect(error);
}
};
sock.reconnect = function(error) {
_socket.retryAttempts++;
if (_socket.retryTimer) {
clearTimeout(_socket.retryTimer);
_socket.retryTimer = null;
}
if (error.code === 2000 && _socket.retryAttempts > 10) {
// No more attempts if all transports failed
if (!_socket.error) {
// Show alert only one time
_socket.error = error;
Pump.error("Looks like your browser not support any socket transport");
Pump.debug(error);
}
return;
}
if (_socket.reconnecting) {
_socket.retryTimer = setTimeout(Pump.setupSocket, _socket.retryTimeout);
} else {
// The first time try to reconnect immediately
_socket.reconnecting = true;
Pump.setupSocket();
}
};
};
Pump.followStreams = function() {
if (!Pump.config.sockjs) {
return;
}
if (!Pump.socket) {
return;
}
var streams = Pump.getStreams();
_.each(streams, function(stream, name) {
Pump.socket.send(JSON.stringify({cmd: "follow", url: stream.url()}));
});
};
Pump.unfollowStreams = function() {
if (!Pump.config.sockjs) {
return;
}
if (!Pump.socket) {
return;
}
var streams = Pump.getStreams();
_.each(streams, function(stream, name) {
Pump.socket.send(JSON.stringify({cmd: "unfollow", url: stream.url()}));
});
};
})(window._, window.$, window.Backbone, window.Pump);
| JavaScript | 0 | @@ -921,32 +921,8 @@
%22;%0A%0A
- // Private instance%0A
|
129e2b771247ab54fb0302ce5708e02cafd1bfdb | Add translator. | assets/src/edit-story/components/form/dateTime/datePicker.js | assets/src/edit-story/components/form/dateTime/datePicker.js | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
/**
* External dependencies
*/
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';
import { useRef, useCallback, useMemo, useEffect } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
const CalendarWrapper = styled.div`
min-height: 236px;
`;
function DatePicker({ currentDate, onChange, onViewChange }) {
const nodeRef = useRef();
const value = useMemo(() => new Date(currentDate), [currentDate]);
const handleOnChange = useCallback(
(newDate) => {
newDate.setHours(value.getHours());
newDate.setMinutes(value.getMinutes());
onChange(newDate.toISOString(), /* Close calendar */ true);
},
[value, onChange]
);
useEffect(() => {
// Set tabIndex to -1 for every except for the first button.
if (nodeRef.current) {
// Allow tabbing to sections inside the calendar.
const navButtons = [
...nodeRef.current.querySelectorAll(
'.react-calendar__navigation button'
),
];
navButtons.shift();
for (const btn of navButtons) {
btn.tabIndex = '-1';
}
const buttons = [
...nodeRef.current.querySelectorAll(
'.react-calendar__viewContainer button'
),
];
buttons.shift();
for (const btn of buttons) {
btn.tabIndex = '-1';
}
}
}, [nodeRef]);
return (
<CalendarWrapper ref={nodeRef}>
<Calendar
value={value}
onChange={handleOnChange}
onViewChange={onViewChange}
nextAriaLabel={__('Next', 'web-stories')}
prevAriaLabel={__('Previous', 'web-stories')}
next2AriaLabel={__('Jump forward', 'web-stories')}
prev2AriaLabel={__('Jump backwards', 'web-stories')}
/>
</CalendarWrapper>
);
}
DatePicker.propTypes = {
onChange: PropTypes.func.isRequired,
onViewChange: PropTypes.func,
currentDate: PropTypes.string,
};
export default DatePicker;
| JavaScript | 0.000001 | @@ -890,17 +890,17 @@
port %7B _
-_
+x
%7D from
@@ -2235,17 +2235,106 @@
l=%7B_
-_('Next',
+x(%0A 'Next',%0A 'This label can apply to next month, year and/or decade',%0A
'we
@@ -2335,32 +2335,41 @@
'web-stories'
+%0A
)%7D%0A prevA
@@ -2383,21 +2383,114 @@
l=%7B_
-_('Previous',
+x(%0A 'Previous',%0A 'This label can apply to previous month, year and/or decade',%0A
'we
@@ -2491,32 +2491,41 @@
'web-stories'
+%0A
)%7D%0A next2
@@ -2532,26 +2532,37 @@
AriaLabel=%7B_
-_(
+x(%0A
'Jump forwar
@@ -2564,16 +2564,89 @@
orward',
+%0A 'This label can apply to month, year and/or decade',%0A
'web-st
@@ -2643,32 +2643,41 @@
'web-stories'
+%0A
)%7D%0A prev2
@@ -2692,10 +2692,21 @@
l=%7B_
-_(
+x(%0A
'Jum
@@ -2718,16 +2718,89 @@
kwards',
+%0A 'This label can apply to month, year and/or decade',%0A
'web-st
@@ -2805,16 +2805,25 @@
stories'
+%0A
)%7D%0A
|
da751166f48e4a2e4ba9fd382887556ecc275339 | Change componentWillReceiveProps to UNSAFE_componentWillReceiveProps | src/ReactHeight.js | src/ReactHeight.js | import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
const getElementHeightDefault = el => el.clientHeight;
export class ReactHeight extends PureComponent {
static propTypes = {
children: PropTypes.node.isRequired,
onHeightReady: PropTypes.func.isRequired,
hidden: PropTypes.bool,
dirty: PropTypes.bool,
getElementHeight: PropTypes.func
};
static defaultProps = {
hidden: false,
dirty: true,
getElementHeight: getElementHeightDefault
};
constructor(props) {
super(props);
this.state = {
dirty: props.dirty,
height: 0
};
}
componentDidMount() {
const {getElementHeight} = this.props;
const height = getElementHeight(this.wrapper);
const dirty = false;
this.setState({height, dirty}, () => {
const {onHeightReady} = this.props;
const {height: currentHeight} = this.state;
onHeightReady(currentHeight);
});
}
// eslint-disable-next-line react/no-deprecated
componentWillReceiveProps({children, dirty}) {
const {children: oldChildren} = this.props;
if (children !== oldChildren || dirty) {
this.setState({dirty: true});
}
}
componentDidUpdate() {
const {getElementHeight} = this.props;
const height = getElementHeight(this.wrapper);
const dirty = false;
const {height: currentSavedHeight} = this.state;
if (height === currentSavedHeight) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({dirty});
} else {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({height, dirty}, () => {
const {onHeightReady} = this.props;
const {height: currentHeight} = this.state;
onHeightReady(currentHeight);
});
}
}
setWrapperRef = el => {
this.wrapper = el;
};
render() {
const {
onHeightReady: _onHeightReady,
getElementHeight: _getElementHeight,
dirty: _dirty,
hidden,
children,
...props
} = this.props;
const {dirty} = this.state;
if (hidden && !dirty) {
return null;
}
if (hidden) {
return (
<div style={{height: 0, overflow: 'hidden'}}>
<div ref={this.setWrapperRef} {...props}>{children}</div>
</div>
);
}
return <div ref={this.setWrapperRef} {...props}>{children}</div>;
}
}
| JavaScript | 0.000002 | @@ -983,30 +983,27 @@
ine
-react/no-deprecated%0A
+camelcase%0A UNSAFE_
comp
|
886d71b9b3c5d0951d90151d6c38b9b5bde6552b | Update for plug-in : skyrock.com | plugins/skyrock.js | plugins/skyrock.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Skyrock',
version:'0.1',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'a img[src*="small"]',
['/small.', '_small_'],
['/big.', '_']
);
hoverZoom.urlReplace(res,
'a img[src*="_avatar_"]',
'_avatar_',
'_'
);
hoverZoom.urlReplace(res,
'#photolist a img[src*="big"]',
/\?.*$/,
''
);
callback($(res));
}
});
| JavaScript | 0 | @@ -168,16 +168,17 @@
s = %5B%5D;%0A
+%0A
@@ -304,32 +304,33 @@
'_'%5D%0A );%0A
+%0A
hoverZoo
@@ -428,32 +428,33 @@
'_'%0A );%0A
+%0A
hoverZoo
@@ -562,16 +562,587 @@
);%0A
+%0A //sample url:%0A //https://i.skyrock.net/0985/88950985/pics/3331887376_1_38_dKzpHPFD.jpg%0A hoverZoom.urlReplace(res,%0A 'img%5Bsrc%5D',%0A %5B'_0_', '_1_', '.0.', '.1.'%5D,%0A %5B'_2_', '_2_', '.2.', '.2.'%5D%0A );%0A%0A //sample url:%0A //https://wir.skyrock.net/wir/v1/profilcrop/?c=isi&im=/0985/88950985/pics/3331887376_1_32_tqV5beqA.jpg&w=264&h=198%0A hoverZoom.urlReplace(res,%0A 'img%5Bsrc%5D',%0A /http.*im=(.*?)(_%7C%5C.).(_%7C%5C.)(.*?)&(.*)/,%0A 'https://mgl.skyrock.net$1$22$3$4'%0A );%0A%0A
@@ -1156,16 +1156,27 @@
k($(res)
+, this.name
);%0A %7D
|
e8f6e23c16c5d7391809445cb3338e1138ce4906 | delete a vertex in polyline by rightclick. | public/javascripts/patheditor.js | public/javascripts/patheditor.js | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function PathEditor(opt_options) {
var options = opt_options || {};
this.setValues(options);
this.polylines = new Array();
this.earthRadius = 6370986;
this.generalStyle = {strokeColor : "#0000ff", strokeOpacity: 0.5, zIndex: 10};
this.selectedStyle = {strokeColor : "#ff0000", strokeOpacity : 0.7, zIndex: 10};
this.drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.POLYLINE]
},
polylineOptions: this.selectedStyle
});
this.drawingManager.setDrawingMode(null);
this.drawingManager.setMap(this.map);
// this.set('selection', null);
this.set('length', 0);
this.set('prevSelection', null);
var self = this;
google.maps.event.addListener(this.drawingManager, 'polylinecomplete', function(polyline) {
self.addPolyline(polyline);
self.set('selection', polyline);
self.drawingManager.setDrawingMode(null);
});
}
PathEditor.prototype = new google.maps.MVCObject();
PathEditor.prototype.toggleEditable = function (){
if(this.selection != null){
var editable = this.selection.getEditable();
this.selection.setEditable(!editable);
}
};
PathEditor.prototype.deletePath = function (){
if(this.selection != null){
this.selection.setMap(null);
this.set('selection', null);
}
var newPolylines = [];
for (var i = 0; i < this.polylines.length; i++) {
var pl = this.polylines[i];
if(pl.getMap()) newPolylines.push(pl);
}
this.polylines = newPolylines;
}
PathEditor.prototype.deleteAll = function () {
this.set('selection', null);
for (var i = 0; i < this.polylines.length; i++) {
var pl = this.polylines[i];
pl.setMap(null);
}
this.polylines = [];
}
PathEditor.prototype.showPath = function (str, select) {
// clearPath();
// var pl = Walkrr.wkt2GMap(str);
var pl = new google.maps.Polyline({});
pl.setPath(google.maps.geometry.encoding.decodePath(str));
this.addPolyline(pl);
if(select && pl.getPath().getLength() > 0) {
this.set('selection', pl);
var xmin, xmax, ymin, ymax;
pl.getPath().forEach(function (elem, i){
if (i == 0) {
xmin = xmax = elem.lng();
ymin = ymax = elem.lat();
}
else {
if (xmin > elem.lng()) xmin = elem.lng();
if (xmax < elem.lng()) xmax = elem.lng();
if (ymin > elem.lat()) ymin = elem.lat();
if (ymax < elem.lat()) ymax = elem.lat();
}
});
var center = new google.maps.LatLng((ymin+ymax)/2, (xmin+xmax)/2);
this.map.panTo(center);
}
}
PathEditor.prototype.addPolyline = function (pl){
pl.setOptions(this.generalStyle);
pl.setMap(this.map);
this.polylines.push(pl);
var self = this;
google.maps.event.addListener(pl, 'click', function () {
self.set('selection', pl);
});
}
PathEditor.prototype.selection_changed = function (){
var prevSelection = this.get('prevSelection');
if (prevSelection){
prevSelection.setOptions(this.generalStyle);
prevSelection.setEditable(false);
}
var selection = this.get('selection');
this.set('prevSelection', selection);
if (selection) {
selection.setOptions(this.selectedStyle);
var path = this.selection.getPath();
var len = path.getLength();
}
this.clearLocalStorage();
this.set('length', this.getSelectionLength());
}
PathEditor.prototype.getSelectionLength = function (){
var sum = 0;
var d2r = Math.PI/180;
if(this.selection) {
var path = this.selection.getPath();
var len = path.getLength();
for (var i = 1; i < len; i++){
var p0 = path.getAt(i-1);
var p1 = path.getAt(i);
var x = (p0.lng()-p1.lng())*d2r*Math.cos((p0.lat()+p1.lat())/2*d2r);
var y = (p0.lat()-p1.lat())*d2r;
sum += Math.sqrt(x*x + y*y)*this.earthRadius;
}
}
return sum;
}
PathEditor.prototype.storeInLocalStorage = function (){
if (localStorage && this.selection) {
console.log('store');
localStorage['editingPath'] = google.maps.geometry.encoding.encodePath(this.selection.getPath());
}
}
PathEditor.prototype.clearLocalStorage = function (){
if (localStorage) {
console.log('delete');
delete localStorage['editingPath'];
}
}
PathEditor.prototype.loadFromLocalStorage = function (){
if(! localStorage || !localStorage['editingPath']) return false;
console.log('load');
this.showPath(localStorage['editingPath'], true);
return true;
} | JavaScript | 0 | @@ -3269,16 +3269,194 @@
%7D);%0A
+ var deleteNode = function(mev) %7B%0A%09if (mev.vertex != null) %7B%0A%09 pl.getPath().removeAt(mev.vertex);%0A%09%7D%0A %7D%0A google.maps.event.addListener(pl, 'rightclick', deleteNode);%0A
%7D%0APathEd
@@ -5155,8 +5155,9 @@
true;%0A%7D
+%0A
|
ba41ac69de0fdcb4079146aebd745c89752812bd | use prototype when convenient | app/scripts/query.js | app/scripts/query.js | 'use strict';
var regexTerm = /([\w\+\-&\|!\(\){}\[\]\^"~\*\?:\\]+)/g;
var regexNonTerm = /[^\w\+\-&\|!\(\){}\[\]\^"~\*\?:\\]+/g;
var enumGlueTypes = {
or: 1,
and: 2,
phrase: 3,
not: 4
};
var glue = function (term, type, field) {
var rv = '';
switch (type) {
case enumGlueTypes.or:
rv += term.replace(regexTerm, field + ':$1');
rv = rv.replace(regexNonTerm, ' OR ');
break;
case enumGlueTypes.and:
rv += term.replace(regexTerm, field + ':$1');
rv = rv.replace(regexNonTerm, ' AND ');
break;
case enumGlueTypes.phrase:
rv += field + ':"' + term + '"';
break;
case enumGlueTypes.not:
rv += term.replace(regexTerm, '-' + field + ':$1');
rv = rv.replace(regexNonTerm, ' AND ');
break;
}
return rv;
};
var Query = function () {
if (!(this instanceof Query)) {
return new Query();
}
var queryExpressions = [];
this.enumGlueTypes = enumGlueTypes;
this.setQueryExpression = function (index, settings) {
var defaults = { term: '*', field: 'er', glueType: enumGlueTypes.or, glueTypeNextTerm: enumGlueTypes.or };
settings = settings || defaults;
var me = queryExpressions[index] || defaults;
me.term = settings.term || me.term;
me.field = settings.field || me.field;
me.glueType = settings.glueType || me.glueType;
me.glueTypeNextTerm = settings.glueTypeNextTerm || me.glueTypeNextTerm;
queryExpressions[index] = me;
};
this.deleteQueryExpression = function (index) {
delete queryExpressions[index];
};
this.getQueryString = function () {
var prevJoiner;
return queryExpressions.reduce(function(prev, cur) {
var rv = prev;
if (cur) {
var gluedTerm = glue(cur.term, cur.glueType, cur.field);
switch (prevJoiner) {
case enumGlueTypes.or:
rv += ' OR ';
break;
case enumGlueTypes.and:
rv += ' AND ';
break;
case enumGlueTypes.not:
rv += ' AND NOT ';
break;
}
prevJoiner = cur.glueTypeNextTerm;
rv += '(' + gluedTerm + ')';
}
return rv;
}, '');
};
};
module.exports = Query;
| JavaScript | 0 | @@ -969,49 +969,8 @@
%5D;%0A%0A
- this.enumGlueTypes = enumGlueTypes;%0A%0A
@@ -2384,16 +2384,64 @@
%7D;%0A%7D;%0A%0A
+Query.prototype.enumGlueTypes = enumGlueTypes;%0A%0A
module.e
|
6b95e777256b21b185523ba648287ea23af6810f | version bump | web/webpack/webpack.common.js | web/webpack/webpack.common.js | const SPECMATE_VERSION = '0.1.7'
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const GitRevisionPlugin = require('git-revision-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const helpers = require('./helpers');
const gitRevisionPlugin = new GitRevisionPlugin({
commithashCommand: 'rev-parse --short HEAD'
});
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'specmate': './src/main.ts',
'assets': './src/assets.ts',
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [{
test: /\.ts$/,
loaders: [{
loader: 'awesome-typescript-loader',
options: { configFileName: helpers.root('src', 'tsconfig.json') }
}, 'angular2-template-loader']
},
{
test: /\.(html|svg)$/,
loader: 'html-loader',
exclude: [helpers.root('node_modules', 'flag-icon-css'), helpers.root('node_modules', 'font-awesome')]
},
{
test: /\.svg/,
loader: 'file-loader?name=img/[name]_[hash].[ext]',
include: [helpers.root('node_modules', 'flag-icon-css'), helpers.root('node_modules', 'font-awesome')]
},
{
test: /\.(html|svg)$/,
loader: 'string-replace-loader',
query: {
search: '@@version',
replace: SPECMATE_VERSION
}
},
{
test: /\.(png|jpe?g|gif|ico)$/,
loader: 'file-loader?name=img/[name]_[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ['style-loader', 'css-loader']
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
{
test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// We cannot use [hash] or anything similar here, since ng-split will not work then.
loader: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?name=fonts/[name].[ext]",
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
},
{
loader: "postcss-loader",
options: {
sourceMap: true,
plugins: function() {
return [require("autoprefixer")];
}
}
},
{
loader: "sass-loader",
options: {
sourceMap: true
}
}
]
}
]
},
plugins: [
new webpack.ContextReplacementPlugin(/angular(\\|\/)core(\\|\/)@angular/, helpers.root('../src'), {}),
new webpack.ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)esm5/, helpers.root('../src'), {}),
new webpack.optimize.CommonsChunkPlugin({ name: ['specmate', 'vendor', 'polyfills', 'assets'] }),
new HtmlWebpackPlugin({
template: 'src/index.html',
favicon: 'src/assets/img/favicon.ico'
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new CopyWebpackPlugin([{
from: helpers.root('src', 'assets', 'i18n'),
to: 'i18n',
copyUnmodified: true
}])
]
};
| JavaScript | 0.000001 | @@ -27,9 +27,9 @@
0.1.
-7
+8
'%0A%0Ac
|
667d79104ea0803e47e3ca7a1768a65141fd44ff | Update build-docs.js | build-docs.js | build-docs.js | const jsdoc2md = require('jsdoc-to-markdown');
const fs = require('fs')
const glob = require('glob')
glob('lib/**/*.js', {}, (err, files) => {
const docs = files.map(file => {
const doc = jsdoc2md.renderSync({ files: file})
return {
location: `docs/${file.replace('.js', '.md')}`,
content: doc
}
})
docs.forEach( docConfig => {
if (docConfig.content) {
fs.writeFileSync(docConfig.location, docConfig.content, 'utf8')
}
})
})
| JavaScript | 0 | @@ -227,16 +227,17 @@
: file%7D)
+;
%0D%0A re
|
d1230985586fc4cc9e3bb9d6a1190cd3cd97c060 | change var to let | src/Service/api.js | src/Service/api.js | const apiUrl = 'https://en.wikipedia.org/';
const searchUri = "w/api.php?format=json&action=query&prop=extracts&titles="
export default function wikiApi(term) {
return fetch(apiUrl + searchUri + term)
.then(function(response) {
return response.json();
}).then(function(json) {
let article = {};
let results = json.query.pages;
for (var i in results) {
if (i > 0) {
let result = results[i];
article.title = result.title;
article.content = result.extract;
break;
}
}
return article;
});
} | JavaScript | 0 | @@ -347,11 +347,11 @@
or (
-var
+let
i i
@@ -533,8 +533,9 @@
%0A%09%09%7D);%0A%7D
+%0A
|
3ce4953463e85924943efbf864a788f2537e5c1f | Update SlimRequest.js | src/SlimRequest.js | src/SlimRequest.js | 'use strict';
const http = require('http');
const https = require('https');
const Querystring = require('querystring');
let debug = false;
let cache = false;
let log = {debug: (...args)=>{console.log(...args)}, info: (...args)=>{console.log(...args)},warn: (...args)=>{console.log(...args)},fatal: (...args)=>{console.log(...args)}};
let savedRequests = {};
class SlimRequest {
static send(params) {
params = SlimRequest.prepareUrl(params);
if (params.method == "post" || params.method == "POST" )
return SlimRequest.post(params);
else
return SlimRequest.get(params);
}
static checkRequestParams(params) {
if(!params.method)
throw(new Error("Post request need method post or get."));
if (!params.url && !params.host)
throw(new Error("Post request need host or url params."));
}
static prepareUrl(params) {
if (params.alias && savedRequests[params.alias]) {
savedRequests[params.alias].data = params.data || savedRequests[params.alias].data;
return savedRequests[params.alias];
}
SlimRequest.checkRequestParams(params);
if (params.url) {
let parts = params.url.split('://');
if (parts.length != 2)
throw new Error("Url must be like: http://somedomain.com");
params.https = parts[0] === 'https';
let hostLength = parts[1].indexOf('/');
let hostPath = parts[1].split('/');
let host = hostPath.shift();
let hostPort = host.split(':');
params.host = hostPort[0];
params.port = hostPort[1];
let path = "/" + hostPath.join('/');
if (path.indexOf('?') != -1) {
let pathParams = path.split('?');
path = pathParams[0];
}
params.path = path;
params.url = null;
}
if (params.https == null || params.https == undefined)
params.https = true;
if (params.json == null || params.json == undefined)
params.json = true;
if (cache && params.alias)
SlimRequest.saveRequest(params);
return params;
}
static post(params) {
return new Promise((resolve, reject) => {
if (debug)
log.debug("Send Post", params);
var type;
var postData;
if (params.json) {
type = "application/json";
postData = JSON.stringify(params.data || {})
} else {
type = "application/x-www-form-urlencoded";
postData = Querystring.stringify(params.data || {})
}
var postOptions = {
host: params.host, //'closure-compiler.appspot.com'
path: params.path, //'/compile'
method: 'POST',
headers: {
'Content-Type': type,
'Content-Length': Buffer.byteLength(postData)
}
};
if (params.port)
postOptions.port = params.port;
if (debug)
log.debug('postOptions', postOptions);
let protocol = params.https? https : http;
let postReq = protocol.request(postOptions, (res)=> {
let data = '';
res.setEncoding('utf8');
res.once('data', (chunk)=> {
if (debug)
log.debug("Remote host response", {chunk: chunk});
data += chunk;
});
res.once('end', ()=> {
if (debug)
log.debug('No more data in response.');
resolve({statusCode: res.statusCode, headers: res.headers, body: data});
res.removeAllListeners();
})
});
postReq.on('error', (e)=> {
if (debug)
log.warn("Problem with request", {err: e});
postReq.removeAllListeners();
reject(e);
});
postReq.on('response', ()=> {
postReq.removeAllListeners();
});
postReq.write(postData);
postReq.end();
})
}
static get(params) {
return new Promise((resolve, reject) => {
if (params.data) {
var urlParams = "?";
for (let k in params.data) {
if (urlParams != "?")
urlParams += `&${k}=${params.data[k]}`;
else
urlParams += `${k}=${params.data[k]}`
}
params.path += urlParams;
}
let postReq = http.request(params, (res)=> {
res.setEncoding('utf8');
res.once('data', (chunk)=> {
if (debug)
log.debug("Remote host response", {chunk: chunk});
resolve({statusCode: res.statusCode, headers: res.headers, body: chunk});
});
res.once('end', ()=> {
if (debug)
log.debug('No more data in response.');
res.removeAllListeners();
})
});
postReq.on('error', (e)=> {
if (debug)
log.warn("Problem with request", {err: e});
postReq.removeAllListeners();
reject(e);
});
postReq.on('response', ()=> {
postReq.removeAllListeners();
});
postReq.end();
});
}
static saveRequest(params) {
savedRequests[params.alias] = params;
}
static checkRequestsAndSave(requests) {
if (!requests || typeof requests !== "object")
return;
if (Object.keys(requests).indexOf("requests") == -1) {
for (let name in requests) {
SlimRequest.checkRequestsAndSave(requests[name]);
}
return;
}
for (let request of requests.requests) {
SlimRequest.prepareUrl(request);
}
}
static loadRequests(cfg) {
for (let name of cfg.requests) {
SlimRequest.checkRequestsAndSave(cfg[name])
}
}
static debugMode(v = true, userLog ) {
debug = v;
log = log || userLog;
}
static cacheMode(v = true) {
cache = v;
}
static get savedRequests() {
return savedRequests
}
}
module.exports = SlimRequest;
| JavaScript | 0 | @@ -3452,34 +3452,32 @@
res.on
-ce
('data', (chunk)
|
bf3219009278131dc2f4b46951870bd254331bda | implement modal on dashboard | app/src/Dashboard.js | app/src/Dashboard.js | import React, { Component } from 'react';
import CategoryForm from './category/CategoryForm';
export default class Dashboard extends Component {
render(){
return(
<div>
<CategoryForm />
</div>
)
}
} | JavaScript | 0.000001 | @@ -86,16 +86,54 @@
ryForm';
+%0Aimport ReactModal from 'react-modal';
%0A%0Aexport
@@ -185,83 +185,764 @@
-render()%7B%0A return(%0A %3Cdiv%3E%0A %3CCategoryForm /
+constructor() %7B%0A super();%0A this.state = %7B%0A showModal: false%0A %7D;%0A%0A this.handleOpenModal = this.handleOpenModal.bind(this);%0A this.handleCloseModal = this.handleCloseModal.bind(this);%0A %7D%0A%0A handleOpenModal() %7B%0A this.setState(%7BshowModal: true%7D);%0A %7D%0A%0A handleCloseModal() %7B%0A this.setState(%7BshowModal: false%7D);%0A %7D%0A%0A render()%7B%0A return(%0A %3Cdiv%3E%0A %3Cbutton onClick=%7Bthis.handleOpenModal%7D%3E+%3C/button%3E%0A %3CReactModal%0A isOpen=%7Bthis.state.showModal%7D%0A contentLabel=%22Dashboard%22%3E%0A %3CCategoryForm /%3E%0A %3Cbutton onClick=%7Bthis.handleCloseModal%7D%3EX%3C/button%3E%0A %3C/ReactModal
%3E%0A
|
410c94f869fa314d1d74a011bd645f07fbcac465 | add missing unbind | public/scripts/app/views/Home.js | public/scripts/app/views/Home.js | define(function(require) {
'use strict';
var $ = require('jquery')
, _ = require('underscore')
, Hammer = require('hammer.min')
, Base = require('app/views/Base')
, socket = require('app/utils/socket')
, ChannelListView = require('app/views/ChannelList')
, ActivityView = require('app/views/Activity/Index')
, SettingsView = require('app/views/Settings')
, log = require('bows.min')('Views:Home')
return Base.extend({
template: _.template(require('text!tpl/Home.html')),
requiresLogin: true,
title: 'Home',
events: {
'click .tabs-item': 'onTabClick',
},
className: 'home screen screen--hasTabViews',
initialize: function(options) {
_.bindAll(this, 'onResize', 'onPanStart', 'onPanMove', 'onPanEnd', 'onTransitionEnd')
this.options = options
},
beforeRender: function() {
if (this.channelListView) {
return
}
this.channelListView = new ChannelListView(this.options)
this.activityView = new ActivityView(this.options)
this.settingsView = new SettingsView(this.options)
this.settingsView.on('error', this.showError, this)
this.tabViews = [
this.channelListView,
this.activityView,
this.settingsView
]
},
render: function() {
this.beforeRender()
var tabViews = document.createDocumentFragment()
this.tabViews.forEach(function(view){
tabViews.appendChild(view.render().el)
})
this.$el.html(this.template())
this.scroller = this.$el.find('.tab-scroller')
this.scroller.append(tabViews)
this.trigger('render')
this.initializeTabViews()
return this
},
initializeTabViews: function() {
this.viewsHolder = this.$el.find('.tab-views')
this.activeIndicator = this.$el.find('.tabs-activeIndicator')
this.navItems = this.$el.find('.tabs-item')
this.viewItems = this.$el.find('.tab-views-item')
this.xMax = this.viewItems.size() - 1
this.scroller.on('transitionend', this.onTransitionEnd)
this.hammertime = new Hammer(this.scroller.get(0))
this.hammertime.on('panstart', this.onPanStart)
this.hammertime.on('panmove', this.onPanMove)
this.hammertime.on('panend', this.onPanEnd)
// stores the current xPos
this.xPos = 0
// adapt view height when channelList got filled
this.channelListView.on('loaded:channel', this.adaptViewsHeight, this)
// update dimensions
this.onResize()
$(window).on('resize.home', this.onResize)
// go to first item
this.navigateTo(this.viewItems.first().attr('data-view'))
},
onDestroy: function() {
$(window).off('resize.home', this.onResize)
this.hammertime.destroy()
},
onResize: function() {
var self = this
this.viewWidth = this.$el.width()
this.tabWidth = this.navItems.first().outerWidth()
this.activeIndicator.width(this.tabWidth)
// cache visible view area height
this.contentHeight = this.$el.outerHeight() - this.$el.find('.screen-header').height()
this.scroller.width(this.viewItems.size() * this.viewWidth)
this.viewItems.css({
width: this.viewWidth,
left: function(i) { return i * self.viewWidth }
})
if(this.visibleTabView)
this.navigateTo(this.visibleTabView.attr('data-view'))
},
onPanStart: function() {
// disable transitions on the scroller so that we can move it
this.scroller.addClass('no-transition')
this.activeIndicator.addClass('no-transition')
},
onPanMove: function(event) {
var newX = this.xPos * this.viewWidth - event.deltaX
this.moveIt(newX)
},
onPanEnd: function(event) {
// re-enable transitions on the scroller
this.scroller.removeClass('no-transition')
this.activeIndicator.removeClass('no-transition')
if(event.deltaX < -this.viewWidth/2 && this.xPos < this.xMax) {
this.xPos += 1
}
else if(event.deltaX > this.viewWidth/2 && this.xPos > 0) {
this.xPos -= 1
}
this.navigateTo(this.viewItems.eq(this.xPos).attr('data-view'))
},
onTabClick: function(event) {
this.navigateTo(event.currentTarget.getAttribute('data-target'))
},
navigateTo: function(viewName) {
this.visibleTabView = this.viewItems.filter('[data-view='+ viewName +']')
this.xPos = this.visibleTabView.index()
this.visibleTabView.addClass('is-visible')
// adjust height
this.adaptViewsHeight()
this.moveIt(this.xPos * this.viewWidth)
console.log(this.xPos, this.viewWidth, viewName)
},
onTransitionEnd: function() {
this.viewItems.filter('.is-visible').not(this.visibleTabView).removeClass('is-visible')
},
adaptViewsHeight: function() {
// reset height
this.viewsHolder.css('height', '')
var height = Math.max(this.visibleTabView.height(), this.contentHeight)
this.viewsHolder.css('height', height)
},
moveIt: function(x) {
var indicatorPos = x/this.viewWidth * this.tabWidth
// limit indicator to view boundaries
indicatorPos = Math.max(0, Math.min(this.xMax * this.tabWidth, indicatorPos))
this.activeIndicator.css('transform', 'translateX('+ indicatorPos +'px)')
this.scroller.css('transform', 'translateX('+ (-x) +'px)')
}
})
})
| JavaScript | 0.000005 | @@ -3066,32 +3066,99 @@
y: function() %7B%0A
+ this.scroller.off('transitionend', this.onTransitionEnd)%0A
$(wind
|
00c89340463240764c808e3ed128f8601395dd8f | Use better confirm dialog | public/viewjs/userpermissions.js | public/viewjs/userpermissions.js | $('input.permission-cb').click(
function()
{
check_hierachy(this.checked, this.name);
}
);
function check_hierachy(checked, name)
{
var disabled = checked;
$('#permission-sub-' + name).find('input.permission-cb')
.prop('checked', disabled)
.attr('disabled', disabled);
}
$('#permission-save').click(
function()
{
var permission_list = $('input.permission-cb')
.filter(function()
{
return $(this).prop('checked') && !$(this).attr('disabled');
}).map(function()
{
return $(this).data('perm-id');
}).toArray();
Grocy.Api.Put('users/' + Grocy.EditObjectId + '/permissions', { 'permissions': permission_list },
function(result)
{
toastr.success(__t("Permissions saved"));
},
function(xhr)
{
toastr.error(JSON.parse(xhr.response).error_message);
}
);
}
);
if (Grocy.EditObjectId == Grocy.UserId)
{
$('input.permission-cb[name=ADMIN]').click(function()
{
if (!this.checked)
{
if (!confirm(__t('Are you sure you want to remove full permissions for yourself?')))
{
this.checked = true;
check_hierachy(this.checked, this.name);
}
}
})
}
| JavaScript | 0 | @@ -922,132 +922,447 @@
%7B%0A%09%09
-if (!this.checked)%0A%09%09%7B%0A%09%09%09if (!confirm(__t('Are you sure you want to remove full permissions for yourself?')))%0A%09%09%09%7B%0A%09%09%09%09this
+var element = this;%0A%0A%09%09if (!element.checked)%0A%09%09%7B%0A%09%09%09bootbox.confirm(%7B%0A%09%09%09%09message: __t('Are you sure you want to remove full permissions for yourself?'),%0A%09%09%09%09closeButton: false,%0A%09%09%09%09buttons: %7B%0A%09%09%09%09%09confirm: %7B%0A%09%09%09%09%09%09label: __t('Yes'),%0A%09%09%09%09%09%09className: 'btn-success'%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09cancel: %7B%0A%09%09%09%09%09%09label: __t('No'),%0A%09%09%09%09%09%09className: 'btn-danger'%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D,%0A%09%09%09%09callback: function(result)%0A%09%09%09%09%7B%0A%09%09%09%09%09if (result == false)%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09element
.che
@@ -1378,16 +1378,18 @@
ue;%0A%09%09%09%09
+%09
+%09
check_hi
@@ -1387,36 +1387,39 @@
%09check_hierachy(
-this
+element
.checked, this.n
@@ -1404,36 +1404,39 @@
lement.checked,
-this
+element
.name);%0A%09%09%09%7D%0A%09%09%7D
@@ -1430,17 +1430,32 @@
me);%0A%09%09%09
-%7D
+%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%7D);
%0A%09%09%7D%0A%09%7D)
|
60ae22f8d954730f0a6edf4881907f4974e62af4 | Fix js typo | webapps/callimachus/status.js | webapps/callimachus/status.js | /*
Copyright (c) 2009-2010 Zepheira LLC, Some Rights Reserved
Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
*/
$(document).ready(initForms);
var formRequestCount = 0;
function initStatus() {
$(window).unload(function (event) {
$("form[about]").addClass("wait")
formRequestCount++
})
$("form[about]").ajaxSend(function(event, xhr, options){
if (!$(this).hasClass("wait")) {
$(this).addClass("wait")
}
formRequestCount++
})
$("form[about]").ajaxComplete(function(event, xhr, options){
formRequestCount--
if (formRequestCount < 1) {
$(this).removeClass("wait")
formRequestCount = 0
}
})
}
function showPageLoading() {
$("form[about]").addClass("wait")
formRequestCount++
}
function showRequest() {
$("#message").empty();
$('#message').trigger('status.calli', []);
}
function showSuccess() {
$("#message").empty();
$('#message').trigger('status.calli', []);
}
function showError(text, detail) {
var msg = $("#message")
if (msg.size()) {
msg.empty()
msg.text(text)
msg.addClass("error")
msg.focus()
if (detail && detail.indexOf('<') == 0) {
detail = $(detail).text()
}
if (detail) {
var pre = $("<pre/>")
pre.text(detail)
pre.hide()
msg.append(pre)
msg.click(function() {
pre.toggle()
})
}
msg.trigger('status.calli', [text, detail]);
} else {
alert(text);
}
}
| JavaScript | 0.999819 | @@ -182,12 +182,13 @@
init
-Form
+Statu
s);%0A
|
c1b030e1db0618a93ec7870abd05842100fc4e1a | update webpack dev config | webpack.development.config.js | webpack.development.config.js | var path = require('path');
var webpack = require('webpack');
module.exports = {
entry:
{
app: [
'webpack-hot-middleware/client',
'./public/src/containers/app'
]
},
output:
{
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/public/asset/js/bundle/',
chunkFilename: "./asset/js/bundle/bundle.[name].js"
},
resolve:
{
"extensions": ["", ".js", ".jsx"]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module:
{
loaders: [
{
test: /\.js?$/,
loader: 'babel',
include: path.resolve(__dirname, 'public'),
exclude: /node_modules/
},
{
test: /\.json$/,
loader: "json-loader"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader?includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'url-loader?limit=8192&name=./asset/img/[name].[ext]'
}]
}
};
| JavaScript | 0 | @@ -491,170 +491,8 @@
%7D,%0A
- plugins: %5B%0A new webpack.optimize.OccurenceOrderPlugin(),%0A new webpack.HotModuleReplacementPlugin(),%0A new webpack.NoErrorsPlugin()%0A %5D,%0A
@@ -1205,12 +1205,174 @@
%7D%5D%0A %7D
+,%0A plugins: %5B%0A new webpack.optimize.OccurenceOrderPlugin(),%0A new webpack.HotModuleReplacementPlugin(),%0A new webpack.NoErrorsPlugin()%0A %5D
%0A%7D;%0A
|
9555dcc2e0af4954105467ea7605d60373f714d2 | 禁用扩展 reload | webpack/webpack.config.dev.js | webpack/webpack.config.dev.js | const _ = require('lodash');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VersionFilePlugin = require('webpack-version-file-plugin');
const ChromeExtensionReloader = require('webpack-chrome-extension-reloader');
const config = require('./config.js');
module.exports = _.merge({}, config, {
output: {
path: path.resolve(__dirname, '../build/dev'),
},
devtool: 'source-map',
plugins: [
new CopyWebpackPlugin([
{ from: './src' }
], {
ignore: ['js/**/*', 'manifest.json'],
copyUnmodified: false
}),
new VersionFilePlugin({
packageFile: path.resolve(__dirname, '../package.json'),
template: path.resolve(__dirname, '../src/manifest.json'),
outputFile: path.resolve(__dirname, '../build/dev/manifest.json'),
}),
new ChromeExtensionReloader() // ONLY USE IT IN DEVELOPMENT BUILD!
],
watch: true
});
| JavaScript | 0 | @@ -820,24 +820,27 @@
%0A %7D),%0A
+ //
new ChromeE
|
7ed3d632adb270538d8246d2517d84eb0398700e | update website-auto-redirect | website-auto-redirect.user.js | website-auto-redirect.user.js | // ==UserScript==
// @name website-auto-redirect
// @description auto redirect to article
// @include http://next.36kr.com/posts/*
// @include http://toutiao.io/posts/*
// @include http://wanqu.co/*
// @exclude http://wanqu.co/blog/*
// @include http://v.videohupu.com/*/v*.html
// @include http://v.liangle.com/*/v*.html
// @include https://www.producthunt.com/*
// @downloadURL https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/website-auto-redirect.user.js
// @updateURL https://raw.githubusercontent.com/goorockey/greasemonkey-scripts/master/website-auto-redirect.user.js
// @version 1.5
// @grant none
// author kelvingu616@gmail.com
// github github.com/goorockey
// ==/UserScript==
var website_target = {
'wanqu.co': '//a[@rel="external"]/@href',
'next.36kr.com': '//a[@class="post-url"]/@href',
'toutiao.io': '//h3[@class="title"]/a[1]/@href',
'v.videohupu.com': '//a[@class="play_btn"]/@href',
'v.liangle.com': '//a[@class="play_btn"]/@href',
'www.producthunt.com': '//main//a[1]/@href',
};
function getUrlByXpath(path) {
return document.evaluate(path, document, null, XPathResult.STRING_TYPE, null).stringValue;
}
var xpath = website_target[location.host];
if (!xpath) {
return;
}
var url = getUrlByXpath(xpath);
if (url) {
window.location.replace(url);
}
| JavaScript | 0 | @@ -392,16 +392,66 @@
t.com/*%0A
+// @include http://today.itjuzi.com/product/*%0A
// @down
@@ -700,9 +700,9 @@
1.
-5
+6
%0A//
@@ -1134,16 +1134,70 @@
@href',%0A
+ 'today.itjuzi.com': '//a%5B@id=%22today_title%22%5D/@href',%0A
%7D;%0A%0Afunc
|
afa8cdda5d939f5828a4646717c47c9fda873951 | remove restrict | src/alert/alert.js | src/alert/alert.js | angular.module('ui.bootstrap.alert', [])
.controller('AlertController', ['$scope', '$attrs', function($scope, $attrs) {
$scope.closeable = !!$attrs.close;
this.close = $scope.close;
}])
.directive('alert', function() {
return {
restrict: 'EA',
controller: 'AlertController',
controllerAs: 'alert',
templateUrl: function(element, attrs) {
return attrs.templateUrl || 'template/alert/alert.html';
},
transclude: true,
replace: true,
scope: {
type: '@',
close: '&'
}
};
})
.directive('dismissOnTimeout', ['$timeout', function($timeout) {
return {
require: 'alert',
link: function(scope, element, attrs, alertCtrl) {
$timeout(function() {
alertCtrl.close();
}, parseInt(attrs.dismissOnTimeout, 10));
}
};
}]);
| JavaScript | 0.000002 | @@ -233,28 +233,8 @@
n %7B%0A
- restrict: 'EA',%0A
|
3edc51da83e4ff84c949ecdebc86871c4814bd47 | cut uniprot features down to domains | src/CLMS/model/SearchResultsModel.js | src/CLMS/model/SearchResultsModel.js | // CLMS-model
// Copyright 2015 Rappsilber Laboratory, Edinburgh University
//
// authors: Colin Combe, Martin Graham
//
// SearchResultsModel.js
var CLMS = CLMS || {};
CLMS.model = CLMS.model || {};
CLMS.model.SearchResultsModel = Backbone.Model.extend ({
//http://stackoverflow.com/questions/19835163/backbone-model-collection-property-not-empty-on-new-model-creation
defaults : function() {
return {
interactors: new Map (), //map
peptides: new Map (), //map
matches: new Map (), //map
crossLinks: new Map(), //map
minScore: NaN,
maxScore: NaN,
searches: new Map()
};
},
initialize: function (options) {
var defaultOptions = {};
this.options = _.extend(defaultOptions, options);
var self = this;
this.set("sid", this.options.sid);
//search meta data
var searches = new Map();
for(var propertyName in this.options.searches) {
var search = this.options.searches[propertyName];
searches.set(propertyName, search);
}
this.set("searches", searches);
this.set("xiNETLayout", options.xiNETLayout);
// we will be removing modification info from sequences
var capitalsOnly = /[^A-Z]/g;
//proteins or 'participants'
var interactors = new Map();// lets not call this 'interactors' after all
var proteins = this.options.proteins;
var protein;
for (var propertyName in proteins) {
capitalsOnly.lastIndex = 0;
protein = proteins[propertyName];
protein.sequence = protein.seq_mods.replace(capitalsOnly, '');
protein.size = protein.sequence.length;
protein.crossLinks = [];
interactors.set(protein.id, protein);
}
this.set("interactors", interactors);
//peptides
var peptides = new Map();
var peptide;
for (var propertyName in this.options.peptides) {
capitalsOnly.lastIndex = 0;
peptide = this.options.peptides[propertyName];
peptide.sequence = peptide.seq_mods.replace(capitalsOnly, '');
peptides.set(peptide.id, peptide);
}
this.set("peptides", peptides);
var rawMatches = this.options.rawMatches;
if (rawMatches) {
var matches = this.get("matches");
var minScore = this.get("minScore");
var maxScore = this.get("maxScore");
var l = rawMatches.length, match;
for (var i = 0; i < l; i++) {
//TODO: this will need updated for ternary or higher order crosslinks
if ((i < (l - 1)) && rawMatches[i].id == rawMatches[i+1].id){
match = new CLMS.model.SpectrumMatch (this, [rawMatches[i], rawMatches[i+1]]);
i++;
}
else {
match = new CLMS.model.SpectrumMatch (this, [rawMatches[i]]);
}
matches.set(match.id, match);
if (!maxScore || match.score > maxScore) {
maxScore = match.score;
}
else if (!minScore || match.score < minScore) {
minScore = this.score;
}
}
}
var interactorCount = interactors.size;
var xiNET_StorageNS = "xiNET.";
var uniprotFeatureTypes = new Set();
var uniprotAccRegex = /[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}/
if (interactors.size < 31) {
for (var protein of interactors.values()){
uniProtTxt(protein);
}
}
else {
CLMSUI.vent.trigger("uniprotDataParsed", self);
}
function uniProtTxt (p){
uniprotAccRegex.lastIndex = 0;
if (!p.is_decoy && uniprotAccRegex.test(p.accession)) {
function uniprotWebService(){
var url = "http://www.uniprot.org/uniprot/" + p.accession + ".txt";
d3.text(url, function (txt) {
processUniProtTxt(p, txt);
});
}
uniprotWebService();
} else { //not protein, no accession or isDecoy
interactorCount--;
if (interactorCount === 0) doneProcessingUniProtText();
}
}
function processUniProtTxt(p, txt){
txt = txt || "";
var features = [];
var sequence = "";
var lines = txt.split('\n');
var lineCount = lines.length;
for (var l = 1; l < lineCount; l++){
var line = lines[l];
if (line.indexOf("FT") === 0){
var fields = line.split(/\s{2,}/g);
if (fields.length > 4 ) {// && fields[1] === 'DOMAIN') {
uniprotFeatureTypes.add(fields[1]);
//console.log(fields[1]);fields[4].substring(0, fields[4].indexOf("."))
var name = fields[4].substring(0, fields[4].indexOf("."));
features.push(new CLMS.model.AnnotatedRegion (name, fields[2], fields[3], null, fields[4], fields[1]));
}
}
if (line.indexOf("SQ") === 0){
//sequence = line;
l++;
for (l; l < lineCount; l++){
line = lines[l];
sequence += line;
}
}
}
p.uniprotFeatures = features;
sequence = sequence.replace(/[^A-Z]/g, '');
p.canonicalSeq = sequence;
interactorCount--;
if (interactorCount === 0) doneProcessingUniProtText();
}
function doneProcessingUniProtText(){
//~ for (var protein of interactorMap.values()) {
//~ console.log(protein.id + "\t" + protein.accession + "\t" + protein.sequence)
//~ console.log(protein.id + "\t" + protein.accession + "\t" + protein.canonicalSeq)
//~ }
//~ console.log("uniprotFeatureTypes:" + Array.from(uniprotFeatureTypes.values()).toString());
self.set("uniprotFeatureTypes", uniprotFeatureTypes);
CLMSUI.vent.trigger("uniprotDataParsed", self);
}
}
});
| JavaScript | 0 | @@ -5220,14 +5220,8 @@
%3E 4
- ) %7B//
&&
|
38815c16f57d9ab9f748bdf48e714cd76afc563f | add timeout | src/api/service.js | src/api/service.js | 'use strict';
const axios = require('axios');
const { GITHUB_API_URL } = require('../../config/api_url');
class GithubService {
constructor() {
this.url = GITHUB_API_URL,
this.timeout = 10000;
this.clientParams = `client_id=${process.env.CLIENT_ID}&client_secret=${process.env.CLIENT_SECRET}`;
}
async getUser(username) {
const options = {
method: 'GET',
headers: {
'User-Agent': `${username}`
},
url: `${this.url}/users/${username}?${this.clientParams}`
};
try {
return await axios(options);
} catch (e) {
throw e;
}
}
async getReposForUser(username, page) {
const options = {
method: 'GET',
headers: {
'User-Agent': `${username}`
},
url: `${this.url}/users/${username}/repos?${this.clientParams}&per_page=100&page=${page}`
};
try {
return await axios(options);
} catch (e) {
throw e;
}
}
}
module.exports = GithubService;
| JavaScript | 0.000005 | @@ -481,32 +481,67 @@
%0A %7D,%0A
+ timeout: this.timeout,%0A
url:
@@ -892,32 +892,67 @@
%0A %7D,%0A
+ timeout: this.timeout,%0A
url:
|
21a964796dabc4fce9fac32a2e4d4111caef6c6f | Fix whitespace in Lokalka's soup names | parsers/lokalka.js | parsers/lokalka.js | var cheerio = require('cheerio');
require('./parserUtil');
module.exports.parse = function(html, date, callback) {
var $ = cheerio.load(html);
var dayMenu = [];
var todayDate = date.format('DD.MM.YYYY');
var elements = $('li.fdm-item', 'div.entry-content.post-content');
elements.each(function(){
var node = $(this);
var title = node.find('p.fdm-item-title').text();
if(isToday(title)){
parseDailyMenu(node.find('table'));
return false;
}
});
callback(dayMenu);
function isToday(title) {
return title.toLowerCase().indexOf(todayDate) !== -1;
}
function parseDailyMenu(table) {
var rows = table.find('tr');
rows.each(function(index, elem){
if(index === 0){
return;
}
if(index === 1){
dayMenu = dayMenu.concat(parseSoup(elem));
}
else{
dayMenu.push(parseOther(elem));
}
});
}
function parseSoup(row) {
var cells = $(row).find('td');
var price = parseFloat(cells.eq(5).text().replace(',', '.'));
var text = cells.eq(1).text() + " " + cells.eq(2).text();
var soups = text.split('/');
return soups.map(function(item) { return { isSoup: true, text: item, price: price }; });
}
function parseOther(row) {
var cells = $(row).find('td');
return { isSoup: false, text: cells.eq(0).text(), price: parseFloat(cells.eq(3).text().replace(',', '.')) };
}
};
| JavaScript | 0.999998 | @@ -1267,16 +1267,23 @@
xt: item
+.trim()
, price:
|
a0c1d78c271a01f6e531d93b8dcd505994b335e1 | Update python script arguments in node script | private/scraper.js | private/scraper.js | var PythonShell = require('python-shell');
var options = {
scriptPath: 'realclearpolitics-scraper',
args: [
'http://www.realclearpolitics.com/epolls/2016/president/nv/nevada_democratic_presidential_caucus-5337.html',
'test.json'
]
}
PythonShell.run('scraper.py', options, function(err, results) {
if (err) throw err;
console.log(results);
});
| JavaScript | 0 | @@ -103,19 +103,16 @@
%09args: %5B
-%0A%09%09
'http://
@@ -214,25 +214,8 @@
tml'
-,%0A%09%09'test.json'%0A%09
%5D%0A%7D%0A
|
d3f52019681fcbf561836662eeb39541f38613be | fix high cpu usage at start by set watcher depth | projectsWatcher.js | projectsWatcher.js | 'use strict';
var _ = require('underscore'),
path = require('path'),
chokidar = require('chokidar'),
project = require('./lib/project'),
logger = require('./lib/logger')('projects watcher');
exports.init = function(app, callback) {
// start file watcher for reloading projects on change
var syncProject = function(filename, fileInfo) {
var baseDir = app.config.paths.projects,
projectName = path.relative(
baseDir,
path.dirname(filename)
);
var projectIndex = _(app.projects).findIndex(function(project) {
return project.name === projectName;
});
if (projectIndex !== -1) {
logger.log('Unload project: "' + projectName + '"');
var unloadedProject = app.projects.splice(projectIndex, 1)[0];
app.emit('projectUnloaded', unloadedProject);
}
// on add or change (info is falsy on unlink)
if (fileInfo) {
logger.log('Load project "' + projectName + '" on change');
project.load(baseDir, projectName, function(err, project) {
if (err) {
return logger.error(
'Error during load project "' + projectName + '": ',
err.stack || err
);
}
app.projects.push(project);
logger.log(
'Project "' + projectName + '" loaded:',
JSON.stringify(project, null, 4)
);
app.emit('projectLoaded', project);
});
}
};
// NOTE: currently after add remove and then add same file events will
// not be emitted
var watcher = chokidar.watch(
path.join(app.config.paths.projects, '*', 'config.*'),
{ignoreInitial: true}
);
watcher.on('add', syncProject);
watcher.on('change', syncProject);
watcher.on('unlink', syncProject);
watcher.on('error', function(err) {
logger.error('File watcher error occurred: ', err.stack || err);
});
callback();
};
| JavaScript | 0.000001 | @@ -1503,16 +1503,26 @@
al: true
+, depth: 1
%7D%0A%09);%0A%09w
|
b65e2d5b5f2672d9a5321e0705ca1370c7352e98 | Fix the link inside the tag` | promise/js/main.js | promise/js/main.js | (function() {
function getUrl(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status === 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error('Network Error'));
};
// Make the request
req.send();
});
}
var newsEndPointUrl = 'js/feed.json';
getUrl(newsEndPointUrl).then(function(response) {
console.log('Success! We got the feed.', JSON.parse(response));
var feed = JSON.parse(response);
var stories = feed.value.items;
var ul = '<ul>';
for (var i = 0; i < stories.length; i++) {
var title = stories[i].title;
var link = stories[i].link;
ul += '<li><h3><a class=\"story\" href=\"+ link +\">' + title + '</a></h3> ';
}
ul += '</ul>';
var mainFeed = document.querySelector('.main-feed');
function addHtmlToPage(content) {
var div = document.createElement('div');
div.innerHTML = content;
mainFeed.appendChild(div);
}
addHtmlToPage(ul);
}, function(error) {
console.error('Failed! No feed for you', error);
});
})(); | JavaScript | 0 | @@ -957,23 +957,16 @@
onse) %7B%0A
- %0A
co
@@ -1282,32 +1282,16 @@
3%3E%3Ca
- class=%5C%22story%5C%22
href=%5C%22
+ li
@@ -1290,16 +1290,18 @@
f=%5C%22
+'
+ link +
%5C%22%3E'
@@ -1300,14 +1300,48 @@
nk +
-%5C%22%3E' +
+ '%5C%22 class=%5C%22story%5C%22%3E' + %0A
tit
@@ -1355,17 +1355,16 @@
/a%3E%3C/h3%3E
-
';%0A
|
379d309b30f4cb9104b28e8e6cb04352cad71cc2 | add title | dashboard/lib/routes/index.js | dashboard/lib/routes/index.js | /*
* Copyright 2015 Telefónica I+D
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
'use strict';
var express = require('express'),
router = express.Router(),
dateFormat = require('dateformat'),
cbroker = require('./cbroker');
/* GET home page. */
router.get('/', function (req, res) {
var timestamp = dateFormat(new Date(), 'yyyy-mm-dd h:MM:ss');
cbroker.postAllRegions(function (regions) {
console.log('regions:' + regions);
res.render('index', {timestamp: timestamp, regions: regions});
});
});
/** @export */
module.exports = router;
| JavaScript | 0.999996 | @@ -1025,16 +1025,56 @@
ndex', %7B
+title: 'FIWARE Regions - Sanity check',
timestam
|
f77e44f2ddddabd71e443278ca00193215bf9954 | edit snippet newsletter | addons/website_mass_mailing/static/src/js/website_mass_mailing.editor.js | addons/website_mass_mailing/static/src/js/website_mass_mailing.editor.js | odoo.define('website_mass_mailing.editor', function (require) {
'use strict';
var Model = require('web.Model');
var ajax = require('web.ajax');
var core = require('web.core');
var base = require('web_editor.base');
var web_editor = require('web_editor.editor');
var options = require('web_editor.snippets.options');
var snippet_editor = require('web_editor.snippet.editor');
var website = require('website.website');
var _t = core._t;
var mass_mailing_common = options.Class.extend({
popup_template_id: "editor_new_mailing_list_subscribe_button",
popup_title: _t("Add a Newsletter Subscribe Button"),
select_mailing_list: function (type, value) {
var self = this;
if (type !== "click") return;
var def = website.prompt({
'id': this.popup_template_id,
'window_title': this.popup_title,
'select': _t("Newsletter"),
'init': function (field) {
return new Model('mail.mass_mailing.list').call('name_search', ['', []], { context: base.get_context() });
},
});
def.then(function (mailing_list_id) {
self.$target.attr("data-list-id", mailing_list_id);
});
return def;
},
drop_and_build_snippet: function() {
var self = this;
this._super();
this.select_mailing_list('click').fail(function () {
self.editor.on_remove($.Event( "click" ));
});
},
});
options.registry.mailing_list_subscribe = mass_mailing_common.extend({
clean_for_save: function () {
this.$target.addClass("hidden");
},
});
options.registry.newsletter_popup = mass_mailing_common.extend({
popup_template_id: "editor_new_mailing_list_subscribe_popup",
popup_title: _t("Add a Newsletter Subscribe Popup"),
select_mailing_list: function (type, value) {
var self = this;
if (type !== "click") return;
return this._super(type, value).then(function (mailing_list_id) {
ajax.jsonRpc('/web/dataset/call', 'call', {
model: 'mail.mass_mailing.list',
method: 'read',
args: [[parseInt(mailing_list_id)], ['popup_content'], base.get_context()],
}).then(function (data) {
self.$target.find(".o_popup_content_dev").empty();
if (data && data[0].popup_content) {
$(data[0].popup_content).appendTo(self.$target.find(".o_popup_content_dev"));
}
});
});
},
});
web_editor.Class.include({
edit: function () {
this._super();
$('body').on('click','#edit_dialog',_.bind(this.edit_dialog, this.rte.editor));
},
save : function() {
var $target = $('#wrapwrap').find('#o_newsletter_popup');
if ($target && $target.length) {
$target.modal('hide');
$target.css("display", "none");
$('.o_popup_bounce_small').show();
if (!$target.find('.o_popup_content_dev').length) {
$target.find('.o_popup_modal_body').prepend($('<div class="o_popup_content_dev" data-oe-placeholder="' + _t("Type Here ...") + '"></div>'));
}
var content = $('#wrapwrap .o_popup_content_dev').html();
var newsletter_id = $target.parent().attr('data-list-id');
ajax.jsonRpc('/web/dataset/call', 'call', {
model: 'mail.mass_mailing.list',
method: 'write',
args: [parseInt(newsletter_id),
{'popup_content':content},
base.get_context()],
});
}
return this._super();
},
edit_dialog : function() {
$('#wrapwrap').find('#o_newsletter_popup').modal('show');
$('.o_popup_bounce_small').hide();
$('.modal-backdrop').css("z-index", "0");
},
});
});
| JavaScript | 0.001914 | @@ -2599,19 +2599,20 @@
e(%7B%0A
-edi
+star
t: funct
@@ -2620,39 +2620,16 @@
on () %7B%0A
- this._super();%0A
@@ -2704,24 +2704,54 @@
e.editor));%0A
+ return this._super();%0A
%7D,%0A s
|
1d5072da040fe04227b8c10fc410183d70098dee | Return new created contact properly | routes/contacts.js | routes/contacts.js | const express = require('express');
const router = express.Router();
const promise = require('bluebird')
const utils = require('../utilities.js')
const contactManager = require('../bin/contact-manager/contact-manager')
/**
* Handles the route `GET /contacts`.
* Lists the first 100 of the contacts available to the user, with a given offset
*/
router.get('/', function (req, res, next) {
// If the GET param 'offset' is supplied, use it. Otherwise, use 0.
let offset = (req.query.offset == undefined ? 0 : req.query.offset)
return utils.verifyNumberIsInteger(offset)
.then(function (offset) {
return contactManager.getHundredContacts(offset)
})
.then(function (rows) {
res.status(200).json(rows)
})
.catch(function (err) {
res.status(500).json(err.message)
})
})
/**
* Handles the route `GET /contacts/{id}`.
* Lists all of the details available about the contact with a given ID.
*/
router.get('/:contact_id', function (req, res, next) {
utils.verifyNumberIsInteger(req.params.contact_id)
.then(function (id) {
return contactManager.checkContactWithIDExists(id)
})
.then(function (id) {
return contactManager.getContactWithId(id)
}).then(function (user) {
res.status(200).json(user)
})
.catch(function (error) {
res.status(500).send(error.message)
})
})
/**
* Handles the route `POST /contacts/`.
* Inserts a new Contact into the database with the details specified in the request body.
*/
router.post('/', function (req, res, next) {
return contactManager.createContact(req.body.first_name, req.body.surname, req.body.email_address, req.body.phone_no, req.body.default_servicechain)
.then(function (newContactID) {
res.status(200).send("New contact: ID " + newContactID)
})
.catch(function (error) {
console.log(error)
res.status(500).end()
})
})
/**
* Handles the route `PUT /contacts/{id}`.
* Updates the details for the Contact with the specified ID with the details provided in the request body.
*/
router.put('/:contact_id', function (req, res, next) {
utils.verifyNumberIsInteger(req.params.contact_id)
.then(function (id) {
return contactManager.checkContactWithIDExists(id)
})
.then(function (id) {
return contactManager.updateContactDetailsWithId(id, req.body)
})
.then(function () {
res.status(200).end()
})
.catch(function () {
console.log(err)
res.status(500).send(err)
})
})
/**
* Handles the route `DELETE /contacts/{id}`.
* Removes the contact with the specified ID from the database.
* Returns 200 even if the contact does not exist, to ensure idempotence. This is why there is no validation that the contact exists first.
*/
router.delete('/:contact_id', function (req, res, next) {
utils.verifyNumberIsInteger(req.params.contact_id)
.then(function (contact_id) {
return contactManager.deleteContactFromDB(contact_id)
})
.then(function (resp) {
res.status(200).json(resp)
})
.catch(function (error) {
console.log(error.message)
res.status(500).end()
})
})
router.get('/:contact_id/messages', function(req,res,next){
//TODO: #11 - Make this work!
})
module.exports = router; | JavaScript | 0 | @@ -1666,17 +1666,21 @@
.phone_n
-o
+umber
, req.bo
@@ -1734,18 +1734,16 @@
wContact
-ID
) %7B%0A
@@ -1764,34 +1764,13 @@
00).
-send(%22New contact: ID %22 +
+json(
newC
@@ -1775,18 +1775,16 @@
wContact
-ID
)%0A %7D)
|
6669c784f1a5d5187ec5e57170655fb7f16ce06b | fix festivals | routes/festival.js | routes/festival.js | var express = require('express')
var router = express.Router()
var path = require('path')
var debug = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async = require('async')
var op = require('object-path')
var mapper = require('../helpers/mapper')
router.get('/:festival_id', function(req, res) {
debug('Loading "' + path.basename(__filename).replace('.js', '') + '"')
var festival = op.get(festivals, req.params.festival_id)
res.render('festival', {
'festival': festival
})
res.end()
})
function prepareFestivals(callback) {
var festivals = {}
async.each(SDC.get(['local_entities', 'by_class', 'festival']), function(festival_entity, callback) {
op.set(festivals, festival_entity.id, mapper.event(festival_entity.id))
// debug(JSON.stringify(event, null, 2))
async.each(SDC.get(['relationships', festival_entity.id, 'event']), function(eid, callback) {
var event = mapper.event(eid)
// debug(JSON.stringify(event, null, 2))
if(event['start-time']) {
var event_date = (event['start-time']).slice(0,10)
var event_time = (event['start-time']).slice(11,16)
op.push(festivals, [festival_entity.id, 'events', event_date, event_time], event)
}
callback()
}, function(err) {
if (err) {
debug('Failed to prepare festival ' + festival_entity.id, err)
callback(err)
return
}
// debug('Festival ' + festival_entity.id + ' prepared.')
callback()
})
}, function(err) {
if (err) {
debug('Failed to prepare festivals.', err)
callback(err)
return
}
// debug('Festivals prepared.' + JSON.stringify(festivals, null, 4))
callback()
})
}
router.prepare = function prepare(callback) {
// debug('Preparing ' + path.basename(__filename).replace('.js', ''))
var parallelf = []
parallelf.push(prepareFestivals)
async.parallel(parallelf, function(err) {
if (err) {
debug('Failed to prepare ' + path.basename(__filename).replace('.js', ''), err)
callback(err)
return
}
// debug('Prepared ' + path.basename(__filename).replace('.js', ''))
callback()
})
}
module.exports = router
| JavaScript | 0.026989 | @@ -286,16 +286,36 @@
pper')%0A%0A
+var festivals = %7B%7D%0A%0A
router.g
@@ -612,24 +612,27 @@
lback) %7B%0A
+ //
var festiva
|
1cd4b3368de2ea8b097c6987d421d1eda644e977 | update bkmlt | src/bookmarklet.js | src/bookmarklet.js | javascript:(function()%7Bfunction%20insertMissingScripts(e)%7Bfor(var%20o%3Ddocument.getElementsByTagName(%22script%22)%2Cr%3D%5B%5D%2Ct%3D0%3Bo.length%3Et%3Bt%2B%2B)o%5Bt%5D.src.match(RegExp(e))%3Fr.push(!0)%3Ar.push(!1)%3B-1%3D%3D%3Dr.indexOf(!0)%26%26appendScript(sources%5Be%5D)%7Dfunction%20appendScript(e)%7Bvar%20o%3Ddocument.createElement(%22script%22)%3Bo.src%3De%2Cdocument.head.appendChild(o)%7Dfor(var%20requestedBookmarklet%3Dwindow.prompt(%22Boom%3A%20Enter%20your%20Bookmarklet%5CnType%20help%20to%20see%20all%20available%20options%22)%2Csources%3D%7BbookmarkletsConfig%3A%22%2F%2Frawgit.com%2Faudibleblink%2Fboom%2Fajax-configs%2Flib%2FbookmarkletsConfig.js%22%2Cjquery%3A%22%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.9.0%2Fjquery.min.js%22%7D%2CsourceKeys%3DObject.keys(sources)%2Cx%3D0%3BsourceKeys.length%3Ex%3Bx%2B%2B)insertMissingScripts(sourceKeys%5Bx%5D)%3BsetTimeout(function%20Boom()%7Bvar%20e%3DCONFIG%2Co%3DObject.keys(e)%3Breturn%22help%22%3D%3D%3DrequestedBookmarklet%3Falert(%22The%20available%20bookmarklets%20for%20this%20version%20are%3A%5Cn%5Cn%22%2Bo.join(%22%5Cn%22))%3A-1!%3D%3D%24.inArray(requestedBookmarklet%2Co)%3Fwindow.location%3De%5BrequestedBookmarklet%5D%3Aalert(%22Bookmarklet%20not%20found%22)%2CBoom%7D%2C200)%3B%7D)()
| JavaScript | 0.000001 | @@ -33,581 +33,138 @@
n%2520
-insertMissingScripts(e)%257Bfor(var%2520o%253Ddocument.getElementsByTagName(%2522script%2522)%252Cr%253D%255B%255D%252Ct%253D0%253Bo.length%253Et%253Bt%252B%252B)o%255Bt%255D.src.match(RegExp(e))%253Fr.push(!0)%253Ar.push(!1)%253B-1%253D%253D%253Dr.indexOf(!0)%2526%2526appendScript(sources%255Be%255D)%257Dfunction%2520appendScript(e)%257Bvar%2520o%253Ddocument.createElement(%2522script%2522)%253Bo.src%253De%252Cdocument.head.appendChild(o)%257Dfor(var%2520requestedBookmarklet%253Dwindow.prompt(%2522Boom%253A%2520Enter%2520your%2520Bookmarklet%255CnType%2520help%2520to%2520see%2520all%2520available%2520options%2522)%252Csources%253D%257BbookmarkletsConfig%253A%2522%252F%252Frawgit.com%252F
+rawGitUrl(i%252Cr)%257Breturn%2522%252F%252Frawgit.com%252F%2522%252Bi%252B%2522%252Fboom%252F%2522%252Br%252B%2522%252Flib%252Fboom.js%2522%257Dvar%2520URL%253DrawGitUrl(%2522
audi
@@ -177,652 +177,117 @@
nk%252
-Fboom%252Fajax-configs%252Flib%252FbookmarkletsConfig.js%2522%252Cjquery%253A%2522%252F%252Fajax.googleapis.com%252Fajax%252Flibs%252Fjquery%252F1.9.0%252Fjquery.min.js%2522%257D%252CsourceKeys%253DObject.keys(sources)%252Cx%253D0%253BsourceKeys.length%253Ex%253Bx%252B%252B)insertMissingScripts(sourceKeys%255Bx%255D)%253BsetTimeout(function%2520Boom()%257Bvar%2520e%253DCONFIG%252Co%253DObject.keys(e)%253Breturn%2522help%2522%253D%253D%253DrequestedBookmarklet%253Falert(%2522The%2520available%2520bookmarklets%2520for%2520this%2520version%2520are%253A%255Cn%255Cn%2522%252Bo.join(%2522%255Cn%2522))%253A-1!%253D%253D%2524.inArray(requestedBookmarklet%252Co)%253Fwindow.location%253De%255BrequestedBookmarklet%255D%253Aalert(%2522Bookmarklet%2520not%2520found%2522)%252CBoom%257D%252C200
+2%252C%2522simplify%2522)%252Cjs%253Ddocument.createElement(%2522script%2522)%253Bjs.src%253DURL%252Cdocument.head.appendChild(js
)%253B
|
34afc564cd58142656773eb04626a001c9527024 | Update markdown.js | plugin/markdown/markdown.js | plugin/markdown/markdown.js | // From https://gist.github.com/1343518
// Modified by Hakim to handle Markdown indented with tabs
(function(){
if( typeof Showdown === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires Showdown to be loaded';
}
var stripLeadingWhitespace = function(section) {
var template = section.querySelector( 'script' );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
var leadingWs = text.match(/^\n?(\s*)/)[1].length,
leadingTabs = text.match(/^\n?(\t*)/)[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
}
return text;
};
var slidifyMarkdown = function(markdown, separator, vertical) {
separator = separator || '^\n---\n$';
var reSeparator = new RegExp(separator + (vertical ? '|' + vertical : ''), 'mg'),
reHorSeparator = new RegExp(separator),
matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [],
markdownSections = '';
// iterate until all blocks between separators are stacked up
while( matches = reSeparator.exec(markdown) ) {
// determine direction (horizontal by default)
isHorizontal = reHorSeparator.test(matches[0]);
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push([]);
}
// pluck slide content from markdown input
content = markdown.substring(lastIndex, matches.index);
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push(content);
} else {
// add to vertical stack
sectionStack[sectionStack.length-1].push(content);
}
lastIndex = reSeparator.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
(wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1]).push(markdown.substring(lastIndex));
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var k = 0, klen = sectionStack.length; k < klen; k++ ) {
markdownSections += typeof sectionStack[k] === 'string'
? '<section data-markdown>' + sectionStack[k] + '</section>'
: '<section><section data-markdown>' + sectionStack[k].join('</section><section data-markdown>') + '</section></section>';
}
return markdownSections;
};
var querySlidingMarkdown = function() {
var sections = document.querySelectorAll( '[data-markdown]'),
section;
for( var j = 0, jlen = sections.length; j < jlen; j++ ) {
section = sections[j];
if( section.getAttribute('data-markdown').length ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute('data-markdown');
xhr.onreadystatechange = function () {
if( xhr.readyState === 4 ) {
section.outerHTML = slidifyMarkdown( xhr.responseText, section.getAttribute('data-separator'), section.getAttribute('data-vertical') );
}
};
xhr.open('GET', url, false);
xhr.send();
} else if( section.getAttribute('data-separator') ) {
var markdown = stripLeadingWhitespace(section);
section.outerHTML = slidifyMarkdown( markdown, section.getAttribute('data-separator'), section.getAttribute('data-vertical') );
}
}
};
var queryMarkdownSlides = function() {
var sections = document.querySelectorAll( '[data-markdown]');
for( var j = 0, jlen = sections.length; j < jlen; j++ ) {
makeHtml(sections[j]);
}
};
var makeHtml = function(section) {
var notes = section.querySelector( 'aside.notes' );
var markdown = stripLeadingWhitespace(section);
section.innerHTML = (new Showdown.converter()).makeHtml(markdown);
if( notes ) {
section.appendChild( notes );
}
};
querySlidingMarkdown();
queryMarkdownSlides();
})();
| JavaScript | 0.000001 | @@ -875,32 +875,144 @@
n text;%0A%0A %7D;%0A
+ %0A var twrap = function(el) %7B%0A return '%3Cscript type=%22text/template%22%3E' + el + '%3C/script%3E';%0A %7D;%0A
%0A var slidify
@@ -2757,32 +2757,40 @@
ata-markdown%3E' +
+ twrap(
sectionStack%5Bk%5D
@@ -2789,16 +2789,19 @@
Stack%5Bk%5D
+ )
+ '%3C/se
@@ -2862,16 +2862,17 @@
down%3E' +
+
section
@@ -2880,16 +2880,27 @@
tack%5Bk%5D.
+map(twrap).
join('%3C/
|
9b25762a56afc587384ec420a724438b7015864c | remove js scroll as .focus() does the same | assets/js/basfoiy.js | assets/js/basfoiy.js | /**
*
* @author Ibrahim Naeem <mbting.9m@gmail.com>
*
**/
var api = null;
$(document).ready(function(){
thaanaKeyboard.defaultKeyboard='phonetic';
$("#followingBallsG").hide();
$("#basterm").focus();
//scroll to searchbox
$('html, body').animate({ scrollTop: $('#basterm').offset().top }, 'slow');
});
$.ajaxSetup({
headers: { 'BasToken': $("#basterm").data("token")}
});
$("#baslang").click(
function() {
var lang = $(this).text();
switch(lang) {
case "EN" :
$(this).addClass("dv").text("ހށ");
$("#basterm").addClass("dv").attr("placeholder","ބަހެއް ޖައްސަވާ").val('').focus();
thaanaKeyboard.setHandlerById("basterm","enable");
break;
case "ހށ" :
$(this).removeClass("dv").text("EN");
$("#basterm").removeClass("dv").attr("placeholder","Enter a word").val('').focus();
thaanaKeyboard.setHandlerById("basterm","disable");
break;
}
return false;
}
);
$("input").keyup(function(){
if ($(this).val() === '') {
$("#baslogo").removeClass("baslogosmall");
$("#bascontent").removeClass("bascontentsmall");
$("#basresults ul").fadeOut("slow",function(){
$(this).html("");
});
$("#basresults .baserror").hide();
if(api !== null) {
api.abort();
}
} else {
$("#baslogo").addClass("baslogosmall");
$("#bascontent").addClass("bascontentsmall");
if ($("#basterm").val() !== '') {
delay(function(){callWords();}, 500 );
}
}
});
$("#basform").submit(function(){
return false;
});
// ajax call
function callWords() {
$("#followingBallsG").show();
$("#basresults ul").html('');
var basdata = {"basterm":$("#basterm").val()};
api = $.post("search",basdata,function(data){
if (data.error === false){
$.each(data.result,function(key,row){
$("#basresults ul")
.hide()
.append('<li data-id="'+row.id+'" class="basword clear"><div class="basbox baseng"><a href="#">'+row.eng+'</a></div><div class="basbox basdv"><a href="#" class="dv">'+row.dhi+' <span class="bascontext">— '+row.latin+'</span></a></div></li>')
.fadeIn("slow",function(){});
});
} else {
$("#basresults ul")
.hide()
.html('<li class="basword clear"><div class="basbox baseng"><a href="#">Not found</a></div><div class="basbox basdv"><a href="#" class="dv">ނުފެނުނު</a></div></li>')
.fadeIn("slow",function(){});
}
$("#followingBallsG").hide();
}).error(function(){
if ($("#basterm").val() !== '') {
$("#basresults .baserror").fadeIn();
}
$("#followingBallsG").hide();
});
}
// delay actions
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
| JavaScript | 0.000001 | @@ -235,16 +235,18 @@
chbox %0A%09
+//
$('html,
|
0ecb07c08754029711a0b5fd9fb8f315827761a1 | Add explicit 'h' import | 1.0-hello-cycle/scripts/app.js | 1.0-hello-cycle/scripts/app.js | import Cycle from "@cycle/core";
import CycleWeb from "@cycle/web";
let {Rx} = Cycle;
let Observable = Rx.Observable;
// APP =============================================================================================
function Main({DOM}) {
let firstName$ = DOM.get("#first-name", "input")
.map(event => event.target.value)
.startWith("");
let lastName$ = DOM.get("#last-name", "input")
.map(event => event.target.value)
.startWith("");
return {
DOM: Observable.combineLatest(
firstName$, lastName$,
function (firstName, lastName) {
return (
<div>
<div className="form-group">
<label htmlFor="first-name">First Name:</label>
<input type="text" className="form-control" id="first-name" placeholder="First Name"/>
</div>
<div className="form-group">
<label htmlFor="last-name">Last Name:</label>
<input type="text" className="form-control" id="last-name" placeholder="Last Name"/>
</div>
<hr/>
<h3>Hello {firstName} {lastName}</h3>
</div>
);
})
};
}
Cycle.run(Main, {
DOM: CycleWeb.makeDOMDriver('#app'),
});
| JavaScript | 0.999998 | @@ -41,16 +41,21 @@
CycleWeb
+, %7Bh%7D
from %22@
|
06c2f294ff0e69ed3a99dcde09f56a0769463514 | Add support for IntersectionObserver | src/canvas-util.js | src/canvas-util.js | // Contains various canvas utility methods.
(function(exports) {
var CanvasUtil = {};
// Constructs a path on a <canvas>, given a Region.
CanvasUtil.pathFromRegion = function(ctx, region) {
region.iter_rectangles(function(x, y, width, height) {
ctx.rect(x, y, width, height);
});
};
// Workaround for browser bugs in drawImage when the source and
// destination <canvas> images are the same:
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=842110
// https://code.google.com/p/chromium/issues/detail?id=176714
CanvasUtil.copyArea = function(ctx, srcX, srcY, destX, destY, w, h) {
if (srcX + w < 0 || srcX > ctx.canvas.width)
return;
if (destX + w < 0 || destX > ctx.canvas.width)
return;
if (srcY + h < 0 || srcY > ctx.canvas.height)
return;
if (destY + h < 0 || destY > ctx.canvas.height)
return;
if (destX < 0) {
w += destX;
srcX -= destX;
destX = 0;
}
if (srcX < 0) {
destX -= srcX;
w += srcX;
srcX = 0;
}
if (destY < 0) {
h += destY;
srcY -= destY;
destY = 0;
}
if (srcY < 0) {
destY -= srcY;
h += srcY;
srcY = 0;
}
var mX = Math.max(srcX, destX);
if (mX >= ctx.canvas.width)
return;
if (mX + w > ctx.canvas.width)
w = ctx.canvas.width - mX;
var mY = Math.max(srcY, destY);
if (mY >= ctx.canvas.height)
return;
if (mY + h > ctx.canvas.height)
h = ctx.canvas.height - mY;
ctx.drawImage(ctx.canvas, srcX, srcY, w, h, destX, destY, w, h);
};
CanvasUtil.visibleRAF = function(elem, func, activateFunc) {
function isElemVisible(elem) {
var rect = elem.getBoundingClientRect();
if (rect.bottom < 0 || rect.top > window.innerHeight)
return false;
return true;
}
function update(t) {
func(t);
if (isRunning)
window.requestAnimationFrame(update);
}
function scrollHandler() {
setRunning(isElemVisible(elem));
}
var isRunning = false;
function setRunning(running) {
if (isRunning == running)
return;
isRunning = running;
if (activateFunc)
activateFunc(isRunning);
if (isRunning)
window.requestAnimationFrame(update);
}
document.addEventListener('scroll', scrollHandler);
scrollHandler();
};
exports.CanvasUtil = CanvasUtil;
})(window);
| JavaScript | 0 | @@ -1900,211 +1900,318 @@
-function isElemVisible(elem) %7B%0A var rect = elem.getBoundingClientRect();%0A if (rect.bottom %3C 0 %7C%7C rect.top %3E window.innerHeight)%0A return false;%0A return true
+let isRunning = false;%0A function setRunning(running) %7B%0A if (isRunning == running)%0A return;%0A%0A isRunning = running;%0A%0A if (activateFunc)%0A activateFunc(isRunning);%0A%0A if (isRunning)%0A window.requestAnimationFrame(update)
;%0A
@@ -2379,29 +2379,40 @@
unction
-scrollHandler
+visibleRAF_impl_onscroll
() %7B%0A
@@ -2420,27 +2420,25 @@
-setRunning(
+function
isElemVi
@@ -2448,18 +2448,18 @@
le(elem)
-);
+ %7B
%0A
@@ -2455,35 +2455,32 @@
) %7B%0A
-%7D%0A%0A
var isRunnin
@@ -2471,166 +2471,394 @@
-var isRunning = false;%0A function setRunning(running) %7B%0A if (isRunning == running)%0A return;%0A%0A isRunning = running;%0A
+const rect = elem.getBoundingClientRect();%0A if (rect.bottom %3C 0 %7C%7C rect.top %3E window.innerHeight)%0A return false;%0A return true;%0A %7D%0A%0A function scrollHandler() %7B%0A setRunning(isElemVisible(elem));%0A %7D%0A%0A document.addEventListener('scroll', scrollHandler);%0A scrollHandler();
%0A
@@ -2866,98 +2866,274 @@
+%7D%0A%0A
-if (activateFunc)%0A activateFunc(isRunning);%0A%0A if (is
+ function visibleRAF_impl_IntersectionObserver() %7B%0A function callback(entries) %7B%0A const %7B intersectionRatio %7D = entries%5B0%5D;%0A const shouldBeRunning = intersectionRatio %3E 0;%0A setRunning(shouldBe
Running)
%0A
@@ -3120,33 +3120,35 @@
shouldBeRunning)
-%0A
+;%0A
@@ -3145,120 +3145,214 @@
+ %7D%0A%0A
-window.requestAnimationFrame(update);%0A %7D%0A%0A document.addEventListener('scroll', scrollHandl
+ const observer = new IntersectionObserver(callback);%0A observer.observe(elem);%0A %7D%0A%0A if (window.IntersectionObserver)%0A visibleRAF_impl_IntersectionObserv
er
+(
);%0A
@@ -3354,37 +3354,65 @@
();%0A
-scrollHandler
+else%0A visibleRAF_impl_onscroll
();%0A %7D;%0A%0A
|
762d5706c02ae12d2970bdee537ce69fb89cf935 | Remove signatures-api | assets/js/helpers.js | assets/js/helpers.js | export function getHostName(url) {
var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) {
return match[2];
}
else {
return null;
}
}
export function openPopup(url, title='popup', w=600, h=500) {
// Fixes dual-screen position
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
var left = ((width / 2) - (w / 2)) + dualScreenLeft;
var top = ((height / 2) - (h / 2)) + dualScreenTop;
var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
}
export function createMetaTags(tags={}) {
const meta = {}
tags = Object.assign({
'author': 'Fight for the Future',
'og:description': tags.description,
'og:image': tags.image,
'og:site_name': 'Battle for the Net',
'og:title': tags.title,
'og:type': 'website',
'og:url': tags.url,
'twitter:card': 'summary_large_image',
'twitter:description': tags.description,
'twitter:image': tags.image,
'twitter:site': '@FightForTheFtr',
'twitter:title': tags.title,
'twitter:url': tags.url
}, tags)
const fakeTagNames = ['title', 'image', 'url']
for (let key of Object.keys(tags)) {
if (key.match(/^og\:/)) {
meta[key] = {
hid: key,
property: key,
content: tags[key]
}
}
else if (!fakeTagNames.includes(key)) {
meta[key] = {
hid: key,
name: key,
content: tags[key]
}
}
}
return Object.values(meta)
}
export function postFormData(url, data={}) {
const axios = require('axios')
const qs = require('qs')
return axios.post(url, qs.stringify(data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
export function sendToMothership(data={}, submission={}) {
const member = data.member || {}
logSubmission(Object.assign({
name: member.first_name,
email: member.email,
zip_code: member.postcode,
phone: member.phone_number,
address: member.street_address,
comments: data.action_comment,
petition_id: data.an_petition_id,
org: data.org
}, submission))
return postFormData('https://queue.fightforthefuture.org/action', data)
}
export function getDonateLink(org) {
switch (org) {
case 'fp':
return "https://freepress.actionkit.com/donate/single/"
case "dp":
return "https://secure.actblue.com/donate/nndayofaction?refcode=20170712-bftn"
case "fftf":
default:
return "https://donate.fightforthefuture.org"
}
}
export async function geocodeState() {
const axios = require('axios')
const state = {
name: null,
code: null
}
try {
const response = await axios.get('https://fftf-geocoder.herokuapp.com')
const geo = response.data
if (
geo.country.iso_code === 'US' &&
geo.subdivisions &&
geo.subdivisions[0] &&
geo.subdivisions[0].names &&
geo.subdivisions[0].names.en
) {
state.name = geo.subdivisions[0].names.en
state.code = geo.subdivisions[0].iso_code
}
}
catch (err) {
console.error(err)
}
return state
}
/**
* Smooth scroll animation
* @param {int} endX: destination x coordinate
* @param {int) endY: destination y coordinate
* @param {int} duration: animation duration in ms
*/
export function smoothScrollTo(endX, endY, duration) {
var startX = window.scrollX || window.pageXOffset,
startY = window.scrollY || window.pageYOffset,
distanceX = endX - startX,
distanceY = endY - startY,
startTime = new Date().getTime();
duration = typeof duration !== 'undefined' ? duration : 400;
// Easing function
var easeInOutQuart = function(time, from, distance, duration) {
if ((time /= duration / 2) < 1) return distance / 2 * time * time * time * time + from;
return -distance / 2 * ((time -= 2) * time * time * time - 2) + from;
};
var timer = window.setInterval(function() {
var time = new Date().getTime() - startTime,
newX = easeInOutQuart(time, startX, distanceX, duration),
newY = easeInOutQuart(time, startY, distanceY, duration);
if (time >= duration) {
window.clearInterval(timer);
}
window.scrollTo(newX, newY);
}, 1000 / 60); // 60 fps
};
export function smoothScrollToElement(el, duration) {
duration = typeof duration !== 'undefined' ? duration : 500;
el = typeof el === 'string' ? document.querySelector(el) : el;
if (el) {
smoothScrollTo(el.offsetLeft, el.offsetTop, duration)
}
}
export async function startTextFlow({ flow, phone }) {
const axios = require('axios')
try {
const { data } = await axios.post('https://utdy3yxx7l.execute-api.us-east-1.amazonaws.com/v1/flow-starts', {
flow: flow,
phone: phone
})
return data
}
catch (error) {
return {}
}
}
export async function logSubmission(params) {
const axios = require('axios')
try {
await axios.post('https://signatures-api.herokuapp.com/signatures', params)
}
catch (error) {
//
}
}
export async function pingCounter(counter) {
const axios = require('axios')
try {
await axios.post(`https://counter.battleforthenet.com/ping/${counter}`)
}
catch (error) {
//
}
}
export function formatNumber(x) {
return x || x === 0 ? x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '';
}
| JavaScript | 0.000215 | @@ -2380,339 +2380,8 @@
) %7B%0A
- const member = data.member %7C%7C %7B%7D%0A%0A logSubmission(Object.assign(%7B%0A name: member.first_name,%0A email: member.email,%0A zip_code: member.postcode,%0A phone: member.phone_number,%0A address: member.street_address,%0A comments: data.action_comment,%0A petition_id: data.an_petition_id,%0A org: data.org%0A %7D, submission))%0A%0A
re
@@ -5061,212 +5061,8 @@
%0A%7D%0A%0A
-export async function logSubmission(params) %7B%0A const axios = require('axios')%0A%0A try %7B%0A await axios.post('https://signatures-api.herokuapp.com/signatures', params)%0A %7D%0A catch (error) %7B%0A //%0A %7D%0A%7D%0A%0A
expo
|
fffb7f14b374db456c6fbad42d7328cf64b4aef9 | Add a default page title when one is not found | assets/js/modules/search-console/dashboard/dashboard-widget-sitestats.js | assets/js/modules/search-console/dashboard/dashboard-widget-sitestats.js | /**
* SearchConsoleDashboardWidgetSiteStats component.
*
* Site Kit by Google, Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
/**
* External dependencies
*/
import withData from 'GoogleComponents/higherorder/withdata';
import { TYPE_MODULES } from 'GoogleComponents/data';
import GoogleChart from 'GoogleComponents/google-chart.js';
import PreviewBlock from 'GoogleComponents/preview-block';
import { decodeHtmlEntity, getTimeInSeconds } from 'GoogleUtil';
/**
* Internal dependencies
*/
import { extractSearchConsoleDashboardData } from './util';
/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { Component } from '@wordpress/element';
class SearchConsoleDashboardWidgetSiteStats extends Component {
constructor( props ) {
super( props );
this.setOptions = this.setOptions.bind( this );
}
setOptions() {
const { selectedStats, series, vAxes } = this.props;
const pageTitle = googlesitekit.pageTitle && googlesitekit.pageTitle.length ? sprintf( __( 'Search Traffic Summary for %s', 'google-site-kit' ), decodeHtmlEntity( googlesitekit.pageTitle ) ) : '';
const options = {
chart: {
title: pageTitle,
},
curveType: 'line',
height: 270,
width: '100%',
chartArea: {
height: '80%',
width: '87%',
},
legend: {
position: 'top',
textStyle: {
color: '#616161',
fontSize: 12,
},
},
hAxis: {
format: 'M/d/yy',
gridlines: {
color: '#fff',
},
textStyle: {
color: '#616161',
fontSize: 12,
},
},
vAxis: {
gridlines: {
color: '#eee',
},
minorGridlines: {
color: '#eee',
},
textStyle: {
color: '#616161',
fontSize: 12,
},
titleTextStyle: {
color: '#616161',
fontSize: 12,
italic: false,
},
},
};
options.series = series;
options.vAxes = vAxes;
// Clean up chart if more than three stats are selected.
if ( 3 <= selectedStats.length ) {
options.vAxis.textPosition = 'none';
options.vAxis.gridlines.color = '#fff';
options.vAxis.minorGridlines.color = '#fff';
options.vAxes = {};
options.chartArea.width = '98%';
}
return options;
}
render() {
const { data, selectedStats } = this.props;
if ( ! data || ! data.length ) {
return null;
}
const options = this.setOptions();
const processedData = extractSearchConsoleDashboardData( data );
return (
<section className="mdc-layout-grid">
<div className="mdc-layout-grid__inner">
<div className="mdc-layout-grid__cell mdc-layout-grid__cell--span-12">
<GoogleChart
selectedStats={ selectedStats }
data={ processedData.dataMap }
options={ options }
singleStat={ false }
/>
</div>
</div>
</section>
);
}
}
export default withData(
SearchConsoleDashboardWidgetSiteStats,
[
{
type: TYPE_MODULES,
identifier: 'search-console',
datapoint: 'searchanalytics',
data: {
dimensions: 'date',
compareDateRanges: true,
},
priority: 1,
maxAge: getTimeInSeconds( 'day' ),
context: 'Single',
},
],
<PreviewBlock width="100%" height="270px" padding />,
{ createGrid: true }
);
| JavaScript | 0 | @@ -1655,10 +1655,57 @@
) :
-''
+__( 'Search Traffic Summary', 'google-site-kit' )
;%0A%0A%09
|
971258ef88c7936cd02138016634d9e837081dce | add user edit routes | back/routes/index.js | back/routes/index.js | /**
* @file Routes file.
*/
const express = require('express');
const router = express.Router();
const passport = require('passport');
const indexCtrl = require('../controllers/index.ctrl');
const userCtrl = require('../controllers/user.ctrl');
const coursesCtrl = require('../controllers/courses.ctrl');
const authMidd = require('../middleware/auth.midd');
router.get('/', indexCtrl.getIndex);
router.get('/join', userCtrl.getRegister);
router.post('/register', userCtrl.register);
router.get('/login', userCtrl.getLogin);
// @see https://github.com/jaredhanson/passport/issues/482
router.post('/login', [
passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }),
authMidd.check,
]);
router.get('/logout', [
userCtrl.logout,
authMidd.check,
]);
router.get('/new', [authMidd.authOnly, coursesCtrl.getCreate]);
router.post('/new', [authMidd.authOnly, coursesCtrl.create]);
router.get('/:username', coursesCtrl.getOwnCourses);
router.get('/:username/:courseSlug', coursesCtrl.getCourse);
router.post('/:username/:courseSlug', coursesCtrl.sectionNew);
router.get('/:username/:courseSlug/new', [authMidd.authOnly, coursesCtrl.getNewSection]);
router.get('/:username/:courseSlug/:sectionSlug', coursesCtrl.getSection);
module.exports = router;
| JavaScript | 0.000001 | @@ -961,16 +961,111 @@
ourses);
+%0Arouter.get('/:username/edit', userCtrl.edit);%0Arouter.post('/:username/edit', userCtrl.update);
%0A%0Arouter
|
634c97cb87c4582137e361b0f8540939100c3b17 | Fix io_progress init | client/common/init/io_progress.js | client/common/init/io_progress.js | 'use strict';
/**
* client
**/
/**
* client.common
**/
/**
* client.common.init
**/
/*global $, nodeca*/
var timeout;
var $notice;
function hide() {
clearTimeout(timeout);
$notice.hide();
}
function init() {
if (!$notice) {
$notice = $(nodeca.client.common.render.template('common.io_progress'));
$notice.appendTo('body').find('.close').click(hide);
hide();
}
}
function show() {
// make sure previous timeout was cleared
clearTimeout(timeout);
// schedule showing new message in next 500 ms
timeout = setTimeout(function () {
init();
$notice.show();
}, 500);
}
/**
* client.common.init.io_progress()
*
* Assigns rpc before/after request handlers showing/hiding "loading" notice.
*
*
* ##### Example
*
* nodeca.client.common.init.io_progress();
**/
module.exports = function () {
nodeca.io.on('rpc.request', show);
nodeca.io.on('rpc.complete', hide);
};
| JavaScript | 0.001019 | @@ -221,16 +221,86 @@
ion
-init() %7B
+show() %7B%0A // make sure previous timeout was cleared%0A clearTimeout(timeout);%0A
%0A i
@@ -467,99 +467,8 @@
%0A %7D
-%0A%7D%0A%0A%0Afunction show() %7B%0A // make sure previous timeout was cleared%0A clearTimeout(timeout);
%0A%0A
@@ -514,16 +514,16 @@
500 ms%0A
+
timeou
@@ -555,20 +555,8 @@
) %7B%0A
- init();%0A
|
dc1583817f5742e37d3d6004438ccc5132dd3256 | remove confirm dialog fix | client/models/document.service.js | client/models/document.service.js | 'use strict';
(function () {
class DocumentService {
constructor(Document, $q, lodash, $mdDialog) {
this.$mdDialog = $mdDialog
this.lodash = lodash
this.$q = $q
this.Document = Document
this.collection = []
}
getCollection() {
return this.Document.query().$promise.then((response) => {
angular.copy(response, this.collection);
return this.collection;
});
}
save(data) {
let action = data._id? 'update' : 'save';
angular.extend(data, {id: data._id});
return this.Document[action](data).$promise.then((response) => {
if(action == 'save'){
this.collection.push(response);
}
return response;
});
}
remove(data) {
let confirm = this.$mdDialog.confirm()
.title('Would you like to delete your documens?')
.ok('YES')
.cancel('NO');
return this.$mdDialog.show(confirm).then(() => {
let prom = [];
if (angular.isArray(data)) {
angular.forEach(data, (el)=> {
prom.push(this.removeOneElement(el));
});
} else {
prom.push(this.removeOneElement(data));
}
return this.$q.all(prom).then(function (response) {
return response;
})
});
}
removeOneElement(data) {
angular.extend(data, {id: data._id});
return this.Document.remove(data).$promise.then((response) => {
this.lodash.remove(this.collection, {_id: data._id});
return response;
});
}
}
angular.module('jagenApp')
.service('DocumentService', DocumentService);
})();
| JavaScript | 0 | @@ -747,32 +747,116 @@
remove(data) %7B%0A
+ if(this.lodash.isEmpty(data))%7B%0A return this.$q.reject(false);%0A %7D%0A%0A
let confir
|
9658f68276a7a39a85e6ea40829c6ecf7e8c998e | Change active command icon | client/src/components/transfer.js | client/src/components/transfer.js | import React, { PureComponent } from 'react'
import { PropTypes } from 'prop-types'
import 'font-awesome-webpack'
import classNames from 'classnames/bind'
import Indicator from './indicator'
import styles from '../styles/core.scss'
import { humanBytes, percentage } from '../lib/utils'
import * as constant from '../lib/const'
const cx = classNames.bind(styles)
export default class Transfers extends PureComponent {
static propTypes = {
store: PropTypes.object.isRequired,
}
// this is a dirty trick to play around the fact that react-router is kind of dumb when it comes to
// redux like scenarios: https://reacttraining.com/react-router/web/guides/redux-integration
componentDidMount() {
const { actions } = this.props.store
actions.getConfig()
}
render() {
const { state } = this.props.store
if (
!(
state.core &&
state.core.operation &&
(state.core.operation.opKind === constant.OP_SCATTER_MOVE ||
state.core.operation.opKind === constant.OP_SCATTER_COPY ||
state.core.operation.opKind === constant.OP_GATHER_MOVE)
)
) {
return (
<section className={cx('row', 'bottom-spacer-half')}>
<div className={cx('col-xs-12')}>
<span>No transfer operation is currently on going.</span>
</div>
</section>
)
}
const operation = state.core.operation
const completed = parseFloat(Math.round(operation.completed * 100) / 100).toFixed(2)
const speed = parseFloat(Math.round(operation.speed * 100) / 100).toFixed(2)
const transferred = `${humanBytes(operation.bytesTransferred + operation.deltaTransfer)} / ${humanBytes(
operation.bytesToTransfer,
)}`
const remaining = operation.remaining
console.log(`line(${operation.line})`)
const rows = operation.commands.map(command => {
let status
// console.log(`line(${operation.line})-commandxfer(${command.transferred})-commandxfer(${command.size})`)
if (command.transferred === 0) {
status = <i className={cx('fa fa-minus-circle', 'statusPending', 'rspacer')} />
} else if (command.transferred === command.size) {
status = <i className={cx('fa fa-check-circle', 'statusDone', 'rspacer')} />
} else {
status = <i className={cx('fa fa-bullseye', 'statusInProgress', 'rspacer')} />
}
const percent = percentage(command.transferred / command.size)
return (
<tr key={command.entry}>
<td>{status}</td>
<td>{command.src}</td>
<td>
rsync {operation.rsyncStrFlags} "{command.entry}" "{command.dst}"
</td>
<td>
<div className={cx('progress')}>
<span style={{ width: percent }} />
</div>
</td>
</tr>
)
})
const grid = (
<section className={cx('row', 'bottom-spacer-half')}>
<div className={cx('col-xs-12')}>
<table>
<thead>
<tr>
<th style={{ width: '50px' }} />
<th style={{ width: '95px' }}>SOURCE</th>
<th>COMMAND</th>
<th>PROGRESS</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
</section>
)
return (
<div>
<section className={cx('row', 'bottom-spacer-half')}>
<div className={cx('col-xs-3')}>
<Indicator label="Completed" value={completed} unit=" %" />
</div>
<div className={cx('col-xs-3')}>
<Indicator label="Speed" value={speed} unit=" MB/s" />
</div>
<div className={cx('col-xs-3')}>
<Indicator label="Transferred / Total" value={transferred} unit="" />
</div>
<div className={cx('col-xs-3')}>
<Indicator label="Remaining" value={remaining} unit="" />
</div>
</section>
<section className={cx('row', 'bottom-spacer-half')}>
<div className={cx('col-xs-12')}>
<span>{operation.line}</span>
</div>
</section>
{grid}
</div>
)
}
}
| JavaScript | 0 | @@ -2204,16 +2204,30 @@
fa-
-bullseye
+circle-o-notch fa-spin
', '
|
07b55fa1e6c40d982d615ce4c501ee6e0c81bf49 | Exit if unable to create ninja. | client.js | client.js | var
fs = require('fs')
, path = require('path')
, util = require('util')
, events = require('events')
, argv = require(path.resolve(__dirname, 'app', 'argv'))
, client = require(path.resolve(__dirname, 'app', 'client'))
, config = require(path.resolve(__dirname, 'app', 'config'))
, logger = require(path.resolve(__dirname, 'lib', 'logger'))
, app = new events.EventEmitter()
, log = new logger(argv)
, creds = {}
;
logger.default = log;
app.log = log;
app.on('error', function(err) {
log.error(err);
/**
* Do more stuff with errors.
* err should include .stack,
* which we could pipe to the cloud
* at some point, it would be useful!
*/
});
var ninja = new client(argv, creds, app);
config(ninja, app);
/**
* Note about apps (event emitters):
*
* We can instantiate multiple apps to
* allow our modules to be namespaced/sandboxed
* if we so desire. This allows us to provide
* isolation without any additional infrastructure
*/
| JavaScript | 0 | @@ -707,16 +707,124 @@
app);%0A%0A
+if((!ninja) %7C%7C !ninja.credentials.id) %7B%0A%0A%09log.error(%22Unable to create ninja client.%22);%0A%09process.exit(1);%0A%7D%0A%0A
config(n
|
58caa3a5019dd48fc01f3360b8327cd9aa55db6b | set title of song on load | client.js | client.js | var search = require('youtube-search')
var ytdl = require('ytdl-core')
var request = require('browser-request')
var ytApiKey = require('./yt_api_key')
var log = function (txt) {
var stdout = document.getElementById('stdout')
if (stdout) {
stdout.innerHTML += txt + '\n'
}
console.log(txt)
}
function showIcon(name) {
document.getElementById('icon_listen').style.display = 'none'
document.getElementById('icon_pause').style.display = 'none'
document.getElementById('icon_play').style.display = 'none'
document.getElementById('icon_stop').style.display = 'none'
document.getElementById('icon_listening').style.display = 'none'
document.getElementById('icon_listen').style.display = 'none'
document.getElementById('icon_working').style.display = 'none'
document.getElementById('icon_' + name).style.display = 'inline-block'
return document.getElementById('icon_' + name)
}
function startListening() {
if (!('webkitSpeechRecognition' in window)) {
log('no speech api support')
} else {
log('begin')
showIcon('listening')
var done = false
var recognition = new webkitSpeechRecognition()
recognition.continuous = true
recognition.interimResults = false
recognition.onstart = function () {
log('start')
}
recognition.onresult = function (event) {
if (done) {
return
}
// console.log(event)
// log(event.results.length)
// log(event.toString())
for (var i = event.resultIndex; i < event.results.length; i++) {
var result = event.results[i]
if (result.isFinal) {
recognition.stop()
showIcon('working')
done = true
var alt = result[0]
// console.log(alt)
result = alt.transcript.trim()
log(result)
search(result, {maxResults: 3, key: ytApiKey}, function (err, videos) {
if (err) {
console.error(err)
} else {
videos = videos.filter(function (video) {
return (video.kind === 'youtube#video')
})
var link = videos[0].link
var encodedUrl = encodeURIComponent(link)
request.get('/audio/' + encodedUrl, function (err, res, body) {
if (err) {
console.error(err)
return
}
var audio = document.getElementById('playback')
audio.src = body
audio.addEventListener('ended', endPlayback)
// TODO: do we actually need this?
setTimeout(function() {
audio.play()
showIcon('stop')
}, 3000)
})
}
})
}
}
}
recognition.onerror = function (err) {
log('err')
log(err.toString())
console.error(err)
showIcon('listen')
}
recognition.onend = function () {
log('end')
}
recognition.lang = 'en-US'
// recognition.lang = 'de'
recognition.start()
}
}
function endPlayback() {
var playback = document.getElementById('playback')
playback.pause()
playback.currentTime = 0
showIcon('listen')
}
window.onload = function () {
showIcon('listen')
document.getElementById('icon_stop').onclick = endPlayback
document.getElementById('icon_listen').onclick = startListening
}
| JavaScript | 0.000001 | @@ -1051,22 +1051,20 @@
owIcon('
-listen
+work
ing')%0A
@@ -1266,16 +1266,44 @@
start')%0A
+ showIcon('listening')%0A
%7D%0A
@@ -2206,24 +2206,100 @@
nent(link)%0A%0A
+ document.getElementById('title').innerHTML = videos%5B0%5D.title%0A%0A
@@ -2629,16 +2629,100 @@
layback)
+%0A audio.addEventListener('playing', function () %7B showIcon('stop') %7D)
%0A%0A
@@ -2841,43 +2841,8 @@
y()%0A
- showIcon('stop')%0A
|
dfc8d91dbb9f0b3dbe77b6fb6cf188b81786ed0f | Update custom_funct.js | leaflet/JS-CSS/custom_funct.js | leaflet/JS-CSS/custom_funct.js | function leaflet_alert() {
alert("Clicking OK the user takes full responsibility of using this map.");
}
| JavaScript | 0.000001 | @@ -102,8 +102,195 @@
p.%22);%0A%7D%0A
+%0Afunction leaflet_alert2() %7B%0A var txt;%0A var r = confirm(%22Clicking OK the user takes full responsibility of using this map.%22);%0A if (r != true) %7B%0A txt = %22You pressed Cancel%22;%0A %7D%0A%7D%0A
|
4d55cd6fe8f1f12818539819a3768c9905bd8ecf | Improve test on post rendering function. | example/app/js/main.js | example/app/js/main.js | var domains = {
"DO_ENTIER": {
"type": "number",
"validation": [{
"type": "number"
}],
},
"DO_DATE": {
"type": "date"
},
"DO_TEXTE_50": {
"type": "text",
"validation": [{
"type": "string",
"options": {
"maxLength": 50
}
}],
"style": ["cssClassDomain1", "cssClassDomain2"],
"decorator": "testHelper"
},
"DO_LISTE": {
"type": "number",
},
"DO_ID": {
"type": "text"
},
"DO_TEXTE_30": {
"type": "text",
"validation": [{
"type": "string",
"options": {
"maxLength": 30
}
}]
},
"DO_EMAIL": {
"type": "email",
"validation": [{
"type": "email"
}, {
"type": "string",
"options": {
"minLength": 4
}
}]
},
"DO_BOOLEEN":{
"type": "boolean"
},
"DO_DEVISE":{
"type": "number",
"validation":{
"type": "number",
"options":{"min": 0}
},
"formatter": "devise"
}
};
Fmk.initialize({domains: domains, metadatas: {}});
var TestView = Fmk.Views.CoreView.extend({
metadatas:{
firstName: "DO_TEXTE_50",
template: function(){ return "<p>Test template!!!</p>"}
}
});
var view = new TestView({model :new Fmk.Models.Model({firstName: "Jon", lastName: "Jiap"})});
console.log(view.render().el);
jQuery.fn.test = function() {
console.log('JQURY PLUGIN TEST');
this.each(function() {
$(this).css("background-color", "#ff00ff");
});
return this;
}
Fmk.Helpers.postRenderingHelper.registerHelper({name: "testHelper", fn: jQuery.fn.test}) | JavaScript | 0 | @@ -1,12 +1,38 @@
+/*global Fmk, jQuery, $*/%0A
var domains
@@ -1051,290 +1051,8 @@
%7D);%0A
-var TestView = Fmk.Views.CoreView.extend(%7B%0A metadatas:%7B%0A firstName: %22DO_TEXTE_50%22,%0A template: function()%7B return %22%3Cp%3ETest template!!!%3C/p%3E%22%7D%0A %7D%0A%0A%7D);%0Avar view = new TestView(%7Bmodel :new Fmk.Models.Model(%7BfirstName: %22Jon%22, lastName: %22Jiap%22%7D)%7D);%0Aconsole.log(view.render().el);%0A%0A
jQue
@@ -1220,16 +1220,17 @@
this;%0A%7D
+;
%0A%0AFmk.He
@@ -1299,20 +1299,411 @@
fn:
-jQuery.fn.test%7D)
+%22test%22%7D);%0Avar TestModel = Fmk.Models.Model.extend(%7B%0A modelName: %22test%22,%0A metadatas:%7B%0A firstName: %7Bdomain: %22DO_TEXTE_50%22, decorator: %22testHelper%22%7D%0A %7D%0A%7D);%0Avar TestView = Fmk.Views.CoreView.extend(%7B%0A template: function()%7B return %22%3Cp data-name='firstName'%3ETest template!!!%3C/p%3E%22;%7D%0A%7D);%0Avar view = new TestView(%7Bmodel :new TestModel(%7BfirstName: %22Jon%22, lastName: %22Jiap%22%7D)%7D);%0Aconsole.log(view.render().el);%0A%0A
|
c95568b4492c97f1bcf850acd0d568c6d95a3405 | Update character | commit.js | commit.js | var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
var inFile = process.argv[ 2 ]
var outFile = process.argv[ 3 ]
if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
var outFD = fs.openSync(outFile, 'w')
fs.readFile(inFile, function(err,data) {
var length = data.length
console.info("Bytes: %s", length)
try {
child_process.execFileSync('/usr/bin/git', ['add', outFile])
} catch (e) {
console.error("Couldn't add %s to git: %s", outFile, e)
}
var args = ['commit', outFile, '-m', 'Update character']
for (var counter = 0; counter < length; counter++)
{
fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
sleep(Math.random() * max_sleep)
child_process.execFileSync('/usr/bin/git', args)
}
})
}
function sleep(seconds) {
var endTime = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= endTime) {;}
}
| JavaScript | 0 | @@ -1097,12 +1097,13 @@
ime) %7B;%7D%0A%7D%0A%0A
+p
|
ad49d9fd344c41045baa8dddcd15c3b5a446b15d | Update character | commit.js | commit.js | var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
var inFile = process.argv[ 2 ]
var outFile = process.argv[ 3 ]
if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
var outFD = fs.openSync(outFile, 'w')
fs.readFile(inFile, function(err,data) {
var length = data.length
console.info("Bytes: %s", length)
try {
child_process.execFileSync('/usr/bin/git', ['add', outFile])
} catch (e) {
console.error("Couldn't add %s to git: %s", outFile, e)
}
var args = ['commit', outFile, '-m', 'Update character']
for (var counter = 0; counter < length; counter++)
{
fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
sleep(Math.r | JavaScript | 0 | @@ -879,8 +879,9 @@
p(Math.r
+a
|
05c8516f2ba3ce7042edaa2b8bc27508ab62b54b | Update character | commit.js | commit.js | var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
var inFile = process.argv[ 2 ]
var outFile = process.argv[ 3 ]
if (process.argv | JavaScript | 0 | @@ -217,8 +217,9 @@
ss.argv
+%5B
|
22b0ee5a329d867ad2cc0d96dac64a76fb0d35ae | Commit all the required changes | commit.js | commit.js | var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support
var commit_messages = [
"Fixing an important issue with the universe.",
"Someone poisoned the waterhole!",
"You feeling lucky punk?",
"Five bullets or six?",
"Fixed memory parsing error #1337",
"Cleaned out the intertubes",
"AAAAAAAAAAARGH!",
"Fixed a typo",
"Updated the readme",
"Fixing a typo added in the last readme update",
"GET A HAIRCUT!",
"Updated the readme again",
"Found an issue with the letter 'a', so I fixed it.",
"Incompatible dimensions found, Cthuhlu Error 666",
"Who you calling a fool?",
"How many more of these can I make?",
"Fixing an error introduced in the last commit",
"Re-updating the readme.",
"Work in Progress",
"WIP",
"Quick fix",
"Grammar fix",
"Fixing punctuation",
"Correcting style",
"Logic error",
"Almost there",
"Nearly got it",
"Not quite working",
"Ooops!",
"Did I do that?",
"Commit all the required changes",
"Really commit all the required changes",
"Should work now",
"Back out the last commit",
"Reverting changes",
"One more time...",
"Re-commiting last",
"One more User Story done",
"Can work my way through the Kanban",
"Sprint complete",
"Well that seemed pretty easy",
"What do you mean you can't pack up the commit?",
"Merge in master",
"Fast-forwarding changes"
]
if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
var inFile = process.argv[ 2 ]
var outFile = process.argv[ 3 ]
if (inFile == outFile) {
console.error("Aborted: infile and outfile must be different")
return(-1);
}
if (process.argv [ 4 ]) max_sleep = process.argv [ | JavaScript | 0.998322 | @@ -1834,20 +1834,21 @@
eep = process.argv %5B
+
|
c11ab3c9b874a0ec17fb89a7576db110b0e0c8b4 | Fixing punctuation | commit.js | commit.js | var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support
var commit_messages = [
"Fixing an important issue with the universe.",
"Someone poisoned the waterhole!",
"You feeling lucky punk?",
"Five bullets or six?",
"Fixed memory parsing error #1337",
"Cleaned out the intertubes",
"AAAAAAAAAAARGH!",
"Fixed a typo",
"Updated the readme",
"Fixing a typo added in the last readme update",
"GET A HAIRCUT!",
"Updated the readme again",
"Found an issue with the letter 'a', so I fixed it.",
"Incompatible dimensions found, Cthuhlu Error 666",
"Who you calling a fool?",
"How many more of these can I make?",
"Fixing an error introduced in the last commit",
"Re-updating the readme.",
"Work in Progress",
"WIP",
"Quick fix",
"Grammar fix",
"Fixing punctuation",
"Correcting style",
"Logic error",
"Almost there",
"Nearly got it",
"Not quite working",
"Ooops!",
"Did I do that?",
"Commit all the required changes",
"Really commit all the required changes",
"Should work now",
"Back out the last commit",
"Reverting changes",
"One more time...",
"Re-commiting last",
"One more User Story done",
"Can work my way through the Kanban",
"Sprint complete",
"Well that seemed pretty easy",
"What do you mean you can't pack up the commit?",
"Merge in master | JavaScript | 0.999999 | @@ -1531,8 +1531,9 @@
n master
+%22
|
3bac7acb489b801e0d48905a0176f81eb86492b8 | Use the tile coordinate as a pseudo URL | examples/geojson-vt.js | examples/geojson-vt.js | import GeoJSON from '../src/ol/format/GeoJSON.js';
import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import Projection from '../src/ol/proj/Projection.js';
import VectorTileSource from '../src/ol/source/VectorTile.js';
import View from '../src/ol/View.js';
import {
Tile as TileLayer,
VectorTile as VectorTileLayer,
} from '../src/ol/layer.js';
// Converts geojson-vt data to GeoJSON
const replacer = function (key, value) {
if (value.geometry) {
let type;
const rawType = value.type;
let geometry = value.geometry;
if (rawType === 1) {
type = 'MultiPoint';
if (geometry.length == 1) {
type = 'Point';
geometry = geometry[0];
}
} else if (rawType === 2) {
type = 'MultiLineString';
if (geometry.length == 1) {
type = 'LineString';
geometry = geometry[0];
}
} else if (rawType === 3) {
type = 'Polygon';
if (geometry.length > 1) {
type = 'MultiPolygon';
geometry = [geometry];
}
}
return {
'type': 'Feature',
'geometry': {
'type': type,
'coordinates': geometry,
},
'properties': value.tags,
};
} else {
return value;
}
};
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const url = 'data/geojson/countries.geojson';
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (json) {
const tileIndex = geojsonvt(json, {
extent: 4096,
debug: 1,
});
const vectorSource = new VectorTileSource({
format: new GeoJSON({
// Data returned from geojson-vt is in tile pixel units
dataProjection: new Projection({
code: 'TILE_PIXELS',
units: 'tile-pixels',
extent: [0, 0, 4096, 4096],
}),
}),
tileUrlFunction: function (tileCoord) {
const data = tileIndex.getTile(
tileCoord[0],
tileCoord[1],
tileCoord[2]
);
const geojson = JSON.stringify(
{
type: 'FeatureCollection',
features: data ? data.features : [],
},
replacer
);
return 'data:application/json;charset=UTF-8,' + geojson;
},
});
const vectorLayer = new VectorTileLayer({
source: vectorSource,
});
map.addLayer(vectorLayer);
});
| JavaScript | 0 | @@ -1987,24 +1987,455 @@
ileCoord) %7B%0A
+ // Use the tile coordinate as a pseudo URL for caching purposes%0A return JSON.stringify(tileCoord);%0A %7D,%0A %7D);%0A // For tile loading obtain the GeoJSON for the tile coordinate%0A // before calling the default tileLoadFunction%0A const defaultTileLoadFunction = vectorSource.getTileLoadFunction();%0A vectorSource.setTileLoadFunction(%0A function (tile, url) %7B%0A const tileCoord = JSON.parse(url);%0A
cons
@@ -2462,16 +2462,16 @@
etTile(%0A
-
@@ -2735,22 +2735,66 @@
-return
+defaultTileLoadFunction(%0A tile,%0A
'data:a
@@ -2834,16 +2834,26 @@
geojson
+%0A )
;%0A
@@ -2849,31 +2849,29 @@
);%0A %7D
-,
%0A
-%7D
);%0A const
|
b7f62387f52d9b037d1f404bfabc461472e367ff | Load rastersync resources using https if available | examples/rastersync.js | examples/rastersync.js | var view = new ol.View({
center: ol.proj.transform([-112.2, 36.06], 'EPSG:4326', 'EPSG:3857'),
zoom: 11
});
var layer0 = new ol.layer.Tile({
source: new ol.source.OSM()
});
var layer1 = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'http://tileserver.maptiler.com/grandcanyon.json',
crossOrigin: 'anonymous'
})
});
var tileJsonSource = new ol.source.TileJSON({
url: 'http://api.tiles.mapbox.com/v3/mapbox.world-borders-light.json',
crossOrigin: 'anonymous'
});
var layer2 = new ol.layer.Tile({
source: tileJsonSource
});
var ol2d = new ol.Map({
layers: [layer0, new ol.layer.Group({layers: [layer1, layer2]})],
target: 'map2d',
view: view,
renderer: 'webgl'
});
var ol3d = new olcs.OLCesium({map: ol2d, target: 'map3d'});
var scene = ol3d.getCesiumScene();
var terrainProvider = new Cesium.CesiumTerrainProvider({
url : '//assets.agi.com/stk-terrain/world'
});
scene.terrainProvider = terrainProvider;
ol3d.setEnabled(true);
var addStamen = function() {
ol2d.addLayer(new ol.layer.Tile({
source: new ol.source.Stamen({
opacity: 0.7,
layer: 'watercolor'
})
}));
};
var tileWMSSource = new ol.source.TileWMS({
url: 'http://demo.boundlessgeo.com/geoserver/wms',
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
crossOrigin: 'anonymous'
});
var addTileWMS = function() {
ol2d.addLayer(new ol.layer.Tile({
opacity: 0.5,
extent: [-13884991, 2870341, -7455066, 6338219],
source: tileWMSSource
}));
};
var changeI = 0;
var changeTileWMSParams = function() {
tileWMSSource.updateParams({
'LAYERS': (changeI++) % 2 == 0 ? 'nurc:Img_Sample' : 'topp:states'
});
};
var addTileJSON = function() {
ol2d.addLayer(new ol.layer.Tile({
source: tileJsonSource
}));
};
var removeLastLayer = function() {
var length = ol2d.getLayers().getLength();
if (length > 0) {
ol2d.getLayers().removeAt(length - 1);
}
};
| JavaScript | 0 | @@ -255,16 +255,17 @@
l: 'http
+s
://tiles
@@ -399,16 +399,17 @@
l: 'http
+s
://api.t
@@ -858,18 +858,16 @@
vider(%7B%0A
-
url :
@@ -867,16 +867,22 @@
url : '
+https:
//assets
|
6db750d22e8da4632723445ab1c13f002b8958bd | add comments | examples/simpleTest.js | examples/simpleTest.js | const serverOperations = require('../out/src/serverOperations');
const config = require('../out/src/config');
// Initialise all required login information
var login = new config.ConnectionInformation();
login.server = '127.0.0.1';
login.port = 11000;
login.principal = 'dopaag';
login.username = 'admin';
login.password = '';
// The source code is the simple test value
var myTestCode = "return 'My simple script!';\n";
// Create the script
var myScript = new serverOperations.scriptT('mySimpleScript');
myScript.localCode = myTestCode;
myScript.conflictMode = false;
// upload
async function uploadAndCheck(paramLogin, paramScript){
await serverOperations.serverSession(paramLogin, [paramScript], serverOperations.uploadScript);
var retval = await serverOperations.serverSession(paramLogin, [paramScript], serverOperations.downloadScript);
if (retval && retval[0] && retval[0].serverCode === myTestCode) {
console.log('Everything ok :)\n');
} else {
console.log('Something went wrong :(\n');
}
}
uploadAndCheck(login, myScript);
| JavaScript | 0 | @@ -571,18 +571,8 @@
;%0A%0A%0A
-// upload%0A
asyn
@@ -622,16 +622,31 @@
Script)%7B
+%0A%0A // upload
%0A awa
@@ -733,24 +733,41 @@
loadScript);
+%0A%0A // download
%0A var ret
@@ -869,16 +869,30 @@
Script);
+%0A%0A // check
%0A if
|
a7d2d50dc0f86501a5c04eacc0b11487ab68527b | remove unused argument to addLocalMedia() | factories/mediafile.js | factories/mediafile.js | wwt.app.factory(
'MediaFile',
[
'$q',
function ($q) {
var api = {
addLocalMedia: addLocalMedia,
flushStore: flushStore,
getBinaryData: getBinaryData
};
var mediaCache = [];
function Media(params) {
return {
url:params.url,
key:params.key,
db:'tempblob',
size:params.size,
filename:params.name
}
}
function addLocalMedia(mediaKey, file, db) {
var deferred = $q.defer();
var keys = ['collection', 'tour', 'image'];
var req = indexedDB.open('tempblob');
req.onupgradeneeded = function () {
// Define the database schema if necessary.
var db = req.result;
var store = db.createObjectStore('files');
};
req.onsuccess = function () {
var db = req.result;
var key = keys.indexOf(mediaKey);
var tx = db.transaction('files', 'readwrite');
var store = tx.objectStore('files');
var addFile = function () {
var addTx = store.put(file, key);
addTx.onsuccess = readFile;
};
var readFile = function () {
var mediaReq = store.get(key);
mediaReq.onsuccess = function (e) {
var file = mediaReq.result;
var localUrl = URL.createObjectURL(file);
var media = Media({
url: localUrl,
key: key,
size: file.size,
name: file.name
});
deferred.resolve(media);
mediaCache[key] = media;
};
};
addFile();
}
return deferred.promise;
}
function flushStore(db) {
var deferred = $q.defer();
var dbName = db || 'tempblob';
var req = indexedDB.deleteDatabase(dbName);
req.onupgradeneeded = function () {
deferred.reject('upgradeneeded');
};
req.onsuccess = deferred.resolve;
req.onerror = deferred.reject;
req.onblocked = deferred.reject;
return deferred.promise;
}
function getBinaryData(url, asUIntArray, asArrayBuffer) {
var deferred = $q.defer();
console.time('get binary string');
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onload = function () {
if (asArrayBuffer) {
deferred.resolve(this.response);
} else if (asUIntArray) {
var uInt8Array = new Uint8Array(this.response);
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
deferred.resolve(uInt8Array);
} else {
deferred.resolve(req.responseText);
}
console.timeEnd('get binary data');
}
if (asUIntArray) {
req.responseType = 'arraybuffer';
} else {
req.overrideMimeType('text\/plain; charset=x-user-defined');
}
req.send(null);
return deferred.promise;
}
var appendBuffer = function (buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
};
function stringToUint(string) {
string = btoa(unescape(encodeURIComponent(string))),
charList = string.split(''),
uintArray = [];
for (var i = 0; i < charList.length; i++) {
uintArray.push(charList[i].charCodeAt(0));
}
return new Uint8Array(uintArray);
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
return api;
}
]
);
| JavaScript | 0 | @@ -474,12 +474,8 @@
file
-, db
) %7B%0A
|
c66c6d5660ab858595818b0fe0773d68e3d329d6 | Update PAC file to use proxy only for internal sites. | files/socks/config.pac | files/socks/config.pac | function FindProxyForURL(url, host) {
return "SOCKS 127.0.0.1:8882";
}
| JavaScript | 0 | @@ -39,37 +39,191 @@
-return %22SOCKS 127.0.0.1:8882%22;
+var resolved_ip = dnsResolve(host);%0A if (isInNet(resolved_ip, %22142.150.237.0%22, %22255.255.255.0%22)) %7B%0A return %22SOCKS 127.0.0.1:8882%22;%0A %7D else %7B%0A return %22DIRECT%22;%0A %7D
%0A%7D%0A
|
1ade97c21acb4ec2435734deb7052028129e8942 | build as default task | flexget/ui/gulpfile.js | flexget/ui/gulpfile.js | 'use strict';
var gulp = require('gulp');
gulp.paths = {
src: 'src',
dist: 'app',
tmp: '.tmp'
};
require('require-dir')('./gulp');
gulp.task('build', ['clean'], function () {
gulp.start('buildapp');
});
| JavaScript | 0.000002 | @@ -210,8 +210,41 @@
');%0A%7D);%0A
+%0Agulp.task('default', %5B'build'%5D);
|
e9226a54658da17aed4113b3eb8db21d8ed61b22 | Add singleCourse subscription; courseId variable | client/templates/course/course.js | client/templates/course/course.js | Template.course.created = function () {
// Set the empty active lesson ID variable
activeLessonID = new ReactiveVar(undefined);
};
| JavaScript | 0 | @@ -35,16 +35,304 @@
() %7B%0A
+// Get reference to template instance%0A var instance = this;%0A%0A // Get reference to router%0A var router = Router.current();%0A%0A // Get course ID from router%0A instance.courseId = router.params._id;%0A%0A // Subscribe to single course%0A instance.subscribe('singleCourse', instance.courseId);%0A%0A
// Set
@@ -368,18 +368,16 @@
ariable%0A
-
active
|
45a8199d4e523eed33229b8685547c71a8469f14 | update rendered calendar dates as soon as locale changes | client/views/calendar/calendar.js | client/views/calendar/calendar.js | Router.map(function () {
this.route('calendar', {
path: 'calendar',
template: 'calendar',
data: function() { return this.params; },
onAfterAction: function() {
document.title = webpagename + 'Calendar'
}
});
});
var updateUrl = function(event, instance) {
var filterParams = instance.filter.toParams();
delete filterParams['region']; // HACK region is kept in the session (for bad reasons)
var queryString = UrlTools.paramsToQueryString(filterParams);
var options = {};
if (queryString.length) {
options.query = queryString;
}
Router.go('calendar', {}, options);
event.preventDefault();
}
Template.calendar.helpers({
weekday: function(day) {
return day.format('dddd Do MMMM');
},
past: function() {
return moment().isAfter(this.end);
},
days: function() {
var start = Template.instance().filter.get('start');
var i = 0;
var days = [];
for (; i < 8; i++) {
days.push({
start: moment(start).add(i, 'days'),
end: moment(start).add(i+1, 'days')
});
}
return days;
},
filter: function() {
return Template.instance().filter;
},
startDate: function() {
return Template.instance().filter.get('start').format('LL');
},
endDate: function() {
return Template.instance().filter.get('start').add(8, 'days').format('LL');
}
});
Template.calendarDay.helpers({
hasEvents: function() {
var filterQuery = this.filter.toQuery();
filterQuery.period = [this.day.start.toDate(), this.day.end.toDate()];
return eventsFind(filterQuery).count() > 0;
},
events: function() {
var filterQuery = this.filter.toQuery();
filterQuery.period = [this.day.start.toDate(), this.day.end.toDate()];
return eventsFind(filterQuery);
},
calendarDay: function(day) {
return day.format('dddd Do MMMM');
}
});
Template.calendar.onCreated(function() {
var instance = this;
var filter = Filtering(EventPredicates);
instance.filter = filter;
// Read URL state
instance.autorun(function() {
var data = Template.currentData();
var query = data.query || {};
filter
.clear()
.add('start', moment())
.add('region', Session.get('region'))
.read(query)
.done();
});
// Keep old subscriptions around until the new ones are ready
var eventSub = false;
var oldSubs = [];
var stopOldSubs = function() {
if (eventSub.ready()) {
_.map(oldSubs, function(sub) { sub.stop() });
oldSubs = [];
}
}
instance.autorun(function() {
var filterQuery = filter.toQuery();
var start = filter.get('start').toDate();
var limit = filter.get('start').add(8, 'days').toDate();
filterQuery.period = [start, limit];
if (eventSub) oldSubs.push(eventSub);
eventSub = instance.subscribe('eventsFind', filterQuery, stopOldSubs);
});
});
Template.calendar.rendered = function() {
var currentPath = Router.current().route.path(this)
$('a[href!="' + currentPath + '"].nav_link').removeClass('active');
$('a[href="' + currentPath + '"].nav_link').addClass('active');
};
Template.calendar_event.rendered = function() {
this.$('.ellipsis').dotdotdot({});
};
var mvDateHandler = function(amount, unit) {
return function(event, instance) {
var start = instance.filter.get('start');
start.add(amount, unit);
instance.filter.add('start', start).done();
updateUrl(event, instance);
return false;
}
}
Template.calendar.events({
'click .nextDay': mvDateHandler(1, 'day'),
'click .prevDay': mvDateHandler(-1, 'day'),
'click .nextWeek': mvDateHandler(1, 'week'),
'click .prevWeek': mvDateHandler(-1, 'week'),
'click .nextMonth': mvDateHandler(1, 'month'),
'click .prevMonth': mvDateHandler(-1, 'month'),
'click .nextYear': mvDateHandler(1, 'year'),
'click .prevYear': mvDateHandler(-1, 'year'),
});
| JavaScript | 0 | @@ -1713,34 +1713,80 @@
on(day) %7B%0A%09%09
-return day
+Session.get('timeLocale');%0A%09%09return moment(day.toDate())
.format('ddd
|
eaa0d1a824e54f33eb289e024e0fe74521ae896e | Fix error in debug command when no project config is found | packages/@sanity/cli/src/commands/debug/printDebugInfo.js | packages/@sanity/cli/src/commands/debug/printDebugInfo.js | import os from 'os'
import util from 'util'
import path from 'path'
import pick from 'lodash/pick'
import omit from 'lodash/omit'
import osenv from 'osenv'
import fsp from 'fs-promise'
import xdgBasedir from 'xdg-basedir'
import promiseProps from 'promise-props-recursive'
import getUserConfig from '../../util/getUserConfig'
import {printResult as printVersionsResult} from '../versions/printVersionResult'
import findSanityModuleVersions from '../../actions/versions/findSanityModuleVersions'
export default async (args, context) => {
const {user, globalConfig, projectConfig, project, versions} = await gatherInfo(context)
const {chalk} = context
// User info
context.output.print('\nUser:')
if (user instanceof Error) {
context.output.print(chalk.red(user.message))
} else {
printKeyValue({ID: user.id, Name: user.name, Email: user.email}, context)
}
// Project info (API-based)
if (project) {
context.output.print('Project:')
printKeyValue({
'Display name': project.displayName,
'Studio URL': project.studioHostname,
'User role': project.userRole
}, context)
}
// Auth info
if (globalConfig.authToken) {
context.output.print('Authentication:')
printKeyValue({
'User type': globalConfig.authType || 'normal',
'Auth token': globalConfig.authToken,
}, context)
}
// Global configuration (user home dir config file)
context.output.print(`Global config (${chalk.yellow(getGlobalConfigLocation())}):`)
const globalCfg = omit(globalConfig, ['authType', 'authToken'])
context.output.print(` ${formatObject(globalCfg).replace(/\n/g, '\n ')}\n`)
// Project configuration (projectDir/sanity.json)
if (!(projectConfig instanceof Error)) {
const configLocation = path.join(context.workDir, 'sanity.json')
context.output.print(`Project config (${chalk.yellow(configLocation)}):`)
context.output.print(` ${formatObject(projectConfig).replace(/\n/g, '\n ')}`)
}
// Print installed package versions
if (versions) {
context.output.print('\nPackage versions:')
printVersionsResult(versions, line => context.output.print(` ${line}`))
}
}
function formatObject(obj) {
return util.inspect(obj, {colors: true, depth: +Infinity})
}
function printKeyValue(obj, context) {
let printedLines = 0
Object.keys(obj).forEach(key => {
if (typeof obj[key] !== 'undefined') {
context.output.print(` ${key}: ${formatObject(obj[key])}`)
printedLines++
}
})
if (printedLines > 0) {
context.output.print('')
}
}
async function gatherInfo(context) {
const baseInfo = await promiseProps({
user: gatherUserInfo(context),
globalConfig: gatherGlobalConfigInfo(context),
projectConfig: gatherProjectConfigInfo(context),
})
return promiseProps(Object.assign({
project: gatherProjectInfo(context, baseInfo),
versions: findSanityModuleVersions(context)
}, baseInfo))
}
function getGlobalConfigLocation() {
const user = (osenv.user() || 'user').replace(/\\/g, '')
const configDir = xdgBasedir.config || path.join(os.tmpdir(), user, '.config')
return path.join(configDir, 'sanity', 'config.json')
}
function gatherGlobalConfigInfo(context) {
return getUserConfig().all
}
async function gatherProjectConfigInfo(context) {
const workDir = context.workDir
const configLocation = path.join(workDir, 'sanity.json')
try {
const config = await fsp.readJson(configLocation)
if (!config.api || !config.api.projectId) {
throw new Error(`Project config (${configLocation}) does not contain required "api.projectId" key`)
}
return config
} catch (err) {
return {error: err}
}
}
async function gatherProjectInfo(context, baseInfo) {
const client = context.apiClient({requireUser: false, requireProject: false})
const projectId = client.config().projectId
if (!projectId) {
return null
}
const projectInfo = await client.projects.getById(projectId)
if (!projectInfo) {
return new Error(`Project specified in configuration (${projectId}) does not exist in API`)
}
const member = projectInfo.members.find(proj => proj.id === baseInfo.user.id)
const hostname = projectInfo.studioHostname && `https://${projectInfo.studioHostname}.sanity.studio/`
return {
displayName: projectInfo.displayName,
studioHostname: hostname,
userRole: member ? member.role : 'unknown'
}
}
async function gatherUserInfo(context) {
const client = context.apiClient({requireUser: false, requireProject: false})
const hasToken = Boolean(client.config().token)
if (!hasToken) {
return new Error('Not logged in')
}
const userInfo = await client.users.getById('me')
if (!userInfo) {
return new Error('Token expired or invalid')
}
return pick(userInfo, ['id', 'name', 'email'])
}
| JavaScript | 0 | @@ -1695,18 +1695,16 @@
n)%0A if
-(!
(project
@@ -1709,34 +1709,16 @@
ctConfig
- instanceof Error)
) %7B%0A
@@ -2130,16 +2130,45 @@
ine%7D%60))%0A
+ context.output.print('')%0A
%7D%0A%7D%0A%0Af
@@ -3662,16 +3662,47 @@
return
+ err.code === 'ENOENT' ? null :
%7Berror:
|
eaac85223b084ed3441ff3c87cdada46b4c50ebe | add community cross-storage on select | packages/bonde-admin/pages/admin/communities/list/page.js | packages/bonde-admin/pages/admin/communities/list/page.js | import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { BondeBackground } from '~client/components/layout/background'
import * as paths from '~client/paths'
import { FormattedMessage } from 'react-intl'
import { Loading } from '~client/components/await'
import { ListItem } from '~client/community/components'
class CommunityListPage extends Component {
componentDidMount () {
this.props.asyncFetch()
}
componentWillReceiveProps (nextProps) {
if (nextProps.isLoaded && nextProps.communities.length === 0) {
this.props.history.push(paths.communityAdd())
}
}
onClickItem (id) {
this.props.select(id)
this.props.history.push(paths.mobilizations())
}
render () {
const { isLoading, isLoaded, communities, user } = this.props
return isLoading ? <Loading /> : (
<BondeBackground
contentSize={3}
alignment={{ x: 'center', y: 'top' }}
>
<div className='col-12'>
<h1>
<FormattedMessage
id='page--community-list.title'
defaultMessage='Olá {name},'
values={{ name: user.firstName || user.first_name }}
/>
</h1>
<h2>
<FormattedMessage
id='page--community-list.subtitle'
defaultMessage='Escolha uma das suas comunidades'
/>
</h2>
{isLoaded ? (
<div className='rounded bg-white'>
{communities && communities.map((community, key) => (
<ListItem
key={`list-item-${key}`}
community={community}
onClick={this.onClickItem.bind(this)}
/>
))}
</div>
) : null}
<p className='white center'>
<FormattedMessage
id='page--community-list.or'
defaultMessage='or {link}'
values={{
link: (
<Link to={paths.communityAdd()}>
<FormattedMessage
id='page--community-list.new'
defaultMessage='Crie uma nova comunidade'
/>
</Link>
)
}}
/>
</p>
</div>
</BondeBackground>
)
}
}
CommunityListPage.propTypes = {
isLoaded: PropTypes.bool,
isLoading: PropTypes.bool,
communities: PropTypes.array,
user: PropTypes.object.isRequired,
// Actions
select: PropTypes.func.isRequired
}
export default CommunityListPage
| JavaScript | 0 | @@ -371,16 +371,72 @@
ponents'
+%0Aimport crossStorage from '~client/cross-storage-client'
%0A%0Aclass
@@ -723,40 +723,236 @@
em (
-id) %7B%0A this.props.select(id)%0A
+community) %7B%0A crossStorage%0A .onConnect()%0A .then(() =%3E %7B%0A return crossStorage%0A .set('community', JSON.stringify(community))%0A .then(() =%3E %7B%0A this.props.select(community.id)%0A
@@ -998,16 +998,38 @@
ions())%0A
+ %7D)%0A %7D)%0A
%7D%0A%0A r
@@ -1975,16 +1975,22 @@
nClick=%7B
+() =%3E
this.onC
@@ -2001,18 +2001,18 @@
Item
-.bind(this
+(community
)%7D%0A
|
cab6c954eaa164e91a252f0b062a6574497da516 | Reset references to panel views on schema load | web_client/js/views/panelGroup.js | web_client/js/views/panelGroup.js | histomicstk.views.PanelGroup = girder.View.extend({
events: {
'click .h-info-panel-reload': 'reload',
'click .h-info-panel-submit': 'submit',
'click .h-remove-panel': 'removePanel'
},
initialize: function () {
this.panels = [];
this._panelViews = {};
this._schemaName = null;
this._jobsPanelView = new histomicstk.views.JobsPanel({
parentView: this,
spec: {
title: 'Jobs',
collapsed: true
}
});
// render a specific schema
this.listenTo(histomicstk.router, 'route:gui', this.schema);
// remove the current schema reseting to the default view
this.listenTo(histomicstk.router, 'route:main', this.reset);
},
render: function () {
this.$el.html(histomicstk.templates.panelGroup({
info: this._gui,
panels: this.panels
}));
_.each(this._panelViews, function (view) {
view.remove();
});
this._jobsPanelView.setElement(this.$('.h-jobs-panel')).render();
_.each(this.panels, _.bind(function (panel) {
this._panelViews[panel.id] = new histomicstk.views.ControlsPanel({
parentView: this,
collection: new histomicstk.collections.Widget(panel.parameters),
title: panel.label,
advanced: panel.advanced,
el: this.$el.find('#' + panel.id)
});
this._panelViews[panel.id].render();
}, this));
},
/**
* Submit the current values to the server.
*/
submit: function () {
var params;
if (!this.validate()) {
return;
}
params = this.parameters();
_.each(params, function (value, key) {
if (_.isArray(value)) {
params[key] = JSON.stringify(value)
}
});
// For the widget demo, just print the parameters to the console
if (this._schemaName === 'demo') {
console.log('Submit'); // eslint-disable-line no-console
console.log(JSON.stringify(params, null, 2)); // eslint-disable-line no-console
return;
}
// post the job to the server
girder.restRequest({
path: 'HistomicsTK/' + this._schemaName + '/run',
type: 'POST',
data: params
});
},
/**
* Get the current values of all of the parameters contained in the gui.
* Returns an object that maps each parameter id to it's value.
*/
parameters: function () {
return _.chain(this._panelViews)
.pluck('collection')
.invoke('values')
.reduce(function (a, b) {
return _.extend(a, b);
}, {})
.value();
},
/**
* Return an array of all widget models optionally filtered by the given panel id
* and model filtering function.
*/
models: function (panelId, modelFilter) {
modelFilter = modelFilter || function () { return true; };
return _.chain(this._panelViews)
.filter(function (v, i) {
return panelId === undefined || panelId === i
})
.pluck('collection')
.pluck('models')
.flatten()
.filter(modelFilter)
.value();
},
/**
* Return an array of all invalid models. Optionally filter by the given panel id.
*/
invalidModels: function (panelId) {
return this.models(panelId, function (m) { return !m.isValid(); });
},
/**
* Return true if all parameters are set and valid. Also triggers 'invalid'
* events on each of the invalid models as a byproduct.
*/
validate: function () {
return !this.invalidModels().length;
},
/**
* Remove a panel after confirmation from the user.
*/
removePanel: function (e) {
girder.confirm({
text: 'Are you sure you want to remove this panel?',
confirmCallback: _.bind(function () {
var el = $(e.currentTarget).data('target');
var id = $(el).attr('id');
this.panels = _.filter(this.panels, function (panel) {
return panel.id !== id;
});
this.render();
}, this)
});
},
/**
* Remove all panels.
*/
reset: function () {
this._schemaName = null;
this.panels = [];
this._gui = null;
this.render();
},
/**
* Restore all panels to the default state.
*/
reload: function () {
if (!this._gui) {
return this;
}
// Create a panel for each "group" in the schema, and copy
// the advanced property from the parent panel.
this.panels = _.chain(this._gui.panels).map(function (panel) {
return _.map(panel.groups, function (group) {
group.advanced = !!panel.advanced;
group.id = _.uniqueId('panel-');
return group;
});
}).flatten(true).value();
this.render();
return this;
},
/**
* Generate a "demo" application that shows off the different kinds of
* widgets available.
*/
demo: function () {
$.ajax(girder.staticRoot + '/built/plugins/HistomicsTK/extra/widget_demo.json')
.then(_.bind(function (spec) {
this._gui = spec;
this._schemaName = 'demo';
this.reload();
}, this));
return this;
},
/**
* Generate panels from a slicer XML schema stored on the server.
*/
schema: function (s) {
if (s === 'demo') {
return this.demo();
}
girder.restRequest({
path: '/HistomicsTK/' + s + '/xmlspec'
}).then(_.bind(function (xml) {
var fail = !xml;
try {
this._gui = histomicstk.schema.parse(xml);
} catch (e) {
fail = true;
}
if (fail) {
girder.events.trigger('g:alert', {
icon: 'attention',
text: 'Invalid XML schema',
type: 'danger'
});
histomicstk.router.navigate('', {trigger: true});
this.reset();
return this;
}
this._schemaName = s;
this.reload();
return this;
}, this));
return this;
}
});
| JavaScript | 0 | @@ -1021,32 +1021,63 @@
();%0A %7D);%0A
+ this._panelViews = %7B%7D;%0A
this._jo
|
482b449b32b07c8f0a5a76b73344bc332585b296 | correct wording | webapp/app/js/controllers/auth.js | webapp/app/js/controllers/auth.js | 'use strict';
KylinApp.controller('LoginCtrl', function ($scope, $rootScope, $location, $base64, AuthenticationService, UserService) {
$scope.username = null;
$scope.password = null;
$scope.loading = false;
$scope.login = function () {
// set the basic authentication header that will be parsed in the next request and used to authenticate
httpHeaders.common['Authorization'] = 'Basic ' + $base64.encode($scope.username + ':' + $scope.password);
$scope.loading = true;
AuthenticationService.login({}, {}, function (data) {
$scope.loading = false;
$rootScope.$broadcast('event:loginConfirmed');
UserService.setCurUser(data);
$location.path(UserService.getHomePage());
}, function (error) {
$scope.loading = false;
$scope.error = "Unable to login, please check your username/password and make sure you have L2 access.";
});
console.debug("Login event requested.");
};
}); | JavaScript | 0.999886 | @@ -934,16 +934,28 @@
ave
-L2 acces
+correct access right
s.%22;
|
d913e80cf5284b5acf167a57bcbedf63b0f66e78 | Remove unused imports | webpack/typescript-loader-rule.js | webpack/typescript-loader-rule.js | const path = require('path');
const { locateStripesModule } = require('./module-paths');
// We want to transpile files inside node_modules/@folio or outside
// any node_modules directory. And definitely not files in
// node_modules outside the @folio namespace even if some parent
// directory happens to be in @folio.
function babelLoaderTest(fileName) {
const nodeModIdx = fileName.lastIndexOf('node_modules');
const folioIdx = fileName.lastIndexOf('@folio');
if (fileName.endsWith('.tsx') && (nodeModIdx === -1 || folioIdx > nodeModIdx)) {
return true;
}
return false;
}
module.exports = {
test: babelLoaderTest,
loader: 'awesome-typescript-loader',
query: {
configFileName: path.join(__dirname, 'tsconfig.json'),
},
};
| JavaScript | 0.000001 | @@ -26,67 +26,8 @@
h');
-%0Aconst %7B locateStripesModule %7D = require('./module-paths');
%0A%0A//
|
5bd3b5032056799fb8f373f58861b4bb70c3f83d | Update DataTranslationCredits.js | src/DataTranslationCredits.js | src/DataTranslationCredits.js | /*
DataTranslationCredits.js
Copyright (c) 2014-2020 dangered wolf, et al
Released under the MIT License
*/
export const translationCredits = `
<b>български</b><br>
vancho1<br>
<a href="https://twitter.com/Khar0s" rel="user" target="_blank">Kharos</a><br>
<br><b>čeština</b><br>
<a href="https://twitter.com/JamesTheWusky" rel="user" target="_blank">JamesTheWusky</a><br>
<br><b>中文</b><br>
<a href="https://twitter.com/N0PELGND" rel="user" target="_blank">DatNopeLegend</a><br>
<a href="https://twitter.com/jeff7262" rel="user" target="_blank">JeffW</a><br>
<a href="https://twitter.com/hugoalhofficial" rel="user" target="_blank">hugoalh</a><br>
<br><b>Deutsche</b><br>
<a href="https://twitter.com/cmdrfletcher" rel="user" target="_blank">cmdrfletcher</a><br>
<a href="https://twitter.com/hamburgator" rel="user" target="_blank">Planke</a><br>
<a href="https://twitter.com/FLUFFSQUEAKER" rel="user" target="_blank">milanmat-fluffsqueaker</a><br>
<a href="https://twitter.com/ItsJustMirko" rel="user" target="_blank">Mirko</a><br>
<a href="https://twitter.com/Machtergreifung" rel="user" target="_blank">Machtergreifung</a><br>
<a href="https://twitter.com/TecraFox" rel="user" target="_blank">Tecra</a><br>
<br><b>Eesti</b><br>
Thoth<br>
<br><b>Español</b><br>
<a href="https://twitter.com/klopma" rel="user" target="_blank">Carlos López</a><br>
<a href="https://twitter.com/dangeredwolf" rel="user" target="_blank">dangeredwolf</a><br>
<a href="https://twitter.com/en_penumbras" rel="user" target="_blank">en_penumbras</a><br>
<a href="https://twitter.com/FibonacciPrower" rel="user" target="_blank">Fibonacci Prower</a><br>
<a href="https://twitter.com/RichardWolfVI" rel="user" target="_blank">Juan Marulanda</a><br>
minyfriki<br>
tetrisdog<br>
TAKAHASHI Shuuji<br>
<br><b>Français</b><br>
<a href="https://twitter.com/COLAMAroro" rel="user" target="_blank">COLAMAroro</a><br>
<a href="https://twitter.com/dracoz" rel="user" target="_blank">Draco</a><br>
<a href="https://twitter.com/eramdam" rel="user" target="_blank">Damien Erambert (eramdam)</a><br>
<a href="https://twitter.com/embraser01" rel="user" target="_blank">embraser01</a><br>
<a href="https://twitter.com/Fenrykos" rel="user" target="_blank">Fenrykos</a><br>
<a href="https://twitter.com/MuraseEtienne" rel="user" target="_blank">Étienne Murase</a><br>
<a href="https://twitter.com/Meylody_" rel="user" target="_blank">Mélodie</a><br>
<a href="https://twitter.com/Nintenloup_Wolf" rel="user" target="_blank">Nintenloup</a><br>
<a href="https://twitter.com/robot275" rel="user" target="_blank">Robot275</a><br>
<a href="https://twitter.com/ShadyFennec" rel="user" target="_blank">ShadyFennec</a><br>
<br><b>日本語</b><br>
<a href="https://twitter.com/hideki_0403" rel="user" target="_blank">ゆきねこ (hideki_0403)</a><br>
pukutaaang<br>
TAKAHASHI Shuuji<br>
<br><b>한국어</b><br>
kemoshota<br>
Lastorder<br>
<br><b>Hrvatski</b><br>
<a href="https://twitter.com/jptjohnny" rel="user" target="_blank">JPTJohnny</a><br>
<br><b>italiano</b><br>
<a href="https://twitter.com/hamburgator" rel="user" target="_blank">Planke</a><br>
<br><b>Polski</b><br>
<a href="https://twitter.com/4D3s12" rel="user" target="_blank">Ad3s12</a><br>
<a href="https://twitter.com/Patryk1023PL" rel="user" target="_blank">Patryk1023</a><br>
<a href="https://twitter.com/PeCeT_full" rel="user" target="_blank">PeCeT_full</a><br>
Paweł Amroziewicz<br>
<a href="https://twitter.com/w1nk000" rel="user" target="_blank">w1nk000</a><br>
<br><b>Português</b><br>
João Ferreira<br>
<br><b>Português (Brasil)</b><br>
<a href="https://twitter.com/eubyt" rel="user" target="_blank">Adrian César</a><br>
André Gama / ToeOficial<br>
Chef! / chefwireframe<br>
<br><b>русский</b><br>
<a href="https://twitter.com/Sominemo" rel="user" target="_blank">Sominemo</a><br>
<a href="https://twitter.com/coldarchie" rel="user" target="_blank">Archie</a><br>
<a href="https://twitter.com/reig_xvi" rel="user" target="_blank">Cyxtru</a><br>
<a href="https://twitter.com/Tailsray2" rel="user" target="_blank">Tailsray</a><br>
<br>
<br>
`
| JavaScript | 0 | @@ -664,32 +664,43 @@
eutsche%3C/b%3E%3Cbr%3E%0A
+Bandie%3Cbr%3E%0A
%3Ca href=%22https:/
|
d60bd6326ba6eb32ee5693e5269edd9b701af75b | Update manage-index.js | wp/admin/sections/manage-index.js | wp/admin/sections/manage-index.js | (function($){
function done(failed){
$("#reindex").removeAttr('disabled').addClass('complete');
$('#progress').hide();
if(failed){
$('#error').show().find('.msg').text(failed);
}else{
$('.finished').text(0);
$('#complete').show();
}
}
function index(page){
$.ajax({
url: window.indexing.ajaxurl,
type: 'POST',
data: {
'action': 'esreindex',
'page': page
},
error: function(xhr){
done(xhr.responseText);
},
success: function(indexed){
var indexed = parseInt(indexed);
var total = $('.finished');
total.text(parseInt(total.text()) + indexed);
if(indexed == window.indexing.perpage){
index(page + 1);
}else{
done();
}
}
});
}
$(function(){
$('.total').text(window.indexing.total);
$("#reindex").click(function(){
$(this).attr('disabled', 'disabled');
$('#progress').show();
$('#complete').hide();
$('#error').hide();
index(1);
return false;
});
});
})(jQuery); | JavaScript | 0.000001 | @@ -202,16 +202,18 @@
+%09%09
$('.fini
@@ -993,8 +993,9 @@
jQuery);
+%0A
|
695592afeda67670931d4025b1d28c9db22348f7 | Switch to https | www/js/core/constants/settings.js | www/js/core/constants/settings.js | (function () {
"use strict";
angular
.module('orange')
.constant('settings', {
'orangeApiUrl': 'http://orange-api.amida-demo.com/api/v1',
'clientSecret': 'arewedoneyetquestionmark',
'avatars': [
{path: 'img/avatars/Option1.png', path2x: 'img/avatars/Option1@2x.png'},
{path: 'img/avatars/Option2.png', path2x: 'img/avatars/Option2@2x.png'},
{path: 'img/avatars/Option3.png', path2x: 'img/avatars/Option3@2x.png'},
{path: 'img/avatars/Option4.png', path2x: 'img/avatars/Option4@2x.png'},
{path: 'img/avatars/Option5.png', path2x: 'img/avatars/Option5@2x.png'},
{path: 'img/avatars/Option6.png', path2x: 'img/avatars/Option6@2x.png'}
],
'defaultLimit': 25,
'defaultScrollDistance': '5%', // for ion-infinite-scroll
timeFormat: 'hh:mm a',
dateFormat: 'YYYY-MM-DD',
fullDateFormat: 'MMM Do YYYY'
});
})();
| JavaScript | 0 | @@ -130,16 +130,17 @@
': 'http
+s
://orang
@@ -141,19 +141,22 @@
/orange-
-api
+secure
.amida-d
|
22426584b9933e0d00e6c0fd241b9a3c3a87ba0b | fix the 'Document Table' directive controller | public/app/directives/controllers/rgiDocumentTableCtrl.js | public/app/directives/controllers/rgiDocumentTableCtrl.js | 'use strict';
angular.module('app')
.controller('rgiDocumentTableCtrl', function (
_,
$scope,
$rootScope,
rgiDialogFactory,
rgiAssessmentSrvc,
rgiDocumentSrvc,
rgiHttpResponseProcessorSrvc,
rgiIdentitySrvc,
rgiNotifier
) {
var limit = 100,
currentPage = 0,
totalPages = 0;
$scope.current_user = rgiIdentitySrvc.currentUser;
$scope.busy = false;
$scope.assessment_filter_options = [
{value: 'all', text: 'Show all documents'}
// {value: 'type', text: 'Sort by document type'},
// {value: 'assessments', text: 'Sort by attached assessments'}
];
$scope.assessment_filter = $scope.assessment_filter_options[0].value;
rgiAssessmentSrvc.query({}, function (assessments) {
if(assessments.reason) {
rgiNotifier.error('No assessments');
} else {
assessments.forEach(function(assessment) {
console.log(assessment);
$scope.assessment_filter_options.push({
value: assessment.assessment_ID,
text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
});
});
}
});
rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
if(response.reason) {
rgiNotifier.error('Load document data failure');
} else {
$scope.count = response.count;
$scope.documents = response.data;
totalPages = Math.ceil(response.count / limit);
currentPage = currentPage + 1;
}
}, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
$scope.loadMoreDocs = function() {
if ($scope.busy) {
return;
}
$scope.busy = true;
if(currentPage < totalPages) {
rgiDocumentSrvc.query({skip: currentPage, limit: limit}, function (response) {
if(response.reason) {
rgiNotifier.error('Documents loading failure');
} else {
$scope.documents = _.union($scope.documents, response.data);
currentPage = currentPage + 1;
$scope.busy = false;
}
}, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
}
};
$scope.deleteDocument = function(doc) {
rgiDialogFactory.deleteDocument($scope, doc);
};
});
| JavaScript | 0.000109 | @@ -248,33 +248,8 @@
vc,%0A
- rgiIdentitySrvc,%0A
@@ -288,61 +288,20 @@
var
-limit = 100,%0A currentPage = 0,%0A
+currentPage,
tot
@@ -311,74 +311,24 @@
ages
+, limit
=
+10
0;%0A%0A
- $scope.current_user = rgiIdentitySrvc.currentUser;%0A
@@ -352,17 +352,16 @@
false;%0A
-%0A
@@ -400,215 +400,11 @@
= %5B
-%0A %7Bvalue: 'all', text: 'Show all documents'%7D%0A // %7Bvalue: 'type', text: 'Sort by document type'%7D,%0A // %7Bvalue: 'assessments', text: 'Sort by attached assessments'%7D%0A
%5D;%0A
-%0A
@@ -438,49 +438,10 @@
r =
-$scope.assessment_filter_options%5B0%5D.value
+''
;%0A%0A
@@ -674,53 +674,8 @@
) %7B%0A
- console.log(assessment);%0A
@@ -970,63 +970,344 @@
-rgiDocumentSrvc.query(%7Bskip: currentPage, limit: limit%7D
+$scope.$watch('assessment_filter', function(assessment) %7B%0A currentPage = 0;%0A totalPages = 0;%0A var searchOptions = %7Bskip: currentPage, limit: limit%7D;%0A%0A if(assessment) %7B%0A searchOptions.assessments = assessment;%0A %7D%0A%0A rgiDocumentSrvc.queryCached(searchOptions
, fu
@@ -1318,32 +1318,36 @@
on (response) %7B%0A
+
if(r
@@ -1372,32 +1372,36 @@
+
rgiNotifier.erro
@@ -1437,32 +1437,36 @@
');%0A
+
+
%7D else %7B%0A
@@ -1450,32 +1450,36 @@
%7D else %7B%0A
+
@@ -1517,32 +1517,36 @@
+
$scope.documents
@@ -1563,16 +1563,168 @@
e.data;%0A
+%0A
+ if($scope.documents.length === 0) %7B%0A rgiNotifier.error('No documents uploaded');%0A %7D%0A%0A
@@ -1791,37 +1791,27 @@
-currentPage =
+
currentPage
@@ -1803,33 +1803,33 @@
currentPage
-+
+=
1;%0A
@@ -1820,34 +1820,42 @@
1;%0A
+
-%7D%0A
+ %7D%0A
%7D, rgiHt
@@ -1927,16 +1927,28 @@
lure'));
+%0A %7D);
%0A%0A
@@ -2150,30 +2150,28 @@
-rgiDocumentSrvc.query(
+var searchOptions =
%7Bski
@@ -2199,16 +2199,210 @@
: limit%7D
+;%0A%0A if($scope.assessment_filter) %7B%0A searchOptions.assessments = $scope.assessment_filter;%0A %7D%0A%0A rgiDocumentSrvc.query(searchOptions
, functi
|
0856dc16a30c53dfa979d1cb239471a566fb12b3 | Update item.client.controller.js | public/modules/core/controllers/item.client.controller.js | public/modules/core/controllers/item.client.controller.js | 'use strict';
angular.module('core').controller('itemController', ['$scope', 'Authentication', 'itemService',
function($scope, Authentication, itemService) {
// This provides Authentication context.
$scope.authentication = Authentication;
// Some example string - remove in prod
$scope.helloText = 'Item Test';
$scope.testuser = $scope.authentication.user.displayName;
$scope.items = itemService.query();
$scope.newItem = '';
$scope.UPCnumber = '';
// $scope.post = function() {
// $scope.items.push($scope.newItem);
// $scope.items.push({created_by: $scope.authentication.user.displayName, UPC: $scope.newItem, created_at: Date.now()},
// function(){
// $scope.items = itemService.query();
// $scope.newItem = '';
// });
// };
$scope.post = function() {
// $scope.newItem.created_by = 'tester';
// $scope.newItem.created_at = Date.now();
$scope.newItem.UPC = $scope.UPCnumber;
itemService.save($scope.newtItem, function(){
$scope.items = itemService.query();
$scope.newItem = '';
});
};
$scope.delete = function(item) {
itemService.delete({id: item._id});
$scope.item = itemService.query();
};
}
]);
| JavaScript | 0.000001 | @@ -956,17 +956,16 @@
cope.new
-t
Item, fu
|
616ab0f635e42c79c134cbf733143e89932c35e6 | Move the initial call to the componentDidMount method | react/features/conference/components/Conference.native.js | react/features/conference/components/Conference.native.js | import React, { Component } from 'react';
import { connect as reactReduxConnect } from 'react-redux';
import { connect, disconnect } from '../../base/connection';
import { Container } from '../../base/react';
import { FilmStrip } from '../../filmStrip';
import { LargeVideo } from '../../largeVideo';
import { RoomLockPrompt } from '../../room-lock';
import { Toolbar } from '../../toolbar';
import PasswordRequiredPrompt from './PasswordRequiredPrompt';
import { styles } from './styles';
/**
* The timeout in milliseconds after which the toolbar will be hidden.
*/
const TOOLBAR_TIMEOUT_MS = 5000;
/**
* The conference page of the application.
*/
class Conference extends Component {
/**
* Conference component's property types.
*
* @static
*/
static propTypes = {
/**
* The indicator which determines whether a password is required to join
* the conference and has not been provided yet.
*
* @private
* @type {JitsiConference}
*/
_passwordRequired: React.PropTypes.object,
/**
* The indicator which determines whether the user has requested to lock
* the conference/room.
*
* @private
* @type {JitsiConference}
*/
_roomLockRequested: React.PropTypes.object,
dispatch: React.PropTypes.func
}
/**
* Initializes a new Conference instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props) {
super(props);
this.state = { toolbarVisible: true };
/**
* The numerical ID of the timeout in milliseconds after which the
* toolbar will be hidden. To be used with
* {@link WindowTimers#clearTimeout()}.
*
* @private
*/
this._toolbarTimeout = undefined;
// Bind event handlers so they are only bound once for every instance.
this._onClick = this._onClick.bind(this);
}
/**
* Inits new connection and conference when conference screen is entered.
*
* @inheritdoc
* @returns {void}
*/
componentWillMount() {
this.props.dispatch(connect());
}
/**
* Destroys connection, conference and local tracks when conference screen
* is left. Clears {@link #_toolbarTimeout} before the component unmounts.
*
* @inheritdoc
* @returns {void}
*/
componentWillUnmount() {
this._clearToolbarTimeout();
this.props.dispatch(disconnect());
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const toolbarVisible = this.state.toolbarVisible;
this._setToolbarTimeout(toolbarVisible);
return (
<Container
onClick = { this._onClick }
style = { styles.conference }
touchFeedback = { false }>
<LargeVideo />
<Toolbar visible = { toolbarVisible } />
<FilmStrip visible = { !toolbarVisible } />
{
this._renderPrompt()
}
</Container>
);
}
/**
* Clears {@link #_toolbarTimeout} if any.
*
* @private
* @returns {void}
*/
_clearToolbarTimeout() {
if (this._toolbarTimeout) {
clearTimeout(this._toolbarTimeout);
this._toolbarTimeout = undefined;
}
}
/**
* Changes the value of the toolbarVisible state, thus allowing us to
* 'switch' between toolbar and filmstrip views and change the visibility of
* the above.
*
* @private
* @returns {void}
*/
_onClick() {
const toolbarVisible = !this.state.toolbarVisible;
this.setState({ toolbarVisible });
this._setToolbarTimeout(toolbarVisible);
}
/**
* Renders a prompt if a password is required to join the conference.
*
* @private
* @returns {ReactElement}
*/
_renderPasswordRequiredPrompt() {
const required = this.props._passwordRequired;
if (required) {
return (
<PasswordRequiredPrompt conference = { required } />
);
}
return null;
}
/**
* Renders a prompt if necessary such as when a password is required to join
* the conference or the user has requested to lock the conference/room.
*
* @private
* @returns {ReactElement}
*/
_renderPrompt() {
return (
this._renderPasswordRequiredPrompt()
|| this._renderRoomLockPrompt()
);
}
/**
* Renders a prompt if the user has requested to lock the conference/room.
*
* @private
* @returns {ReactElement}
*/
_renderRoomLockPrompt() {
const requested = this.props._roomLockRequested;
if (requested) {
return (
<RoomLockPrompt conference = { requested } />
);
}
return null;
}
/**
* Triggers the default toolbar timeout.
*
* @param {boolean} toolbarVisible - indicates if the toolbar is currently
* visible
* @private
*/
_setToolbarTimeout(toolbarVisible) {
this._clearToolbarTimeout();
if (toolbarVisible) {
this._toolbarTimeout
= setTimeout(this._onClick, TOOLBAR_TIMEOUT_MS);
}
}
}
/**
* Maps (parts of) the Redux state to the associated Conference's props.
*
* @param {Object} state - The Redux state.
* @returns {{
* _passwordRequired: boolean
* }}
*/
function mapStateToProps(state) {
return {
/**
* The indicator which determines whether a password is required to join
* the conference and has not been provided yet.
*
* @private
* @type {JitsiConference}
*/
_passwordRequired: state['features/base/conference'].passwordRequired,
/**
* The indicator which determines whether the user has requested to lock
* the conference/room.
*
* @private
* @type {JitsiConference}
*/
_roomLockRequested: state['features/room-lock'].requested
};
}
export default reactReduxConnect(mapStateToProps)(Conference);
| JavaScript | 0 | @@ -2055,32 +2055,265 @@
d(this);%0A %7D%0A%0A
+ /**%0A * Inits the toolbar timeout after the component is initially rendered.%0A *%0A * @inheritDoc%0A * returns %7Bvoid%7D%0A */%0A componentDidMount() %7B%0A this._setToolbarTimeout(this.state.toolbarVisible);%0A %7D%0A%0A
/**%0A * I
@@ -3058,58 +3058,8 @@
e;%0A%0A
- this._setToolbarTimeout(toolbarVisible);%0A%0A
@@ -5482,17 +5482,17 @@
sible -
-i
+I
ndicates
@@ -5547,24 +5547,47 @@
* @private%0A
+ * @returns %7Bvoid%7D%0A
*/%0A
|
35f13324050f3dea611c6e494d3d400066e205ee | update doc | api-doc.js | api-doc.js | /*
* Cut.js
* Copyright (c) 2013-2014 Ali Shakiba, Piqnt LLC and other contributors
* Available under the MIT license
* @license
*/
//
// ### Cut
//
// Create a new plain cut instance.
// No painting is associated with a plain cut, it is just a parent for other cuts.
var foo = Cut.create();
// Append/prepend bar, baz, ... to foo's children.
foo.append(bar, baz, etc);
foo.prepend(bar, baz, etc);
// Append/prepend bar to foo's children.
bar.appendTo(foo);
bar.prependTo(foo);
// Insert baz, qux, ... after/before bar.
bar.insertNext(baz, qux, etc);
bar.insertPrev(baz, qux, etc);
// Insert baz after/before bar.
baz.insertAfter(bar);
baz.insertBefore(bar);
// Remove bar from parent.
bar.remove();
// Remove bar, baz, ... from foo.
foo.remove(bar, baz, etc);
// Remove all foo's children.
foo.empty();
// Get foo first/last (visible) child.
foo.first(visible = false);
foo.last(visible = false);
// Get immediate parent.
bar.parent();
// Get bar next/prev (visible) sibling.
bar.next(visible = false);
bar.prev(visible = false);
// Get or set bar visiblity.
bar.visible();
bar.visible(visible);
bar.hide();
bar.show();
// Get or set single pinning value.
bar.pin(name);
bar.pin(name, value);
// Set one or more pinning values.
// If `nameX` equals `nameY`, `name` shorthand can be used instead.
// For relative values 0 is top/left and 1 is bottom/right.
bar.pin({
// Transparency applied to self and children.
alpha : "",
// Transparency applied to only to self textures.
textureAlpha : "",
scaleX : "",
scaleY : "",
skewX : "",
skewY : "",
rotation : "",
// Set automatically based on cut type, used for relative pinning values.
width : "",
height : "",
// Relative location on self used as scale/skew/rotation center.
pivotX : "",
pivotY : "",
// Relative location on self used for positioning .
handleX : "",
handleY : "",
// Relative location on parent used for positioning.
alignX : "",
alignY : "",
// Positioning offset in pixel.
offsetX : "",
offsetY : "",
// Scale and resize to width/height.
resizeMode : "", // "in"/"out"
resizeWidth : "",
resizeHeight : ""
});
// Ticker is called on ticking before every paint, it can be used to modify the
// cut.
foo.tick(ticker, beforeChildren = false);
// Register a type-listener to bar.
foo.listen(type, listener);
// Get type-listeners registered to bar.
foo.listeners(type);
// Call type-listeners with args.
foo.publish(type, args);
// Visit foo's sub-tree.
foo.visit({
start : function() {
return skipChildren ? true : false;
},
end : function() {
return stopVisit ? true : false;
},
reverse : reverseChildrenOrder ? true : false,
visible : onlyVisibleCuts ? true : false
});
// Rendering pauses unless/until at least one cut is touched directly or
// indirectly.
foo.touch();
//
// ### Row
//
// Create a new row.
// A row is a cut which organizes its children as a horizontal sequence.
var row = Cut.row(valign = 0);
//
// ### Column
//
// Create a new column.
// A column is a cut which organizes its children as a vertical sequence.
var column = Cut.column(halign = 0);
//
// ### Cut
//
// Create a new image instance.
// An image is a cut which pastes a cutout.
var image = Cut.image("textureName:cutoutName");
// Change image.
image.setImage("textureName:cutoutName");
// Crop image.
image.cropX(w, x = 0);
image.cropY(h, y = 0);
// Tile image to cover pin width and height. To define tile border use top,
// bottom, left and right with texture cutouts.
image.tile();
// Stretch image to cover pin width and height. To define stretch border use
// top, bottom, left and right with texture cutouts.
image.stretch();
//
// ### Anim(Clip)
//
// Create a new anim instance.
// An anim is a cut which have a set of cutouts and pastes a cutout at a time.
var anim = Cut.anim("textureName:cutoutPrefix", fps = Cut.Anim.FPS);
// Get or set anim fps.
anim.fps();
anim.fps(fps);
// Set anim cutouts.
anim.setFrames("textureName:cutoutPrefix");
anim.gotoFrame(n, resize = false);
anim.gotoLabel("cutoutName", resize = false);
anim.randomFrame();
anim.moveFrame(n);
anim.play(reset = false);
anim.stop(frame = null);
anim.repeat(repeat, callback = null);
//
// ### String
//
// Create a new string (sequence) instance.
// String is a row of anim cuts.
Cut.string("textureName:cutoutPrefix");
string.setFont("textureName:cutoutPrefix");
// set string value
string.setValue(value);
//
// ### Textures
//
// Register a texture, images are automatically loaded by Cut.Loader.
Cut.addTexture({
name : "",
imagePath : "",
imageRatio : "",
filter : "",
ratio : "",
cutouts : [ {
name : "",
x : "",
y : "",
width : "",
height : "",
// Optional, used by tile:
top : "",
bottom : "",
left : "",
right : ""
}, etc ]
}, etc);
//
// ### Loader
//
// Load an app with root node and container element.
Cut.Loader.load(function(root, container) {
// add cuts to root
foo.appendTo(root);
});
//
// ### Mouse(Touch)
//
// Subscribe the root to mouse/touch events.
Cut.Mouse.subscribe(root, container, includingMoveEvents = false);
// Add click listener to bar, other mouse/touch event types are start, end and
// move.
bar.listen(Cut.Mouse.CLICK, function(event, point) {
// point is relative to this cut
});
//
// ### Extending Cut
//
// Home extends Cut.
function Home() {
Home.prototype._super.apply(this, arguments);
// ...
}
Home.prototype = new Cut(Cut.Proto);
Home.prototype._super = Cut;
Home.prototype.constructor = Home;
Home.prototype.fun = function() {
// ...
};
| JavaScript | 0 | @@ -2024,24 +2024,123 @@
fsetY : %22%22,%0A
+ // Scale to width-height.%0A scaleMode : %22%22, // %22in%22/%22out%22%0A scaleWidth : %22%22,%0A scaleHeight : %22%22,%0A
// Scale a
@@ -2157,17 +2157,17 @@
to width
-/
+-
height.%0A
@@ -2238,16 +2238,17 @@
ght : %22%22
+,
%0A%7D);%0A%0A//
|
d60affeb1777864a576da2ed2303a602b5693c8a | disable recording of pos as I moved the records | app/app.js | app/app.js | 'use strict';
//
// Debug
//
const stringifyObject = require('stringify-object');
function pretty(data) {
return "<pre>" + stringifyObject(data) + "</pre>";
}
const os = require('os');
function running_on_pi() {
// very hacky way to determine
// better: https://github.com/fourcube/detect-rpi
return os.arch() === 'arm';
}
//
// Sub modules
//
const Config = require('./src/config.js');
const cache = require('./src/cache.js');
cache.init_discogs();
const DG = require('./src/discogs.js');
const searcher = require('./src/search.js');
//
// Express REST server
//
const express = require('express');
const app = express();
function get_pub_dir() {
return __dirname + '/public/';
}
app.use(express.static(get_pub_dir()));
// always have this ready
const fs = require('fs');
const templ_file = fs.readFileSync(get_pub_dir() + 'results.template.html', 'utf8');
//
// index routing & debug
//
app.get('/', function (req, res) {
res.sendFile('index.html', { root: get_pub_dir() });
});
app.get('/info', function (req, res) {
var info = {
client: Config.Discogs.UserAgent,
uptime: os.uptime(),
cpu: os.cpus(),
archicture: os.arch(),
type: os.type()
};
res.send(pretty(info));
});
//
// Direct Discogs queries
//
app.get('/all', function (req, res) {
res.send(pretty(DG.raw_col));
});
app.get('/detail/:id(\\d+)', function (req, res) {
DG.api_db.getRelease(req.params.id, function(err, data){
if (err) {
res.send(pretty(err));
return;
}
res.send(pretty(data));
});
});
app.get('/price', function(req, res) {
const cmd_market = require('./src/cmd_market.js');
cmd_market.price_of_box('box:4', res);
});
//
// Search
//
const cmd_search = require('./src/cmd_search.js');
app.get('/search', function (req, res) {
res.send(cmd_search.search_and_output(
req, templ_file, get_pub_dir(), running_on_pi()));
});
//
// Finder
//
const cmd_find = require('./src/cmd_find.js');
app.get('/find/:id(\\d+)', function (req, res) {
// if (!running_on_pi()) {
// res.send('Err: find can only run on the Raspberry Pi!');
// return;
// }
cmd_find(req, res);
});
//
// Play dialog and tracks
//
const lru = require('./src/lru.js');
const cmd_play = require('./src/cmd_play.js');
app.get('/play/:id(\\d+)', function (req, res) {
cmd_play(req, res);
});
//
// Sqlite local database
//
const db = function() {
const disable = process.argv.find(arg => arg === '--no-db');
return (disable) ? undefined : require('./src/sqlite.js');
}();
app.get('/db-create', function (req, res) {
db.create();
res.send("Creating database...");
});
//
// Heatmap visualization
//
const cmd_heatmap = require('./src/cmd_heatmap.js');
app.get('/heatmap', function (req, res) {
res.sendFile('heatmap.html', { root: get_pub_dir() });
});
app.get('/heatmap-draw', function (req, res) {
cmd_heatmap.draw(db, res);
});
//
// Last.fm
//
const last_fm = function() {
const disable = process.argv.find(arg => arg === '--no-lastfm');
return (disable) ? undefined : require('./src/last_fm.js');
}();
app.get('/last.fm/:id(\\d+)/:choice/:side', function (req, res) {
var choice = req.params.choice;
var side = req.params.side;
var to_submit = lru.filter(choice, side);
if (!to_submit) {
res.send('invalid request');
return;
}
lru.adjust_track_times(to_submit);
// debug
//res.send(pretty(to_submit));
//return;
var entry = DG.find_by_id(req.params.id);
if (!entry) {
res.send('invalid request');
return;
}
if (db) {
var info = {
$release: entry.id,
$timestamp: lru.timestamp(),
$shelf_id: DG.get_shelf_id(entry),
$shelf_pos: DG.get_shelf_pos(entry),
$cmd: choice,
$track_data: stringifyObject(to_submit)
};
db.add(info);
}
if (last_fm) {
last_fm.scrobble(to_submit, res);
} else {
res.send('Last.fm disabled');
}
});
//
// Main
//
console.log("Starting...");
function start_server(){
app.listen(Config.Server.Port, function () {
console.log('Listening on ' + Config.Server.Port + '...');
});
}
DG.load(function () {
searcher.init_search(DG.raw_col);
start_server();
});
| JavaScript | 0 | @@ -3770,24 +3770,89 @@
imestamp(),%0A
+ // disable as I moved them around and bought new shelves%0A
@@ -3862,16 +3862,22 @@
elf_id:
+-1, //
DG.get_s
@@ -3916,16 +3916,22 @@
lf_pos:
+-1, //
DG.get_s
@@ -3939,32 +3939,45 @@
elf_pos(entry),%0A
+ ////%0A
$cmd
|
c42e5d95d411cb4770ac99897fc1386d2433c953 | step 5.1 - events | app/app.js | app/app.js | var Container = React.createClass({
getInitialState: function(){
return {
title: this.props.title
}
},
handleClick: function(){
this.setState({title: 'Updated title'});
},
render: function() {
return (
<div>
<h1>{this.state.title}</h1>
<button onClick={this.handleClick}>Change title</button>
</div>
);
}
});
React.render(
<Container title='Hello react' />,
document.getElementById('container')
); | JavaScript | 0.999868 | @@ -102,16 +102,45 @@
ps.title
+,%0A newTitle: 'new title'
%0A %7D%0A
@@ -201,23 +201,117 @@
le:
-'Updated title'
+this.state.newTitle%7D);%0A %7D,%0A handleChange: function(event) %7B%0A this.setState(%7BnewTitle: event.target.value
%7D);%0A
@@ -399,16 +399,102 @@
e%7D%3C/h1%3E%0A
+ %3Cinput type=%22text%22 value=%7Bthis.state.newTitle%7D onChange=%7Bthis.handleChange%7D/%3E%0A
|
6bf2b2c9dfd52b83ca6a580b257021e27971a010 | Update app.js | app/app.js | app/app.js | /*jshint esversion: 6 */
'use strict';
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var CronJob = require('cron').CronJob;
var SUNLIGHT_APIKEY = 'd9eeb169a7224fe28ae0f32aca0dc93e';
var LEGISTLATOR_URL = 'http://congress.api.sunlightfoundation.com/legislators';
var BILL_URL = 'http://congress.api.sunlightfoundation.com/bills?fields=official_title,urls.congress,sponsor_id,cosponsor_ids';
var BILL_RANGE = '&bill_id__in=sconres38-114|hconres88-114|s2426-114|hr4154-114|hr1853-114|hconres76-114|s1683-113|hres494-113|hjres109-113|sjres31-113|hconres55-113|hconres46-113|hr1151-113|s579-113|hres185-113|hconres29-113|s12-113|hr419-113';
var routes = require('./routes/index');
var users = require('./routes/users');
var candidates = require('./routes/candidates');
var bills = require('./routes/bills');
var sunlight_legislator = require('./modules/sunlight_legislator');
var PORT = 8080;
var app = express();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('../db/db.sqlite3');
db.serialize(function() {
db.run('CREATE TABLE IF NOT EXISTS candidates(' +
'firstName TEXT, ' +
'lastName TEXT, ' +
'party TEXT, ' +
'chamber TEXT, ' +
'state TEXT, ' +
'district INT, ' +
'incumbent BOOLEAN, ' +
'bioguideId TEXT,' +
'fecId TEXT,' +
'website TEXT,' +
'email TEXT,' +
'facebook TEXT,' +
'twitter TEXT,' +
'youtube TEXT,' +
'note BLOB' +
')');
db.run('CREATE TABLE IF NOT EXISTS bills(' +
'billId TEXT, ' +
'officialTitle BLOB, ' +
'sponsorId TEXT, ' +
'url TEXT' +
')');
db.run('CREATE TABLE IF NOT EXISTS cosponsors_bills(' +
'cid INTEGER PRIMARY KEY ASC, ' +
'cosponsorId TEXT REFERENCES candidates (bioguideId), ' +
'billId TEXT REFERENCES bills (billId)' +
')');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/candidates', candidates);
app.use('/bills', bills);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(PORT);
module.exports = app;
| JavaScript | 0 | @@ -360,40 +360,16 @@
= '
-d9eeb169a7224fe28ae0f32aca0dc93e
+%5Bapikey%5D
';%0D%0A
|
a9c61ff2c371dffb163ae90b29a98b59aa228a50 | remove menu from login page | app/app.js | app/app.js | 'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.logout',
'myApp.login',
'myApp.patients',
'myApp.EditPatients',
'myApp.captureform',
'myApp.thankyou',
'myApp.users',
'myApp.AddUsers',
'myApp.version',
'ui.bootstrap.datetimepicker'
])
.factory('httpRequestInterceptor', '$rootScope', '$location', function ($rootScope, $location) {
return {
request: function (config) {
config.headers['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.tokenid;
config.headers['Page'] = $location.path();
config.headers['Accept'] = 'application/json;odata=verbose';
return config;
}
};
})
.config(['$locationProvider', '$routeProvider', '$httpProvider', '$resourceProvider', function($locationProvider, $routeProvider, $httpProvider, $resourceProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/captureform'});
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = false;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
}])
.factory('Sessions', ['$resource', function($resource) {
return $resource( '/sessions/:_id', null,
{
'update': { method:'PUT' }
});
}])
.run(['$rootScope', '$location', '$cookieStore', '$http', 'Sessions', '$resource', function ($rootScope, $location, $cookieStore, $http, Sessions, $resource) {
$rootScope.globals = $cookieStore.get('globals') || {};
$http.defaults.headers.common['Page'] = $location.path();
if($location.path() == '') {
$location.path('/captureform');
}
// keep user logged in after page refresh
if ($rootScope.globals.currentUser) {
$http.defaults.headers.common['Authorization'] = $rootScope.globals.currentUser.tokenid; // jshint ignore:line
}
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var restrictedPage = $.inArray($location.path(), ['/captureform', '/thankyou', '/users/add']) === -1;
if(restrictedPage && $rootScope.globals.currentUser) {
$resource('/sessions/:_id', { _id: $rootScope.globals.currentUser.tokenid}).get(function(result) {
var givenTime = moment(result.logindate);
var d = new Date() ;
d.setTime( d.getTime() - new Date().getTimezoneOffset()*60*1000 );
var minutesPassed = moment(d).diff(givenTime, "minutes");
if(result._id == $rootScope.globals.currentUser.tokenid && minutesPassed > 15) {
Sessions.update({ _id: $rootScope.globals.currentUser.tokenid }, { expired: 'Y'});
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic';
$location.path('/login');
}
});
}
// redirect to login page if not logged in and trying to access a restricted page
var loggedIn = $rootScope.globals.currentUser;
if (restrictedPage && !loggedIn) {
$location.path('/login');
}
});
}
]); | JavaScript | 0.000001 | @@ -2229,16 +2229,181 @@
) %7B%0A%09%09%09%0A
+%09%09%09var nomenuPage = $.inArray($location.path(), %5B '/login', '/logout'%5D) %3E -1;%0A%09%09%09if(nomenuPage) %7B%0A%09%09%09%09$('.menu').hide();%0A%09%09%09%7D else %7B%0A%09%09%09%09$('.menu').show();%0A%09%09%09%7D%0A%09%09%09%0A
%09%09%09var r
@@ -2478,22 +2478,8 @@
you'
-, '/users/add'
%5D) =
|
6284bd3f177b0b45dbc1e92fe76a6d5e811e4794 | Remove an unecessary console.log(). | app/app.js | app/app.js | // Must be loaded before angular.
import 'angular-file-upload'
import angular from 'angular'
import uiBootstrap from'angular-ui-bootstrap'
import uiIndeterminate from'angular-ui-indeterminate'
import uiRouter from'angular-ui-router'
import uiSelect from'angular-ui-select'
import naturalSort from 'angular-natural-sort'
import xeditable from 'angular-xeditable'
import xoDirectives from 'xo-directives'
import xoFilters from 'xo-filters'
import xoServices from 'xo-services'
import aboutState from './modules/about'
import consoleState from './modules/console'
import deleteVmsState from './modules/delete-vms'
import genericModalState from './modules/generic-modal'
import hostState from './modules/host'
import listState from './modules/list'
import navbarState from './modules/navbar'
import newSrState from './modules/new-sr'
import newVmState from './modules/new-vm'
import poolState from './modules/pool'
import schedulerState from './modules/scheduler'
import settingsState from './modules/settings'
import dashboardState from './modules/dashboard'
import srState from './modules/sr'
import treeState from './modules/tree'
import updater from './modules/updater'
import vmState from './modules/vm'
import '../dist/bower_components/angular-chart.js/dist/angular-chart.js'
// ===================================================================
console.log('done')
export default angular.module('xoWebApp', [
uiBootstrap,
uiIndeterminate,
uiRouter,
uiSelect,
naturalSort,
xeditable,
xoDirectives,
xoFilters,
xoServices,
aboutState,
consoleState,
dashboardState,
deleteVmsState,
genericModalState,
hostState,
listState,
navbarState,
newSrState,
newVmState,
poolState,
schedulerState,
settingsState,
srState,
treeState,
updater,
vmState,
'chart.js'
])
// Prevent Angular.js from mangling exception stack (interfere with
// source maps).
.factory('$exceptionHandler', () => function (exception) {
throw exception
})
.config(function (
$compileProvider,
$stateProvider,
$urlRouterProvider,
$tooltipProvider,
uiSelectConfig
) {
// Disable debug data to improve performance.
//
// In case of a bug, simply use `angular.reloadWithDebugInfo()` in
// the console.
//
// See https://docs.angularjs.org/guide/production
$compileProvider.debugInfoEnabled(false)
// Redirect to default state.
$stateProvider.state('index', {
url: '/',
controller: function ($state, xoApi) {
let isAdmin = xoApi.user && (xoApi.user.permission === 'admin')
$state.go(isAdmin ? 'tree' : 'list')
}
})
// Redirects unmatched URLs to `/`.
$urlRouterProvider.otherwise('/')
// Changes the default settings for the tooltips.
$tooltipProvider.options({
appendToBody: true,
placement: 'bottom'
})
uiSelectConfig.theme = 'bootstrap'
uiSelectConfig.resetSearchInput = true
})
.run(function (
$anchorScroll,
$rootScope,
$state,
editableOptions,
editableThemes,
notify,
updater,
xoApi
) {
$rootScope.$watch(() => xoApi.user, (user, previous) => {
// The user just signed in.
if (user && !previous) {
$state.go('index')
}
})
$rootScope.$on('$stateChangeStart', function (event, state, stateParams) {
const {user} = xoApi
if (!user) {
event.preventDefault()
return
}
if (user.permission === 'admin') {
return
}
// Some pages requires the admin permission.
if (state.data && state.data.requireAdmin) {
event.preventDefault()
notify.error({
title: 'Restricted area',
message: 'You do not have the permission to view this page'
})
}
let {id} = stateParams
if (id && !xoApi.canAccess(id)) {
event.preventDefault()
notify.error({
title: 'Restricted area',
message: 'You do not have the permission to view this page'
})
}
})
// Work around UI Router bug (https://github.com/angular-ui/ui-router/issues/1509)
$rootScope.$on('$stateChangeSuccess', function () {
$anchorScroll()
})
editableThemes.bs3.inputClass = 'input-sm'
editableThemes.bs3.buttonsClass = 'btn-sm'
editableOptions.theme = 'bs3'
})
.name
| JavaScript | 0.000009 | @@ -1352,27 +1352,8 @@
===%0A
-console.log('done')
%0Aexp
|
1c42c909da0c0771bc25a9228e729fc0d09fd251 | Update app.js | app/app.js | app/app.js | angular
.module('app', ['nzTour','ngMaterial', 'ui.codemirror', 'ngMdIcons'])
.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('orange');
})
.directive('menuKey', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
var keyCode = event.which || event.keyCode;
// If enter key is pressed
if (keyCode === 27) {
scope.$apply(function() {
// Evaluate the expression
scope.$eval(attrs.menuKey);
});
event.preventDefault();
}
});
};
})
;
| JavaScript | 0.000002 | @@ -1,225 +1,4 @@
-angular%0A .module('app', %5B'nzTour','ngMaterial', 'ui.codemirror', 'ngMdIcons'%5D)%0A .config(function($mdThemingProvider) %7B%0A $mdThemingProvider.theme('default')%0A .primaryPalette('blue')%0A .accentPalette('orange');%0A %7D)
%0A .
|
8210485ddce9bde543a5a9f61c1a63fd25962320 | Check that findOne, updateOne and deleteOne do not use JSL in filter.id | src/middleware/validation/client_input_syntax.js | src/middleware/validation/client_input_syntax.js | 'use strict';
const { set, merge, mergeWith } = require('lodash');
const { validate } = require('../../utilities');
/**
* Check API input, for client-side errors (e.g. 400)
* Only checks basic input according to current action
* In a nutshell, checks that:
* - required attributes are defined
* - disabled attributes are not defined
* - `filter` is an object, `data` is an array or object (depending on action)
* - `order_by` syntax looks valid (does not check whether it is semantically correct)
**/
const validateClientInputSyntax = function ({ modelName, action, args }) {
const type = 'clientInputSyntax';
const schema = getValidateClientSchema({ action });
validate({ schema, data: args, reportInfo: { type, action, modelName } });
};
// Builds JSON schema to validate against
const getValidateClientSchema = function({ action }) {
const rule = rules[action];
const properties = getProperties({ rule });
const requiredProperties = getRequiredProps(rule.required);
const forbiddenProperties = getForbiddenProperties({ rule });
const schema = merge({ type: 'object', additionalProperties: false }, properties, requiredProperties, forbiddenProperties);
return schema;
};
// Get properties to check against, as JSON schema, for a given action
const getProperties = function ({ rule }) {
return validateClientSchema
// Whitelists input according to `allowed` or `required`
.filter(({ name }) => rule.allowed.includes(name) || rule.required.includes(name))
.map(({ name, value }) => {
// Fire value functions
value = typeof value === 'function' ? value(rule) : value;
// Use `properties` JSON schema syntax
name = 'properties.' + name.replace(/\./g, '.properties.');
return { name, value };
})
// Handles 'VAR.VAR2' dot-delimited syntax
.reduce((props, { name, value }) => set(props, name, value), {});
};
// JSON schemas applied to input
const validateClientSchema = [
{ name: 'data', value: ({ dataMultiple }) => !dataMultiple ? { type: 'object' } : { type: 'array', items: { type: 'object' } } },
{ name: 'filter', value: { type: 'object' } },
{ name: 'filter.id', value: {} },
// Matches order_by value, i.e. 'ATTR[+|-],...'
{ name: 'order_by', value: { type: 'string', pattern: '^([a-z0-9_]+[+-]?)(,[a-z0-9_]+[+-]?)*$' } },
];
// Transform required properties into JSON schema
// E.g. ['filter', 'filter.var', 'filter.var.vat']
// to { required: ['filter'], properties: { filter: { required: ['var'], properties: { var: { required: ['vat'] } } } } }
const getRequiredProps = function (props) {
// E.g. can be ['filter', 'filter.var', 'filter.var.vat']
return props
// E.g. this could transform to ['filter', 'properties.filter.var', 'properties.filter.properties.var.vat']
.map(requiredProp => {
const parts = requiredProp.split('.');
return parts
.reduce((memo, part, index) => memo
.concat(index === parts.length - 1 ? [] : 'properties')
.concat(part),
[])
.join('.')
// Allow using syntax like `data.*.id` when `data` is an array
.replace('properties.*', 'items');
})
// E.g. this could transform to [{ required: ['filter'] }, { properties: { filter: { required: ['var'] } } },
// { properties: { filter: { properties: { var: { required: ['vat'] } } } } }]
.map(requiredProp => {
const value = [requiredProp.replace(/.*\./, '')];
const path = requiredProp.replace(/[^.]+$/, 'required');
return set({}, path, value);
})
// Merge array of objects into single object
.reduce((memo, value) => mergeWith(memo, value, (obj, src) => obj instanceof Array ? obj.concat(src) : undefined), {});
};
// Add JSON schema forbidding properties
// E.g. `data.id` becomes { properties: { data: { properties: { id: false } } } }
// Only required for nested properties, since `allowed` is whitelisting
const getForbiddenProperties = function ({ rule: { forbidden = [] } }) {
return forbidden
.map(forbiddenProp => 'properties.' + forbiddenProp.replace(/\./g, '.properties.'))
.map(path => set({}, path, false))
.reduce(merge, {});
};
/**
* List of rules for allowed|required attributes, according to the current action
* `required` implies `allowed`
* `dataSingle` is `data` as object, `dataMultiple` is `data` as array.
**/
/* eslint-disable key-spacing, no-multi-spaces */
const rules = {
findOne: { allowed: [], required: ['filter', 'filter.id'], },
findMany: { allowed: ['filter', 'filter.id', 'order_by'], required: [], },
deleteOne: { allowed: [], required: ['filter', 'filter.id'] },
deleteMany: { allowed: ['filter', 'filter.id', 'order_by'], required: [], },
updateOne: { allowed: [], required: ['data', 'filter', 'filter.id'],
forbidden: ['data.id'] },
updateMany: { allowed: ['filter', 'filter.id', 'order_by'], required: ['data'],
forbidden: ['data.id'] },
upsertOne: { allowed: [], required: ['data', 'data.id'] },
upsertMany: { allowed: ['order_by'], required: ['data', 'data.*.id'],
dataMultiple: true },
replaceOne: { allowed: [], required: ['data', 'data.id'] },
replaceMany: { allowed: ['order_by'], required: ['data', 'data.*.id'],
dataMultiple: true },
createOne: { allowed: [], required: ['data'] },
createMany: { allowed: ['order_by'], required: ['data'],
dataMultiple: true },
};
/* eslint-enable key-spacing, no-multi-spaces */
module.exports = {
validateClientInputSyntax,
};
| JavaScript | 0 | @@ -2167,16 +2167,91 @@
, value:
+ (%7B isNotJslFilterId %7D) =%3E isNotJslFilterId ? %7B not: %7B type: 'object' %7D %7D :
%7B%7D %7D,%0A
@@ -4604,16 +4604,119 @@
er.id'%5D,
+%0A isNotJslFilterId: true
@@ -4802,33 +4802,33 @@
required: %5B%5D
-,
+
@@ -4952,24 +4952,127 @@
'filter.id'%5D
+,%0A isNotJslFilterId: true
@@ -5159,25 +5159,25 @@
required: %5B%5D
-,
+
@@ -5337,39 +5337,39 @@
-
+isNotJslFilterId: true,
|
e87038fac47d650475c1ecabbc7fbc075670fb15 | Fix for #38 | script/contest-admin.js | script/contest-admin.js | /**************************************
* Script for contest admin dashboard *
**************************************/
var defaultHash = "overview";
/**
* On document ready
*/
$(document).ready(function(){
// Add a listener if hash is changed
$(window).bind('hashchange', function() {
chooseWindow();
});
if (!window.location.hash) {
// If hash is not present in the URL add default hash
window.location.hash = defaultHash;
} else {
// If hash is already present in the URL
chooseWindow();
}
// To handle the reset password form
$("#reset-pass-form").submit(function(e){
e.preventDefault();
$("#pass-reset-btn").val("Please wait...");
$.ajax({
method: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
dataType: "json",
success: function(data) {
$("#pass-reset-btn").val("Submit");
if (data.status == false) {
alert(data.error);
} else {
alert(data.message);
$("#old-password").val('');
$("#new-password").val('');
$("#cnew-password").val('');
}
}
});
});
// To handle challenge addition ajax events
$(".checkbox").click(function(){
var tr = $(this).parents("tr");
var challenge = tr.find(".challenge").html();
var name = tr.find("input[name='name']").val();
var points = tr.find("input[name='points']").val();
var flag = tr.find("input[name='flag']").val();
tr.addClass("success");
$.ajax({
method: "POST",
url: addChallengeURL,
data: "challenge="+challenge+"&name="+name+"&points="+points+"&flag="+flag,
success: function() {
tr.fadeOut(200);
}
});
});
});
/**
* Function to display the required window
*/
function chooseWindow()
{
var hashInUrl = window.location.hash.substr(1);
$("#side-nav").find("li.active").removeClass("active");
hidePrevious(); // Hide all previous divs
switch (hashInUrl) {
case "overview":
showOverview();
break;
case "reports":
showReports();
break;
case "analytics":
showAnalytics();
break;
case "users":
showUsers();
break;
case "challenges":
showChallenges();
break;
case "settings":
showSettings();
break;
default:
window.location.hash = defaultHash;
showOverview();
break;
}
}
/**
* Function to hide all the divs within #main-content
*/
function hidePrevious()
{
$("#main-content").children().each(function(){
if (!$(this).hasClass("hidden")) {
$(this).addClass("hidden");
}
});
}
/**
* To display overview page
*/
function showOverview()
{
$("#heading").html("Welcome admin!");
$("#overview").addClass("active");
$("#overview-content").removeClass("hidden");
}
/**
* To display reports page
*/
function showReports()
{
$("#heading").html("Reports");
$("#reports").addClass("active");
$("#reports-content").removeClass("hidden");
}
/**
* To display analytics page
*/
function showAnalytics()
{
$("#heading").html("Analytics");
$("#analytics").addClass("active");
$("#analytics-content").removeClass("hidden");
}
/**
* To display Users page
*/
function showUsers()
{
$("#heading").html("Users");
$("#users").addClass("active");
$("#users-content").removeClass("hidden");
}
/**
* To display challenge page
*/
function showChallenges()
{
$("#heading").html("Challenges");
$("#challenges").addClass("active");
$("#challenges-content").removeClass("hidden");
}
/**
* To display account settings
*/
function showSettings()
{
$("#heading").html("Account Settings");
$("#account-settings").addClass("active");
$("#account-settings-content").removeClass("hidden");
}
| JavaScript | 0 | @@ -1667,24 +1667,463 @@
%5D%22).val();%0A%0A
+ if (challenge === '') %7B%0A alert(%22Invalid request%22);%0A return false;%0A %7D else if(name === '') %7B%0A alert(%22Please input name of challenge%22);%0A return false;%0A %7D else if(!$.isNumeric(points)) %7B%0A alert(%22Please input points (int only)%22);%0A return false;%0A %7D else if(flag === '') %7B%0A alert(%22Please input Flag%22);%0A return false;%0A %7D%0A%0A
tr.a
|
b0d77329f04817cae795b1a0b7c542abdc3dbdb6 | update protractor settings | protractor.conf.js | protractor.conf.js | exports.config = {
baseUrl: 'http://localhost:8080/',
specs: [
'src/**/*.e2e-spec.js'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
onPrepare: function () {
var SpecReporter = require('jasmine-spec-reporter');
// add jasmine spec reporter
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = true;
},
/**
* Angular 2 configuration
*
* useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
* `rootEl`
*
*/
useAllAngular2AppRoots: true,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
// restartBrowserBetweenTests: true,
multiCapabilities: [{
'browserName': 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'platform': 'OS X 10.11',
'version': '48'
}],
onComplete: function() {
var printSessionId = function(jobName){
browser.getSession().then(function(session) {
console.log('SauceOnDemandSessionID=' + session.getId() + ' job-name=' + jobName);
});
};
printSessionId("wind-ng");
}
};
| JavaScript | 0 | @@ -44,17 +44,17 @@
host:808
-0
+1
/',%0A%0A s
|
b9ac1dbc99e17a08a2cb42eebd3db606b8dd0b01 | Exclude vector layers from featureInfo directive | src/modules/featureinfo/featureinfo-directive.js | src/modules/featureinfo/featureinfo-directive.js | angular.module('anol.featureinfo')
/**
* @ngdoc directive
* @name anol.featureinfo.directive:anolFeatureInfo
*
* @restrict A
* @requires $compile
* @requires $http
* @required $window
* @requires anol.map.MapService
* @requires anol.map.LayersService
*
* @description
* Makes GetFeatureInfo request on all layers with 'getFeatureInfo' property
* and show result depending on 'target' specified in 'getFeatureInfo'
*
* Layer property **getFeatureInfo** - {Object} - Contains properties:
* - **target** - {string} - Target for getFeatureInfo result. ('_blank', '_popup', [element-id])
*/
.directive('anolFeatureInfo', ['$compile', '$http', '$window', 'MapService', 'LayersService', function($compile, $http, $window, MapService, LayersService) {
return {
restrict: 'A',
require: '?^anolMap',
replace: true,
scope: {},
templateUrl: 'src/modules/featureinfo/templates/popup.html',
link: {
pre: function(scope, element) {
$compile(element.contents())(scope);
scope.map = MapService.getMap();
var view = scope.map.getView();
var popupContent = element.find('#popup-content');
var popupOverlay = new ol.Overlay({
element: element.context,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
scope.map.addOverlay(popupOverlay);
scope.handlePopupClose = function() {
element.css('display', 'none');
};
scope.handleClick = function(evt) {
var viewResolution = view.getResolution();
var coordinate = evt.coordinate;
var divTargetCleared = false;
element.css('display', 'none');
popupContent.empty();
angular.forEach(LayersService.layers, function(layer) {
var layers = [layer];
if(layer instanceof ol.layer.Group) {
layers = layer.getLayersArray();
}
angular.forEach(layers, function(layer) {
if(!layer.getVisible()) {
return;
}
var featureInfo = layer.get('featureinfo');
if(angular.isUndefined(featureInfo)) {
return;
}
var url = layer.getSource().getGetFeatureInfoUrl(
coordinate, viewResolution, view.getProjection(),
{'INFO_FORMAT': 'text/html'}
);
if(angular.isDefined(url)) {
$http.get(url).success(function(response) {
if(angular.isString(response) && response !== '' && !response.startsWith('<?xml')) {
var iframe;
if(featureInfo.target !== '_blank') {
iframe = $('<iframe seamless src="' + url + '"></iframe>');
}
switch(featureInfo.target) {
case '_blank':
$window.open(url, '_blank');
break;
case '_popup':
popupContent.append(iframe);
if(element.css('display') === 'none') {
element.css('display', '');
popupOverlay.setPosition(coordinate);
}
break;
default:
var target = $(featureInfo.target);
if(divTargetCleared === false) {
target.empty();
divTargetCleared = true;
}
target.append(iframe);
break;
}
}
});
}
});
});
};
},
post: function(scope) {
scope.map.on('singleclick', scope.handleClick, this);
}
}
};
}]);
| JavaScript | 0 | @@ -2409,32 +2409,169 @@
%7D%0A
+ if(layer instanceof ol.layer.Vector) %7B%0A return;%0A %7D%0A
|
b0e5c4b6affd5939014ed138f970a05624376e29 | Store appx in out folder | script/windows-store.js | script/windows-store.js | const ChildProcess = require('child_process')
const path = require('path')
const version = require('../package').version + '.0'
const command = path.join(__dirname, '..', 'node_modules', '.bin', 'electron-windows-store.cmd')
const args = [
'--input-directory',
path.join(__dirname, '..', 'out', 'ElectronAPIDemos-win32-ia32'),
'--output-directory',
path.join(__dirname, '..', 'windows-store'),
'--flatten',
true,
'--package-version',
version,
'--package-name',
'ElectronAPIDemos'
]
const windowsStore = ChildProcess.spawn(command, args, {stdio: 'inherit'})
windowsStore.on('close', (code) => {
process.exit(code)
})
| JavaScript | 0.000001 | @@ -378,16 +378,23 @@
e, '..',
+ 'out',
'window
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.