mirror of
https://github.com/RussellChamp/tilde-projects.git
synced 2026-10-28 00:22:34 +00:00
Just some new banterbot trick and changes and things
This commit is contained in:
1 parent
10d2aef8d0
commit
5bd1f60a0b
24 files changed
+784
-40
No files matched your search
+42
-2
@@ -19,6 +19,10 @@ from rhymesWith import getRhymes
|
||||
from rhymesWith import rhymeZone
|
||||
from defineWord import defWord
|
||||
from rainbow import makeRainbow
|
||||
import welch
|
||||
import evil
|
||||
import tumblr
|
||||
import xkcdApropos
|
||||
|
||||
parser = OptionParser()
|
||||
|
||||
@@ -129,14 +133,35 @@ def define_word(channel, user, text):
|
||||
ircsock.send("PRIVMSG " + channel + " :" + user + ": Couldn't find the definition of '" + word + "' :(\n")
|
||||
else:
|
||||
for entry in defs:
|
||||
ircsock.send("PRIVMSG " + channel + " :" + user + ": Define '" + word + "'" + entry[0:200] + "\n")
|
||||
ircsock.send("PRIVMSG " + channel + " :" + user + ": Define '" + word + "'" + entry[0:400] + "\n")
|
||||
|
||||
def make_rainbow(channel, user, text):
|
||||
rbword = makeRainbow(text[9:])
|
||||
ircsock.send("PRIVMSG " + channel + " :" + rbword + "\n")
|
||||
|
||||
def get_welch(channel):
|
||||
ircsock.send("PRIVMSG " + channel + " :" + welch.get_thing()[0:400] + "\n")
|
||||
|
||||
def get_evil(channel):
|
||||
evilThing = evil.get_thing();
|
||||
for line in [evilThing[i:i+400] for i in range(0, len(evilThing), 400)]:
|
||||
ircsock.send("PRIVMSG " + channel + " :" + line + "\n")
|
||||
|
||||
def get_tumble(url, channel):
|
||||
tumble = tumblr.tumble(url)
|
||||
for line in [tumble[i:i+400] for i in range(0, len(tumble), 400)]:
|
||||
ircsock.send("PRIVMSG " + channel + " :" + line + "\n")
|
||||
|
||||
def get_xkcd(channel, text):
|
||||
links = xkcdApropos.xkcd_links(text[6:])
|
||||
joined_links = ', '.join(links)
|
||||
for line in [joined_links[i:i+400] for i in range(0, len(joined_links), 400)]:
|
||||
ircsock.send("PRIVMSG " + channel + " :" + line + "\n")
|
||||
#res = xkcdApropos.xkcd(text[6:])
|
||||
#ircsock.send("PRIVMSG " + channel + " :" + res + "\n")
|
||||
|
||||
def rollcall(channel):
|
||||
ircsock.send("PRIVMSG "+ channel +" :U wot m8? I score all the top drawer #banter and #bantz on this channel! Find new top-shelf banter with !newbanter, !rhymes, and !define. Make your chatter #legend with !rainbow\n")
|
||||
ircsock.send("PRIVMSG "+ channel +" :U wot m8? I score all the top drawer #banter and #bantz on this channel! Find new top-shelf banter with !newbanter, !rhymes, and !define. Make your chatter #legend with !rainbow and get jokes with !welch and !evil\n")
|
||||
|
||||
def connect(server, channel, botnick):
|
||||
ircsock.connect((server, 6667))
|
||||
@@ -192,6 +217,21 @@ def listen():
|
||||
if ircmsg.find(":!rainbow") != -1:
|
||||
make_rainbow(channel, user, messageText)
|
||||
|
||||
if ircmsg.find("!welch") != -1:
|
||||
get_welch(channel)
|
||||
|
||||
if ircmsg.find("!evil") != -1:
|
||||
get_evil(channel)
|
||||
|
||||
if ircmsg.find("!kjp") != -1:
|
||||
get_tumble('http://kingjamesprogramming.tumblr.com', channel)
|
||||
|
||||
if ircmsg.find("!help") != -1:
|
||||
get_tumble('http://thedoomthatcametopuppet.tumblr.com', channel)
|
||||
|
||||
if ircmsg.find("!xkcd") != -1:
|
||||
get_xkcd(channel, messageText)
|
||||
|
||||
if ircmsg.find(":!rollcall") != -1:
|
||||
rollcall(channel)
|
||||
|
||||
|
||||
Executable
+179
@@ -0,0 +1,179 @@
|
||||
import urllib
|
||||
import urllib2
|
||||
import json as j
|
||||
import sys
|
||||
|
||||
__version__ = 0.242
|
||||
|
||||
|
||||
def query(query, useragent='python-duckduckgo '+str(__version__), safesearch=True, html=False, meanings=True, **kwargs):
|
||||
"""
|
||||
Query DuckDuckGo, returning a Results object.
|
||||
|
||||
Here's a query that's unlikely to change:
|
||||
|
||||
>>> result = query('1 + 1')
|
||||
>>> result.type
|
||||
'nothing'
|
||||
>>> result.answer.text
|
||||
'1 + 1 = 2'
|
||||
>>> result.answer.type
|
||||
'calc'
|
||||
|
||||
Keword arguments:
|
||||
useragent: UserAgent to use while querying. Default: "python-duckduckgo %d" (str)
|
||||
safesearch: True for on, False for off. Default: True (bool)
|
||||
html: True to allow HTML in output. Default: False (bool)
|
||||
meanings: True to include disambiguations in results (bool)
|
||||
Any other keyword arguments are passed directly to DuckDuckGo as URL params.
|
||||
""" % __version__
|
||||
|
||||
safesearch = '1' if safesearch else '-1'
|
||||
html = '0' if html else '1'
|
||||
meanings = '0' if meanings else '1'
|
||||
params = {
|
||||
'q': query,
|
||||
'o': 'json',
|
||||
'kp': safesearch,
|
||||
'no_redirect': '1',
|
||||
'no_html': html,
|
||||
'd': meanings,
|
||||
}
|
||||
params.update(kwargs)
|
||||
encparams = urllib.urlencode(params)
|
||||
url = 'http://api.duckduckgo.com/?' + encparams
|
||||
|
||||
request = urllib2.Request(url, headers={'User-Agent': useragent})
|
||||
response = urllib2.urlopen(request)
|
||||
json = j.loads(response.read())
|
||||
response.close()
|
||||
|
||||
return Results(json)
|
||||
|
||||
|
||||
class Results(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.type = {'A': 'answer', 'D': 'disambiguation',
|
||||
'C': 'category', 'N': 'name',
|
||||
'E': 'exclusive', '': 'nothing'}.get(json.get('Type',''), '')
|
||||
|
||||
self.json = json
|
||||
self.api_version = None # compat
|
||||
|
||||
self.heading = json.get('Heading', '')
|
||||
|
||||
self.results = [Result(elem) for elem in json.get('Results',[])]
|
||||
self.related = [Result(elem) for elem in
|
||||
json.get('RelatedTopics',[])]
|
||||
|
||||
self.abstract = Abstract(json)
|
||||
self.redirect = Redirect(json)
|
||||
self.definition = Definition(json)
|
||||
self.answer = Answer(json)
|
||||
|
||||
self.image = Image({'Result':json.get('Image','')})
|
||||
|
||||
|
||||
class Abstract(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.html = json.get('Abstract', '')
|
||||
self.text = json.get('AbstractText', '')
|
||||
self.url = json.get('AbstractURL', '')
|
||||
self.source = json.get('AbstractSource')
|
||||
|
||||
class Redirect(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.url = json.get('Redirect', '')
|
||||
|
||||
class Result(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.topics = json.get('Topics', [])
|
||||
if self.topics:
|
||||
self.topics = [Result(t) for t in self.topics]
|
||||
return
|
||||
self.html = json.get('Result')
|
||||
self.text = json.get('Text')
|
||||
self.url = json.get('FirstURL')
|
||||
|
||||
icon_json = json.get('Icon')
|
||||
if icon_json is not None:
|
||||
self.icon = Image(icon_json)
|
||||
else:
|
||||
self.icon = None
|
||||
|
||||
|
||||
class Image(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.url = json.get('Result')
|
||||
self.height = json.get('Height', None)
|
||||
self.width = json.get('Width', None)
|
||||
|
||||
|
||||
class Answer(object):
|
||||
|
||||
def __init__(self, json):
|
||||
self.text = json.get('Answer')
|
||||
self.type = json.get('AnswerType', '')
|
||||
|
||||
class Definition(object):
|
||||
def __init__(self, json):
|
||||
self.text = json.get('Definition','')
|
||||
self.url = json.get('DefinitionURL')
|
||||
self.source = json.get('DefinitionSource')
|
||||
|
||||
|
||||
def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', 'definition'], urls=True, **kwargs):
|
||||
'''A helper method to get a single (and hopefully the best) ZCI result.
|
||||
priority=list can be used to set the order in which fields will be checked for answers.
|
||||
Use web_fallback=True to fall back to grabbing the first web result.
|
||||
passed to query. This method will fall back to 'Sorry, no results.'
|
||||
if it cannot find anything.'''
|
||||
|
||||
ddg = query('\\'+q, **kwargs)
|
||||
response = ''
|
||||
|
||||
for p in priority:
|
||||
ps = p.split('.')
|
||||
type = ps[0]
|
||||
index = int(ps[1]) if len(ps) > 1 else None
|
||||
|
||||
result = getattr(ddg, type)
|
||||
if index is not None:
|
||||
if not hasattr(result, '__getitem__'): raise TypeError('%s field is not indexable' % type)
|
||||
result = result[index] if len(result) > index else None
|
||||
if not result: continue
|
||||
|
||||
if result.text: response = result.text
|
||||
if result.text and hasattr(result,'url') and urls:
|
||||
if result.url: response += ' (%s)' % result.url
|
||||
if response: break
|
||||
|
||||
# if there still isn't anything, try to get the first web result
|
||||
if not response and web_fallback:
|
||||
if ddg.redirect.url:
|
||||
response = ddg.redirect.url
|
||||
|
||||
# final fallback
|
||||
if not response:
|
||||
response = 'Sorry, no results.'
|
||||
|
||||
return response
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1:
|
||||
q = query(' '.join(sys.argv[1:]))
|
||||
keys = q.json.keys()
|
||||
keys.sort()
|
||||
for key in keys:
|
||||
sys.stdout.write(key)
|
||||
if type(q.json[key]) in [str,unicode]: print(':', q.json[key])
|
||||
else:
|
||||
sys.stdout.write('\n')
|
||||
for i in q.json[key]: print('\t',i)
|
||||
else:
|
||||
print('Usage: %s [query]' % sys.argv[0])
|
||||
@@ -0,0 +1,6 @@
|
||||
import random
|
||||
|
||||
def get_thing():
|
||||
file = "/home/krowbar/logs/evildata.txt"
|
||||
thing = ""
|
||||
return "If I Ever Become an Evil Overlord: " + random.choice(list(open(file))).rstrip()
|
||||
+2
-2
@@ -37,8 +37,8 @@ def make_puzzle():
|
||||
elif roll == 5:
|
||||
p1 = primes[random.randrange(0,len(primes))]
|
||||
p2 = primes[random.randrange(0,len(primes))]
|
||||
answer = str(p1) + ',' + str(p2)
|
||||
puzzle += p.number_to_words(p1 * p2) + " when factored into its two primes (answer in the form of the two primes with a comman between)"
|
||||
answer = str(min(p1,p2)) + ',' + str(max(p1,p2))
|
||||
puzzle += p.number_to_words(p1 * p2) + " when factored into its two primes (answer in the form of the two primes with a comma between)"
|
||||
|
||||
|
||||
puzzle += "? (Answer with numbers)"
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
krowbar&^%336&^%1452540446
|
||||
krowbar&^%399&^%1454593921
|
||||
karlen&^%272&^%1449500011
|
||||
endorphant&^%682&^%1444775660
|
||||
jumblesale&^%24&^%1426171214
|
||||
marcus&^%834&^%1452521269
|
||||
marcus&^%877&^%1454436882
|
||||
papa&^%179&^%1438878499
|
||||
epicmorphism&^%5&^%1421937744
|
||||
audy&^%78&^%1442345315
|
||||
kc&^%18&^%1422326056
|
||||
vilmibm&^%9&^%1445468087
|
||||
cmr&^%1074&^%1451719260
|
||||
cmr&^%1131&^%1454335852
|
||||
imt&^%519&^%1424087616
|
||||
cndorphant&^%788&^%1424094192
|
||||
rain&^%17&^%1422310975
|
||||
@@ -28,11 +28,13 @@ reppard&^%11&^%1437512059
|
||||
jesse&^%6&^%1437569027
|
||||
khoi&^%3&^%1438044039
|
||||
sanqui&^%4&^%1438184911
|
||||
endorphan&^%57&^%1450367628
|
||||
endorphan&^%64&^%1452614950
|
||||
cndorphbo&^%2&^%1447862524
|
||||
santi&^%3&^%1447873216
|
||||
insom&^%1&^%1450346059
|
||||
tahnok&^%3&^%1450457276
|
||||
nilsding&^%8&^%1452449452
|
||||
nilsding&^%12&^%1454100197
|
||||
vypr&^%3&^%1452470872
|
||||
synergian&^%1&^%1452541847
|
||||
synergian&^%21&^%1454583808
|
||||
dheeraj&^%2&^%1454438936
|
||||
demobot&^%6&^%1454439605
|
||||
@@ -18,3 +18,5 @@
|
||||
1444203916&^%cmr&^%http://tilde.town/~wiki/ircbots.html | cndorphbot:
|
||||
1447252215&^%krowbar&^%#bots, the last bastion of the free
|
||||
1451487092&^%krowbar&^%Bots rule! Users drool!
|
||||
1453394948&^%krowbar&^%We'll leave it to the future to resolve the present
|
||||
1453924207&^%krowbar&^%The best things happen when you're parsing
|
||||
@@ -130,3 +130,4 @@
|
||||
1449698715&^%vilmibm&^%hack the planet (with feels)
|
||||
1451971379&^%vilmibm&^%let's talk about html & feels | welcome new users!
|
||||
1452017977&^%vilmibm&^%let's talk about html & feels! | add yrself to the map of townies! http://tilde.town/~bear/where.html
|
||||
1453427743&^%vilmibm&^%WHAT MOVIE SHOULD WE WATCH IN ASCII ON MOVIE NIGHT? | add yrself to the map http://tilde.town/~bear/where.html
|
||||
@@ -1,5 +1,5 @@
|
||||
krowbar&^%7&^%17
|
||||
vilmibm&^%0&^%19
|
||||
krowbar&^%9&^%19
|
||||
vilmibm&^%0&^%20
|
||||
hardmath123&^%0&^%6
|
||||
joe&^%1&^%1jumblesale
|
||||
audiodude&^%1&^%0
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import urllib
|
||||
from bs4 import BeautifulSoup
|
||||
import random
|
||||
import re
|
||||
|
||||
def tumble(url):
|
||||
#Find the max pages
|
||||
soup = BeautifulSoup(urllib.urlopen(url).read(), 'html.parser')
|
||||
pages = soup.findAll('span', 'page-numbers')[0].text.split('/')[1] #this could totally fail several ways
|
||||
page = random.randrange(1, int(pages)+1)
|
||||
|
||||
#Parse a page
|
||||
soup = BeautifulSoup(urllib.urlopen(url + '/page/' + str(page)).read(), 'html.parser')
|
||||
article = random.choice(soup.findAll('article'))
|
||||
quote = article.find('blockquote').text.replace('\n','');
|
||||
if len(article.find('footer').findAll('ul')) > 1:
|
||||
quote += re.sub('\n+', ' ', article.find('footer').findAll('ul')[0].text); #the hash tags
|
||||
quote += '(' + re.sub('\n+', ' ', article.find('footer').findAll('ul')[1].text) + ')'; #and the date and notes
|
||||
else:
|
||||
quote += '(' + re.sub('\n+', ' ', article.find('footer').findAll('ul')[0].text) + ')'; #just the date and notes
|
||||
|
||||
return quote.encode('ascii', 'ignore')
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import random
|
||||
|
||||
def get_thing():
|
||||
file = "/home/krowbar/logs/welchdata.txt"
|
||||
thing = ""
|
||||
return "Thing Mr. Welch can no longer do in a RPG #" + random.choice(list(open(file))).rstrip()
|
||||
@@ -0,0 +1,24 @@
|
||||
import duckduckgo
|
||||
import urllib
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
def xkcd(query):
|
||||
res = duckduckgo.get_zci('site:xkcd.com ' + query);
|
||||
title = "";
|
||||
try: #ddg returns a url for these searches. i want a title as well
|
||||
title = BeautifulSoup(urllib.urlopen(res).read(), 'html.parser').title.text
|
||||
except:
|
||||
pass #just swallow the error. maybe the result wasn't a url or something else bad happened
|
||||
return (((title + ' - ') if title else '') + res).encode('ascii', 'ignore')
|
||||
|
||||
def xkcd_links(query):
|
||||
url = "https://duckduckgo.com/html/?q=site%3Axkcd.com+" + query.replace(' ', '+')
|
||||
soup = BeautifulSoup(urllib.urlopen(url).read(), 'html.parser')
|
||||
links = filter(lambda a: a[0:8] == 'xkcd.com', [a.text.strip() for a in soup.find_all("div", class_="url")])
|
||||
def pretty_link(url):
|
||||
data = BeautifulSoup(urllib.urlopen('http://'+url).read(), 'html.parser')
|
||||
title = data.title.text if data.title else ''
|
||||
return (title + ' - ' + url) if title else url
|
||||
|
||||
links = map(lambda url: pretty_link(url), links)
|
||||
return links
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/python
|
||||
import fileinput
|
||||
import json
|
||||
import time
|
||||
import calendar
|
||||
import shutil
|
||||
import re
|
||||
import math
|
||||
import operator
|
||||
|
||||
MAX_NODES = 3
|
||||
|
||||
logfile = "/home/jumblesale/Code/irc/log"
|
||||
outfile = "/home/krowbar/logs/chatBesties.json"
|
||||
outCircle = "/home/krowbar/logs/chatcircle.json"
|
||||
userData = {} #hash keyed by "user" that contains a hash of mentioned other users with count
|
||||
nameFix = {
|
||||
'jumblesal': 'jumblesale',
|
||||
'hardmath1': 'kc',
|
||||
'hardmath123': 'kc',
|
||||
'bendorphan': 'endorphant',
|
||||
'endorphan': 'endorphant',
|
||||
'synergian': 'synergiance'
|
||||
}
|
||||
|
||||
users = []
|
||||
#Get a list of all user names by checking the logs for people who have said things
|
||||
with open(logfile, "r") as log:
|
||||
for line in log:
|
||||
try:
|
||||
time, user, message = line.split("\t", 3)
|
||||
if nameFix.has_key(user):
|
||||
user = nameFix[user]
|
||||
else:
|
||||
user = user.lower()
|
||||
|
||||
if user not in users:
|
||||
users.append(user)
|
||||
except ValueError:
|
||||
continue #There are some bad lines in the log file that we'll ignore if we can't parse
|
||||
|
||||
d3data = {}
|
||||
d3data['nodes'] = []
|
||||
|
||||
#re-read the log and this time look for instances of user names in messages
|
||||
with open(logfile, "r") as log:
|
||||
for line in log:
|
||||
try:
|
||||
time, user, message = line.split("\t", 3)
|
||||
if nameFix.has_key(user):
|
||||
user = nameFix[user]
|
||||
else:
|
||||
user = user.lower()
|
||||
except ValueError:
|
||||
continue #There are some bad lines in the log file that we'll ignore if we can't parse
|
||||
for word in message.split(' '):
|
||||
word = re.sub('[^A-Za-z0-9]+', '', word)
|
||||
if word in users: #SOMEONE MENTIONED SOMEONE
|
||||
if userData.has_key(user): #This user is already set up
|
||||
if userData[user]['data'].has_key(word): #This user has mentioned this person before
|
||||
userData[user]['data'][word] += 1
|
||||
else: #This user never mentioned this person before
|
||||
userData[user]['data'][word] = 1
|
||||
else: #This user was never set up
|
||||
userData[user] = {} #make it a dictionary!
|
||||
userData[user]['data'] = {}
|
||||
userData[user]['data'][word] = 1
|
||||
userData[user]['id'] = len(d3data['nodes']) #so we know how to match people during the links phase
|
||||
d3data['nodes'].append({"name": user, "group": 1})
|
||||
if not userData.has_key(word): #check if the target has not been set up
|
||||
userData[word] = {}
|
||||
userData[word]['data'] = {}
|
||||
userData[word]['id'] = len(d3data['nodes'])
|
||||
d3data['nodes'].append({"name": word, "group": 1})
|
||||
|
||||
d3data['links'] = []
|
||||
#Now connect all the pople to their stuff
|
||||
for user, values in userData.iteritems():
|
||||
besties = sorted(values['data'].items(), key=operator.itemgetter(1), reverse=True)[0:MAX_NODES] #ONLY the top 5 besties
|
||||
for target, score in besties:
|
||||
try:
|
||||
print "Adding link for " + user + " (" + str(values['id']) + ") to " + target + " (" + str(userData[target]['id']) + ") for " + str(score)
|
||||
d3data['links'].append({"source": values['id'], "target": userData[target]['id'], "value": math.ceil(math.sqrt(score))})
|
||||
except KeyError:
|
||||
print "Error when trying to link " + user + " to " + target
|
||||
continue
|
||||
if len(values['data']) > MAX_NODES:
|
||||
print "...ignoring " + str(len(values['data']) - MAX_NODES) + " more connections"
|
||||
|
||||
d3Circle = {}
|
||||
d3Circle['names'] = [''] * len(userData)
|
||||
d3Circle['matrix'] = [[0] * len(userData)] * len(userData)
|
||||
|
||||
for user, values in userData.iteritems():
|
||||
d3Circle['names'][values['id']] = user
|
||||
for name, score in values['data'].iteritems():
|
||||
d3Circle['matrix'][values['id']][userData[name]['id']] = score if score > 1 else 0
|
||||
|
||||
with open(outfile + ".tmp", "w") as tmpFile:
|
||||
tmpFile.write(json.dumps(d3data))
|
||||
shutil.move(outfile + ".tmp", outfile)
|
||||
|
||||
with open(outCircle + ".tmp", "w") as tmpFile:
|
||||
tmpFile.write(json.dumps(d3Circle))
|
||||
shutil.move(outCircle + ".tmp", outCircle)
|
||||
@@ -22,7 +22,8 @@ charset="utf-8"></script>-->
|
||||
data.push([user, d, d]);
|
||||
})
|
||||
});
|
||||
google.setOnLoadCallback(drawChart);
|
||||
//google.setOnLoadCallback(drawChart);
|
||||
$(drawChart);
|
||||
});
|
||||
|
||||
function drawChart() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html content="text/html; charset=UTF-8;charset=utf-8">
|
||||
<head>
|
||||
<title>IRC chat stats</title>
|
||||
</head>
|
||||
@@ -12,6 +12,7 @@ charset="utf-8"></script>-->
|
||||
google.load("visualization", "1.1", {packages:["table"]});
|
||||
|
||||
data = [];
|
||||
|
||||
jQuery.getJSON("/~krowbar/data/chatStats.json", function(json) {
|
||||
now = new Date();
|
||||
nowSec = Math.round(now.getTime()/1000)
|
||||
@@ -27,12 +28,15 @@ charset="utf-8"></script>-->
|
||||
Number((userData.responseTime / (userData.mentions ? userData.mentions : 1) / 60).toFixed(2)),
|
||||
]);
|
||||
});
|
||||
google.setOnLoadCallback(drawTable);
|
||||
console.log("* Loaded the data!");
|
||||
//google.setOnLoadCallback(drawTable);
|
||||
$(drawTable)
|
||||
});
|
||||
|
||||
function drawTable() {
|
||||
|
||||
var dataTable = new google.visualization.DataTable();
|
||||
var userFormatter = new google.visualization.PatternFormat('<a href="/~{0}">{0}</a>');
|
||||
var minFormatter = new google.visualization.NumberFormat({pattern: '##.## minutes'});
|
||||
var dayFormatter = new google.visualization.NumberFormat({pattern: '## days'});
|
||||
var wordFormatter = new google.visualization.NumberFormat({pattern: '##.## words'});
|
||||
@@ -40,23 +44,24 @@ charset="utf-8"></script>-->
|
||||
var streakFormatter = new google.visualization.NumberFormat({pattern: '## lines'});
|
||||
var mentionsFormatter = new google.visualization.NumberFormat({pattern: '## mentions'});
|
||||
|
||||
dataTable.addColumn('string', 'User'); //col0
|
||||
dataTable.addColumn('datetime', 'First Spoke'); //col1
|
||||
dataTable.addColumn('datetime', 'Last Spoke'); //col2
|
||||
dataTable.addColumn('number', 'Total Time'); //col3
|
||||
dataTable.addColumn('number', 'Active on'); //col4
|
||||
dataTable.addColumn('number', 'Active Ratio');//col5
|
||||
dataTable.addColumn('number', 'Lines'); //col6
|
||||
dataTable.addColumn('number', 'Words'); //col7
|
||||
dataTable.addColumn('number', 'per Line'); //col8
|
||||
dataTable.addColumn('number', 'Characters'); //col9
|
||||
dataTable.addColumn('number', 'per Line'); //col10
|
||||
dataTable.addColumn('number', 'Chat Streak'); //col11
|
||||
dataTable.addColumn('number', 'Popularity'); //col12
|
||||
dataTable.addColumn('number', 'Bot Use'); //col13
|
||||
dataTable.addColumn('number', 'Avg response time'); //col14
|
||||
dataTable.addColumn('string', 'User'); //col0
|
||||
dataTable.addColumn('datetime', 'First Spoke'); //col1
|
||||
dataTable.addColumn('datetime', 'Last Spoke'); //col2
|
||||
dataTable.addColumn('number', 'Total'); //col3
|
||||
dataTable.addColumn('number', 'Active on'); //col4
|
||||
dataTable.addColumn('number', 'Ratio'); //col5
|
||||
dataTable.addColumn('number', 'Lines'); //col6
|
||||
dataTable.addColumn('number', 'Words'); //col7
|
||||
dataTable.addColumn('number', 'per Line'); //col8
|
||||
dataTable.addColumn('number', 'Characters'); //col9
|
||||
dataTable.addColumn('number', 'per Line'); //col10
|
||||
dataTable.addColumn('number', 'Chat Streak'); //col11
|
||||
dataTable.addColumn('number', 'Popularity'); //col12
|
||||
dataTable.addColumn('number', 'Bot Use'); //col13
|
||||
dataTable.addColumn('number', 'Response time'); //col14
|
||||
|
||||
dataTable.addRows(data);
|
||||
userFormatter.format(dataTable, [0]);
|
||||
dayFormatter.format(dataTable, 3);
|
||||
dayFormatter.format(dataTable, 4);
|
||||
wordFormatter.format(dataTable, 8);
|
||||
@@ -64,10 +69,12 @@ charset="utf-8"></script>-->
|
||||
streakFormatter.format(dataTable, 11);
|
||||
mentionsFormatter.format(dataTable, 12);
|
||||
minFormatter.format(dataTable, 14);
|
||||
console.log("* Set up the columns!");
|
||||
|
||||
var table = new google.visualization.Table(document.getElementById('statTable'));
|
||||
|
||||
table.draw(dataTable, {showRowNumber: false, width:'95%', height: '60%', sortColumn:2, sortAscending:false});
|
||||
table.draw(dataTable, {showRowNumber: false, width:'95%', height: '60%', sortColumn:2, sortAscending:false, allowHtml: true});
|
||||
console.log("* Drew the tables! (I hope.)");
|
||||
}
|
||||
</script>
|
||||
<body>
|
||||
|
||||
@@ -49,6 +49,9 @@
|
||||
linedata.addColumn('date', 'Date');
|
||||
var userData = {};
|
||||
_.forEach(json, function(set, idx) {
|
||||
//only display 1/8 the points. (every 2 days instead of every 6 hours) page is loading too slow
|
||||
//maybe i could add something to show more points but we're not losing too much granularity for the speed we gain
|
||||
if(idx % 8 != 0) return;
|
||||
_.forEach(set.data, function(point) {
|
||||
if(point.du > 2000) { //the 'interesting' threshold is set at 20000kb
|
||||
if(!userData[point.user]) {
|
||||
@@ -63,6 +66,7 @@
|
||||
})
|
||||
})
|
||||
_.forEach(json, function(set,idx) {
|
||||
if(idx % 8 != 0) return;
|
||||
var d = new Date(0);
|
||||
d.setUTCSeconds(set.date);
|
||||
linedata.addRow([d].concat(_.map(userData, function(user) { return user[idx];})));
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
.jsondiffpatch-annotated-delta {
|
||||
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
padding: 0 0 0 12px;
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta pre {
|
||||
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta td {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta td pre:hover {
|
||||
font-weight: bold;
|
||||
}
|
||||
td.jsondiffpatch-delta-note {
|
||||
font-style: italic;
|
||||
padding-left: 10px;
|
||||
}
|
||||
.jsondiffpatch-delta-note > div {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.jsondiffpatch-delta-note pre {
|
||||
font-style: normal;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta .jsondiffpatch-delta-note {
|
||||
color: #777;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta tr:hover {
|
||||
background: #ffc;
|
||||
}
|
||||
.jsondiffpatch-annotated-delta tr:hover > td.jsondiffpatch-delta-note {
|
||||
color: black;
|
||||
}
|
||||
.jsondiffpatch-error {
|
||||
background: red;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
.jsondiffpatch-delta {
|
||||
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
padding: 0 0 0 12px;
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-delta pre {
|
||||
font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace;
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: inline-block;
|
||||
}
|
||||
ul.jsondiffpatch-delta {
|
||||
list-style-type: none;
|
||||
padding: 0 0 0 20px;
|
||||
margin: 0;
|
||||
}
|
||||
.jsondiffpatch-delta ul {
|
||||
list-style-type: none;
|
||||
padding: 0 0 0 20px;
|
||||
margin: 0;
|
||||
}
|
||||
.jsondiffpatch-added .jsondiffpatch-property-name,
|
||||
.jsondiffpatch-added .jsondiffpatch-value pre,
|
||||
.jsondiffpatch-modified .jsondiffpatch-right-value pre,
|
||||
.jsondiffpatch-textdiff-added {
|
||||
background: #bbffbb;
|
||||
}
|
||||
.jsondiffpatch-deleted .jsondiffpatch-property-name,
|
||||
.jsondiffpatch-deleted pre,
|
||||
.jsondiffpatch-modified .jsondiffpatch-left-value pre,
|
||||
.jsondiffpatch-textdiff-deleted {
|
||||
background: #ffbbbb;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-movedestination {
|
||||
color: gray;
|
||||
}
|
||||
.jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
transition: all 0.5s;
|
||||
-webkit-transition: all 0.5s;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
.jsondiffpatch-unchanged-showing .jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-unchanged-showing .jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
max-height: 100px;
|
||||
}
|
||||
.jsondiffpatch-unchanged-hidden .jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
max-height: 0;
|
||||
}
|
||||
.jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value,
|
||||
.jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
display: block;
|
||||
}
|
||||
.jsondiffpatch-unchanged-visible .jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-unchanged-visible .jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
max-height: 100px;
|
||||
}
|
||||
.jsondiffpatch-unchanged-hiding .jsondiffpatch-unchanged,
|
||||
.jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value {
|
||||
max-height: 0;
|
||||
}
|
||||
.jsondiffpatch-unchanged-showing .jsondiffpatch-arrow,
|
||||
.jsondiffpatch-unchanged-hiding .jsondiffpatch-arrow {
|
||||
display: none;
|
||||
}
|
||||
.jsondiffpatch-value {
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-property-name {
|
||||
display: inline-block;
|
||||
padding-right: 5px;
|
||||
vertical-align: top;
|
||||
}
|
||||
.jsondiffpatch-property-name:after {
|
||||
content: ': ';
|
||||
}
|
||||
.jsondiffpatch-child-node-type-array > .jsondiffpatch-property-name:after {
|
||||
content: ': [';
|
||||
}
|
||||
.jsondiffpatch-child-node-type-array:after {
|
||||
content: '],';
|
||||
}
|
||||
div.jsondiffpatch-child-node-type-array:before {
|
||||
content: '[';
|
||||
}
|
||||
div.jsondiffpatch-child-node-type-array:after {
|
||||
content: ']';
|
||||
}
|
||||
.jsondiffpatch-child-node-type-object > .jsondiffpatch-property-name:after {
|
||||
content: ': {';
|
||||
}
|
||||
.jsondiffpatch-child-node-type-object:after {
|
||||
content: '},';
|
||||
}
|
||||
div.jsondiffpatch-child-node-type-object:before {
|
||||
content: '{';
|
||||
}
|
||||
div.jsondiffpatch-child-node-type-object:after {
|
||||
content: '}';
|
||||
}
|
||||
.jsondiffpatch-value pre:after {
|
||||
content: ',';
|
||||
}
|
||||
li:last-child > .jsondiffpatch-value pre:after,
|
||||
.jsondiffpatch-modified > .jsondiffpatch-left-value pre:after {
|
||||
content: '';
|
||||
}
|
||||
.jsondiffpatch-modified .jsondiffpatch-value {
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-modified .jsondiffpatch-right-value {
|
||||
margin-left: 5px;
|
||||
}
|
||||
.jsondiffpatch-moved .jsondiffpatch-value {
|
||||
display: none;
|
||||
}
|
||||
.jsondiffpatch-moved .jsondiffpatch-moved-destination {
|
||||
display: inline-block;
|
||||
background: #ffffbb;
|
||||
color: #888;
|
||||
}
|
||||
.jsondiffpatch-moved .jsondiffpatch-moved-destination:before {
|
||||
content: ' => ';
|
||||
}
|
||||
ul.jsondiffpatch-textdiff {
|
||||
padding: 0;
|
||||
}
|
||||
.jsondiffpatch-textdiff-location {
|
||||
color: #bbb;
|
||||
display: inline-block;
|
||||
min-width: 60px;
|
||||
}
|
||||
.jsondiffpatch-textdiff-line {
|
||||
display: inline-block;
|
||||
}
|
||||
.jsondiffpatch-textdiff-line-number:after {
|
||||
content: ',';
|
||||
}
|
||||
.jsondiffpatch-error {
|
||||
background: red;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
@@ -2,4 +2,4 @@
|
||||
"data1": "foo",
|
||||
"data2": "bar",
|
||||
"data3": ["foo","bar","baz"]
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"data1": "foo",
|
||||
"data4": "banana",
|
||||
"data3": ["foo","bat","baz","bang"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html content="text/html; charset=UTF-8;charset=utf-8">
|
||||
<head>
|
||||
<title>JSON diff POC</title>
|
||||
</head>
|
||||
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||||
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"
|
||||
charset="utf-8"></script>-->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
jQuery.getJSON("data.json", function(json) {
|
||||
});
|
||||
jQuery.getJSON("data2.json", function(json) {
|
||||
});
|
||||
</script>
|
||||
<body>
|
||||
<div>HERE'S SOME STUFF!</div>
|
||||
<textarea id="text1" cols="40" rows="10"></textarea>
|
||||
<textarea id="text2" cols="40" rows="10"></textarea>
|
||||
<textarea id="diff" cols="40" rows="10"></textarea>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),(f.jsondiffpatch||(f.jsondiffpatch={})).formatters=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
module.exports=require("./formatters");
|
||||
},{"./formatters":6}],2:[function(require,module,exports){
|
||||
exports.isBrowser="undefined"!=typeof window;
|
||||
},{}],3:[function(require,module,exports){
|
||||
var base=require("./base"),BaseFormatter=base.BaseFormatter,AnnotatedFormatter=function(){this.includeMoveDestinations=!1};AnnotatedFormatter.prototype=new BaseFormatter,AnnotatedFormatter.prototype.prepareContext=function(t){BaseFormatter.prototype.prepareContext.call(this,t),t.indent=function(t){this.indentLevel=(this.indentLevel||0)+("undefined"==typeof t?1:t),this.indentPad=new Array(this.indentLevel+1).join(" ")},t.row=function(e,n){t.out('<tr><td style="white-space: nowrap;"><pre class="jsondiffpatch-annotated-indent" style="display: inline-block">'),t.out(t.indentPad),t.out('</pre><pre style="display: inline-block">'),t.out(e),t.out('</pre></td><td class="jsondiffpatch-delta-note"><div>'),t.out(n),t.out("</div></td></tr>")}},AnnotatedFormatter.prototype.typeFormattterErrorFormatter=function(t,e){t.row("",'<pre class="jsondiffpatch-error">'+e+"</pre>")},AnnotatedFormatter.prototype.formatTextDiffString=function(t,e){var n=this.parseTextDiff(e);t.out('<ul class="jsondiffpatch-textdiff">');for(var o=0,r=n.length;r>o;o++){var a=n[o];t.out('<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">'+a.location.line+'</span><span class="jsondiffpatch-textdiff-char">'+a.location.chr+'</span></div><div class="jsondiffpatch-textdiff-line">');for(var i=a.pieces,d=0,p=i.length;p>d;d++){var f=i[d];t.out('<span class="jsondiffpatch-textdiff-'+f.type+'">'+f.text+"</span>")}t.out("</div></li>")}t.out("</ul>")},AnnotatedFormatter.prototype.rootBegin=function(t,e,n){t.out('<table class="jsondiffpatch-annotated-delta">'),"node"===e&&(t.row("{"),t.indent()),"array"===n&&t.row('"_t": "a",',"Array delta (member names indicate array indices)")},AnnotatedFormatter.prototype.rootEnd=function(t,e){"node"===e&&(t.indent(-1),t.row("}")),t.out("</table>")},AnnotatedFormatter.prototype.nodeBegin=function(t,e,n,o,r){t.row("""+e+"": {"),"node"===o&&t.indent(),"array"===r&&t.row('"_t": "a",',"Array delta (member names indicate array indices)")},AnnotatedFormatter.prototype.nodeEnd=function(t,e,n,o,r,a){"node"===o&&t.indent(-1),t.row("}"+(a?"":","))},AnnotatedFormatter.prototype.format_unchanged=function(){},AnnotatedFormatter.prototype.format_movedestination=function(){},AnnotatedFormatter.prototype.format_node=function(t,e,n){this.formatDeltaChildren(t,e,n)};var wrapPropertyName=function(t){return'<pre style="display:inline-block">"'+t+""</pre>"},deltaAnnotations={added:function(t,e,n,o){var r=" <pre>([newValue])</pre>";return"undefined"==typeof o?"new value"+r:"number"==typeof o?"insert at index "+o+r:"add property "+wrapPropertyName(o)+r},modified:function(t,e,n,o){var r=" <pre>([previousValue, newValue])</pre>";return"undefined"==typeof o?"modify value"+r:"number"==typeof o?"modify at index "+o+r:"modify property "+wrapPropertyName(o)+r},deleted:function(t,e,n,o){var r=" <pre>([previousValue, 0, 0])</pre>";return"undefined"==typeof o?"delete value"+r:"number"==typeof o?"remove index "+o+r:"delete property "+wrapPropertyName(o)+r},moved:function(t,e,n,o){return'move from <span title="(position to remove at original state)">index '+o+'</span> to <span title="(position to insert at final state)">index '+t[1]+"</span>"},textdiff:function(t,e,n,o){var r="undefined"==typeof o?"":"number"==typeof o?" at index "+o:" at property "+wrapPropertyName(o);return"text diff"+r+', format is <a href="https://code.google.com/p/google-diff-match-patch/wiki/Unidiff">a variation of Unidiff</a>'}},formatAnyChange=function(t,e){var n=this.getDeltaType(e),o=deltaAnnotations[n],r=o&&o.apply(o,Array.prototype.slice.call(arguments,1)),a=JSON.stringify(e,null,2);"textdiff"===n&&(a=a.split("\\n").join('\\n"+\n "')),t.indent(),t.row(a,r),t.indent(-1)};AnnotatedFormatter.prototype.format_added=formatAnyChange,AnnotatedFormatter.prototype.format_modified=formatAnyChange,AnnotatedFormatter.prototype.format_deleted=formatAnyChange,AnnotatedFormatter.prototype.format_moved=formatAnyChange,AnnotatedFormatter.prototype.format_textdiff=formatAnyChange,exports.AnnotatedFormatter=AnnotatedFormatter;var defaultInstance;exports.format=function(t,e){return defaultInstance||(defaultInstance=new AnnotatedFormatter),defaultInstance.format(t,e)};
|
||||
},{"./base":4}],4:[function(require,module,exports){
|
||||
var isArray="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},getObjectKeys="function"==typeof Object.keys?function(e){return Object.keys(e)}:function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(r);return t},trimUnderscore=function(e){return"_"===e.substr(0,1)?e.slice(1):e},arrayKeyToSortNumber=function(e){return"_t"===e?-1:"_"===e.substr(0,1)?parseInt(e.slice(1),10):parseInt(e,10)+.1},arrayKeyComparer=function(e,t){return arrayKeyToSortNumber(e)-arrayKeyToSortNumber(t)},BaseFormatter=function(){};BaseFormatter.prototype.format=function(e,t){var r={};return this.prepareContext(r),this.recurse(r,e,t),this.finalize(r)},BaseFormatter.prototype.prepareContext=function(e){e.buffer=[],e.out=function(){this.buffer.push.apply(this.buffer,arguments)}},BaseFormatter.prototype.typeFormattterNotFound=function(e,t){throw new Error("cannot format delta type: "+t)},BaseFormatter.prototype.typeFormattterErrorFormatter=function(e,t){return t.toString()},BaseFormatter.prototype.finalize=function(e){return isArray(e.buffer)?e.buffer.join(""):void 0},BaseFormatter.prototype.recurse=function(e,t,r,o,n,a,i){var f=t&&a,s=f?a.value:r;if("undefined"!=typeof t||"undefined"!=typeof o){var u=this.getDeltaType(t,a),p="node"===u?"a"===t._t?"array":"object":"";"undefined"!=typeof o?this.nodeBegin(e,o,n,u,p,i):this.rootBegin(e,u,p);var y;try{y=this["format_"+u]||this.typeFormattterNotFound(e,u),y.call(this,e,t,s,o,n,a)}catch(d){this.typeFormattterErrorFormatter(e,d,t,s,o,n,a),"undefined"!=typeof console&&console.error&&console.error(d.stack)}"undefined"!=typeof o?this.nodeEnd(e,o,n,u,p,i):this.rootEnd(e,u,p)}},BaseFormatter.prototype.formatDeltaChildren=function(e,t,r){var o=this;this.forEachDeltaKey(t,r,function(n,a,i,f){o.recurse(e,t[n],r?r[a]:void 0,n,a,i,f)})},BaseFormatter.prototype.forEachDeltaKey=function(e,t,r){var o,n=getObjectKeys(e),a="a"===e._t,i={};if("undefined"!=typeof t)for(o in t)"undefined"!=typeof e[o]||a&&"undefined"!=typeof e["_"+o]||n.push(o);for(o in e){var f=e[o];isArray(f)&&3===f[2]&&(i[f[1].toString()]={key:o,value:t&&t[parseInt(o.substr(1))]},this.includeMoveDestinations!==!1&&"undefined"==typeof t&&"undefined"==typeof e[f[1]]&&n.push(f[1].toString()))}a?n.sort(arrayKeyComparer):n.sort();for(var s=0,u=n.length;u>s;s++){var p=n[s];if(!a||"_t"!==p){var y=a?"number"==typeof p?p:parseInt(trimUnderscore(p),10):p,d=s===u-1;r(p,y,i[y],d)}}},BaseFormatter.prototype.getDeltaType=function(e,t){if("undefined"==typeof e)return"undefined"!=typeof t?"movedestination":"unchanged";if(isArray(e)){if(1===e.length)return"added";if(2===e.length)return"modified";if(3===e.length&&0===e[2])return"deleted";if(3===e.length&&2===e[2])return"textdiff";if(3===e.length&&3===e[2])return"moved"}else if("object"==typeof e)return"node";return"unknown"},BaseFormatter.prototype.parseTextDiff=function(e){for(var t=[],r=e.split("\n@@ "),o=0,n=r.length;n>o;o++){var a=r[o],i={pieces:[]},f=/^(?:@@ )?[-+]?(\d+),(\d+)/.exec(a).slice(1);i.location={line:f[0],chr:f[1]};for(var s=a.split("\n").slice(1),u=0,p=s.length;p>u;u++){var y=s[u];if(y.length){var d={type:"context"};"+"===y.substr(0,1)?d.type="added":"-"===y.substr(0,1)&&(d.type="deleted"),d.text=y.slice(1),i.pieces.push(d)}}t.push(i)}return t},exports.BaseFormatter=BaseFormatter;
|
||||
},{}],5:[function(require,module,exports){
|
||||
function htmlEscape(t){for(var e=t,o=[[/&/g,"&"],[/</g,"<"],[/>/g,">"],[/'/g,"'"],[/"/g,"""]],a=0;a<o.length;a++)e=e.replace(o[a][0],o[a][1]);return e}var base=require("./base"),BaseFormatter=base.BaseFormatter,HtmlFormatter=function(){};HtmlFormatter.prototype=new BaseFormatter,HtmlFormatter.prototype.typeFormattterErrorFormatter=function(t,e){t.out('<pre class="jsondiffpatch-error">'+e+"</pre>")},HtmlFormatter.prototype.formatValue=function(t,e){t.out("<pre>"+htmlEscape(JSON.stringify(e,null,2))+"</pre>")},HtmlFormatter.prototype.formatTextDiffString=function(t,e){var o=this.parseTextDiff(e);t.out('<ul class="jsondiffpatch-textdiff">');for(var a=0,r=o.length;r>a;a++){var i=o[a];t.out('<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">'+i.location.line+'</span><span class="jsondiffpatch-textdiff-char">'+i.location.chr+'</span></div><div class="jsondiffpatch-textdiff-line">');for(var n=i.pieces,s=0,d=n.length;d>s;s++){var f=n[s];t.out('<span class="jsondiffpatch-textdiff-'+f.type+'">'+htmlEscape(unescape(f.text))+"</span>")}t.out("</div></li>")}t.out("</ul>")};var adjustArrows=function(t){t=t||document;var e=function(t){return t.textContent||t.innerText},o=function(t,e,o){for(var a=t.querySelectorAll(e),r=0,i=a.length;i>r;r++)o(a[r])},a=function(t,e){for(var o=0,a=t.children.length;a>o;o++)e(t.children[o],o)};o(t,".jsondiffpatch-arrow",function(t){var o=t.parentNode,r=t.children[0],i=r.children[1];r.style.display="none";var n,s=e(o.querySelector(".jsondiffpatch-moved-destination")),d=o.parentNode;if(a(d,function(t){t.getAttribute("data-key")===s&&(n=t)}),n)try{var f=n.offsetTop-o.offsetTop;r.setAttribute("height",Math.abs(f)+6),t.style.top=-8+(f>0?0:f)+"px";var l=f>0?"M30,0 Q-10,"+Math.round(f/2)+" 26,"+(f-4):"M30,"+-f+" Q-10,"+Math.round(-f/2)+" 26,4";i.setAttribute("d",l),r.style.display=""}catch(c){return}})};HtmlFormatter.prototype.rootBegin=function(t,e,o){var a="jsondiffpatch-"+e+(o?" jsondiffpatch-child-node-type-"+o:"");t.out('<div class="jsondiffpatch-delta '+a+'">')},HtmlFormatter.prototype.rootEnd=function(t){t.out("</div>"+(t.hasArrows?'<script type="text/javascript">setTimeout('+adjustArrows.toString()+",10);</script>":""))},HtmlFormatter.prototype.nodeBegin=function(t,e,o,a,r){var i="jsondiffpatch-"+a+(r?" jsondiffpatch-child-node-type-"+r:"");t.out('<li class="'+i+'" data-key="'+o+'"><div class="jsondiffpatch-property-name">'+o+"</div>")},HtmlFormatter.prototype.nodeEnd=function(t){t.out("</li>")},HtmlFormatter.prototype.format_unchanged=function(t,e,o){"undefined"!=typeof o&&(t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,o),t.out("</div>"))},HtmlFormatter.prototype.format_movedestination=function(t,e,o){"undefined"!=typeof o&&(t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,o),t.out("</div>"))},HtmlFormatter.prototype.format_node=function(t,e,o){var a="a"===e._t?"array":"object";t.out('<ul class="jsondiffpatch-node jsondiffpatch-node-type-'+a+'">'),this.formatDeltaChildren(t,e,o),t.out("</ul>")},HtmlFormatter.prototype.format_added=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out("</div>")},HtmlFormatter.prototype.format_modified=function(t,e){t.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">'),this.formatValue(t,e[0]),t.out('</div><div class="jsondiffpatch-value jsondiffpatch-right-value">'),this.formatValue(t,e[1]),t.out("</div>")},HtmlFormatter.prototype.format_deleted=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out("</div>")},HtmlFormatter.prototype.format_moved=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out('</div><div class="jsondiffpatch-moved-destination">'+e[1]+"</div>"),t.out('<div class="jsondiffpatch-arrow" style="position: relative; left: -34px;"> <svg width="30" height="60" style="position: absolute; display: none;"> <defs> <marker id="markerArrow" markerWidth="8" markerHeight="8" refx="2" refy="4" orient="auto" markerUnits="userSpaceOnUse"> <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" /> </marker> </defs> <path d="M30,0 Q-10,25 26,50" style="stroke: #88f; stroke-width: 2px; fill: none; stroke-opacity: 0.5; marker-end: url(#markerArrow);"></path> </svg> </div>'),t.hasArrows=!0},HtmlFormatter.prototype.format_textdiff=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatTextDiffString(t,e[0]),t.out("</div>")};var showUnchanged=function(t,e,o){var a=e||document.body,r="jsondiffpatch-unchanged-",i={showing:r+"showing",hiding:r+"hiding",visible:r+"visible",hidden:r+"hidden"},n=a.classList;if(n){if(!o)return n.remove(i.showing),n.remove(i.hiding),n.remove(i.visible),n.remove(i.hidden),void(t===!1&&n.add(i.hidden));t===!1?(n.remove(i.showing),n.add(i.visible),setTimeout(function(){n.add(i.hiding)},10)):(n.remove(i.hiding),n.add(i.sLine truncated
|
||||
},{"./base":4}],6:[function(require,module,exports){
|
||||
var environment=require("../environment");if(exports.base=require("./base"),exports.html=require("./html"),exports.annotated=require("./annotated"),!environment.isBrowser){var consoleModuleName="./console";exports.console=require(consoleModuleName)}
|
||||
},{"../environment":2,"./annotated":3,"./base":4,"./html":5}]},{},[1])(1)
|
||||
});
|
||||
|
||||
|
||||
//# sourceMappingURL=jsondiffpatch-formatters.min.map
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.jsondiffpatch=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
var environment=require("./environment"),DiffPatcher=require("./diffpatcher").DiffPatcher;exports.DiffPatcher=DiffPatcher,exports.create=function(e){return new DiffPatcher(e)},exports.dateReviver=require("./date-reviver");var defaultInstance;if(exports.diff=function(){return defaultInstance||(defaultInstance=new DiffPatcher),defaultInstance.diff.apply(defaultInstance,arguments)},exports.patch=function(){return defaultInstance||(defaultInstance=new DiffPatcher),defaultInstance.patch.apply(defaultInstance,arguments)},exports.unpatch=function(){return defaultInstance||(defaultInstance=new DiffPatcher),defaultInstance.unpatch.apply(defaultInstance,arguments)},exports.reverse=function(){return defaultInstance||(defaultInstance=new DiffPatcher),defaultInstance.reverse.apply(defaultInstance,arguments)},environment.isBrowser)exports.homepage="https://github.com/benjamine/jsondiffpatch",exports.version="0.1.38";else{var packageInfoModuleName="../package.json",packageInfo=require(packageInfoModuleName);exports.homepage=packageInfo.homepage,exports.version=packageInfo.version;var formatterModuleName="./formatters",formatters=require(formatterModuleName);exports.formatters=formatters,exports.console=formatters.console}
|
||||
},{"./date-reviver":6,"./diffpatcher":7,"./environment":8}],2:[function(require,module,exports){
|
||||
var Pipe=require("../pipe").Pipe,Context=function(){};Context.prototype.setResult=function(t){return this.result=t,this.hasResult=!0,this},Context.prototype.exit=function(){return this.exiting=!0,this},Context.prototype.switchTo=function(t,e){return"string"==typeof t||t instanceof Pipe?this.nextPipe=t:(this.next=t,e&&(this.nextPipe=e)),this},Context.prototype.push=function(t,e){return t.parent=this,"undefined"!=typeof e&&(t.childName=e),t.root=this.root||this,t.options=t.options||this.options,this.children?(this.children[this.children.length-1].next=t,this.children.push(t)):(this.children=[t],this.nextAfterChildren=this.next||null,this.next=t),t.next=this,this},exports.Context=Context;
|
||||
},{"../pipe":15}],3:[function(require,module,exports){
|
||||
var Context=require("./context").Context,DiffContext=function(t,e){this.left=t,this.right=e,this.pipe="diff"};DiffContext.prototype=new Context,exports.DiffContext=DiffContext;
|
||||
},{"./context":2}],4:[function(require,module,exports){
|
||||
var Context=require("./context").Context,PatchContext=function(t,e){this.left=t,this.delta=e,this.pipe="patch"};PatchContext.prototype=new Context,exports.PatchContext=PatchContext;
|
||||
},{"./context":2}],5:[function(require,module,exports){
|
||||
var Context=require("./context").Context,ReverseContext=function(e){this.delta=e,this.pipe="reverse"};ReverseContext.prototype=new Context,exports.ReverseContext=ReverseContext;
|
||||
},{"./context":2}],6:[function(require,module,exports){
|
||||
module.exports=function(d,e){var t;return"string"==typeof e&&(t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d*))?(Z|([+\-])(\d{2}):(\d{2}))$/.exec(e))?new Date(Date.UTC(+t[1],+t[2]-1,+t[3],+t[4],+t[5],+t[6],+(t[7]||0))):e};
|
||||
},{}],7:[function(require,module,exports){
|
||||
var Processor=require("./processor").Processor,Pipe=require("./pipe").Pipe,DiffContext=require("./contexts/diff").DiffContext,PatchContext=require("./contexts/patch").PatchContext,ReverseContext=require("./contexts/reverse").ReverseContext,trivial=require("./filters/trivial"),nested=require("./filters/nested"),arrays=require("./filters/arrays"),dates=require("./filters/dates"),texts=require("./filters/texts"),DiffPatcher=function(e){this.processor=new Processor(e),this.processor.pipe(new Pipe("diff").append(nested.collectChildrenDiffFilter,trivial.diffFilter,dates.diffFilter,texts.diffFilter,nested.objectsDiffFilter,arrays.diffFilter).shouldHaveResult()),this.processor.pipe(new Pipe("patch").append(nested.collectChildrenPatchFilter,arrays.collectChildrenPatchFilter,trivial.patchFilter,texts.patchFilter,nested.patchFilter,arrays.patchFilter).shouldHaveResult()),this.processor.pipe(new Pipe("reverse").append(nested.collectChildrenReverseFilter,arrays.collectChildrenReverseFilter,trivial.reverseFilter,texts.reverseFilter,nested.reverseFilter,arrays.reverseFilter).shouldHaveResult())};DiffPatcher.prototype.options=function(){return this.processor.options.apply(this.processor,arguments)},DiffPatcher.prototype.diff=function(e,r){return this.processor.process(new DiffContext(e,r))},DiffPatcher.prototype.patch=function(e,r){return this.processor.process(new PatchContext(e,r))},DiffPatcher.prototype.reverse=function(e){return this.processor.process(new ReverseContext(e))},DiffPatcher.prototype.unpatch=function(e,r){return this.patch(e,this.reverse(r))},exports.DiffPatcher=DiffPatcher;
|
||||
},{"./contexts/diff":3,"./contexts/patch":4,"./contexts/reverse":5,"./filters/arrays":9,"./filters/dates":10,"./filters/nested":12,"./filters/texts":13,"./filters/trivial":14,"./pipe":15,"./processor":16}],8:[function(require,module,exports){
|
||||
exports.isBrowser="undefined"!=typeof window;
|
||||
},{}],9:[function(require,module,exports){
|
||||
function arraysHaveMatchByRef(e,t,r,i){for(var a=0;r>a;a++)for(var n=e[a],l=0;i>l;l++){var s=t[l];if(n===s)return!0}}function matchItems(e,t,r,i,a){var n=e[r],l=t[i];if(n===l)return!0;if("object"!=typeof n||"object"!=typeof l)return!1;var s=a.objectHash;if(!s)return a.matchByPosition&&r===i;var o,f;return"number"==typeof r?(a.hashCache1=a.hashCache1||[],o=a.hashCache1[r],"undefined"==typeof o&&(a.hashCache1[r]=o=s(n,r))):o=s(n),"undefined"==typeof o?!1:("number"==typeof i?(a.hashCache2=a.hashCache2||[],f=a.hashCache2[i],"undefined"==typeof f&&(a.hashCache2[i]=f=s(l,i))):f=s(l),"undefined"==typeof f?!1:o===f)}var DiffContext=require("../contexts/diff").DiffContext,PatchContext=require("../contexts/patch").PatchContext,ReverseContext=require("../contexts/reverse").ReverseContext,lcs=require("./lcs"),ARRAY_MOVE=3,isArray="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},arrayIndexOf="function"==typeof Array.prototype.indexOf?function(e,t){return e.indexOf(t)}:function(e,t){for(var r=e.length,i=0;r>i;i++)if(e[i]===t)return i;return-1},diffFilter=function(e){if(e.leftIsArray){var t,r,i,a,n={objectHash:e.options&&e.options.objectHash,matchByPosition:e.options&&e.options.matchByPosition},l=0,s=0,o=e.left,f=e.right,c=o.length,h=f.length;for(c>0&&h>0&&!n.objectHash&&"boolean"!=typeof n.matchByPosition&&(n.matchByPosition=!arraysHaveMatchByRef(o,f,c,h));c>l&&h>l&&matchItems(o,f,l,l,n);)t=l,a=new DiffContext(e.left[t],e.right[t]),e.push(a,t),l++;for(;c>s+l&&h>s+l&&matchItems(o,f,c-1-s,h-1-s,n);)r=c-1-s,i=h-1-s,a=new DiffContext(e.left[r],e.right[i]),e.push(a,i),s++;var u;if(l+s===c){if(c===h)return void e.setResult(void 0).exit();for(u=u||{_t:"a"},t=l;h-s>t;t++)u[t]=[f[t]];return void e.setResult(u).exit()}if(l+s===h){for(u=u||{_t:"a"},t=l;c-s>t;t++)u["_"+t]=[o[t],0,0];return void e.setResult(u).exit()}delete n.hashCache1,delete n.hashCache2;var d=o.slice(l,c-s),v=f.slice(l,h-s),p=lcs.get(d,v,matchItems,n),y=[];for(u=u||{_t:"a"},t=l;c-s>t;t++)arrayIndexOf(p.indices1,t-l)<0&&(u["_"+t]=[o[t],0,0],y.push(t));var x=!0;e.options&&e.options.arrays&&e.options.arrays.detectMove===!1&&(x=!1);var m=!1;e.options&&e.options.arrays&&e.options.arrays.includeValueOnMove&&(m=!0);var C=y.length;for(t=l;h-s>t;t++){var R=arrayIndexOf(p.indices2,t-l);if(0>R){var A=!1;if(x&&C>0)for(var _=0;C>_;_++)if(r=y[_],matchItems(d,v,r-l,t-l,n)){u["_"+r].splice(1,2,t,ARRAY_MOVE),m||(u["_"+r][0]=""),i=t,a=new DiffContext(e.left[r],e.right[i]),e.push(a,i),y.splice(_,1),A=!0;break}A||(u[t]=[f[t]])}else r=p.indices1[R]+l,i=p.indices2[R]+l,a=new DiffContext(e.left[r],e.right[i]),e.push(a,i)}e.setResult(u).exit()}};diffFilter.filterName="arrays";var compare={numerically:function(e,t){return e-t},numericallyBy:function(e){return function(t,r){return t[e]-r[e]}}},patchFilter=function(e){if(e.nested&&"a"===e.delta._t){var t,r,i=e.delta,a=e.left,n=[],l=[],s=[];for(t in i)if("_t"!==t)if("_"===t[0]){if(0!==i[t][2]&&i[t][2]!==ARRAY_MOVE)throw new Error("only removal or move can be applied at original array indices, invalid diff type: "+i[t][2]);n.push(parseInt(t.slice(1),10))}else 1===i[t].length?l.push({index:parseInt(t,10),value:i[t][0]}):s.push({index:parseInt(t,10),delta:i[t]});for(n=n.sort(compare.numerically),t=n.length-1;t>=0;t--){r=n[t];var o=i["_"+r],f=a.splice(r,1)[0];o[2]===ARRAY_MOVE&&l.push({index:o[1],value:f})}l=l.sort(compare.numericallyBy("index"));var c=l.length;for(t=0;c>t;t++){var h=l[t];a.splice(h.index,0,h.value)}var u,d=s.length;if(d>0)for(t=0;d>t;t++){var v=s[t];u=new PatchContext(e.left[v.index],v.delta),e.push(u,v.index)}return e.children?void e.exit():void e.setResult(e.left).exit()}};patchFilter.filterName="arrays";var collectChildrenPatchFilter=function(e){if(e&&e.children&&"a"===e.delta._t){for(var t,r=e.children.length,i=0;r>i;i++)t=e.children[i],e.left[t.childName]=t.result;e.setResult(e.left).exit()}};collectChildrenPatchFilter.filterName="arraysCollectChildren";var reverseFilter=function(e){if(!e.nested)return void(e.delta[2]===ARRAY_MOVE&&(e.newName="_"+e.delta[1],e.setResult([e.delta[0],parseInt(e.childName.substr(1),10),ARRAY_MOVE]).exit()));if("a"===e.delta._t){var t,r;for(t in e.delta)"_t"!==t&&(r=new ReverseContext(e.delta[t]),e.push(r,t));e.exit()}};reverseFilter.filterName="arrays";var reverseArrayDeltaIndex=function(e,t,r){if("string"==typeof t&&"_"===t[0])return parseInt(t.substr(1),10);if(isArray(r)&&0===r[2])return"_"+t;var i=+t;for(var a in e){var n=e[a];if(isArray(n))if(n[2]===ARRAY_MOVE){var l=parseInt(a.substr(1),10),s=n[1];if(s===+t)return l;i>=l&&s>i?i++:l>=i&&i>s&&i--}else if(0===n[2]){var o=parseInt(a.substr(1),10);i>=o&&i++}else 1===n.length&&i>=a&&i--}return i},collectChildrenReverseFilter=function(e){if(e&&e.children&&"a"===e.delta._t){for(var t,r=e.children.length,i={_t:"a"},a=0;r>a;a++){t=e.children[a];var n=t.newName;"undefined"==typeof n&&(n=reverseArrayDeltaIndex(e.delta,t.childName,t.result)),i[n]!==t.result&&(i[n]=t.result)}e.setResult(i).exit()}};collectChildrenRLine truncated
|
||||
},{"../contexts/diff":3,"../contexts/patch":4,"../contexts/reverse":5,"./lcs":11}],10:[function(require,module,exports){
|
||||
var diffFilter=function(t){t.left instanceof Date?(t.right instanceof Date?t.left.getTime()!==t.right.getTime()?t.setResult([t.left,t.right]):t.setResult(void 0):t.setResult([t.left,t.right]),t.exit()):t.right instanceof Date&&t.setResult([t.left,t.right]).exit()};diffFilter.filterName="dates",exports.diffFilter=diffFilter;
|
||||
},{}],11:[function(require,module,exports){
|
||||
var defaultMatch=function(t,e,n,r){return t[n]===e[r]},lengthMatrix=function(t,e,n,r){var c,a,i=t.length,u=e.length,f=[i+1];for(c=0;i+1>c;c++)for(f[c]=[u+1],a=0;u+1>a;a++)f[c][a]=0;for(f.match=n,c=1;i+1>c;c++)for(a=1;u+1>a;a++)n(t,e,c-1,a-1,r)?f[c][a]=f[c-1][a-1]+1:f[c][a]=Math.max(f[c-1][a],f[c][a-1]);return f},backtrack=function(t,e,n,r,c,a){if(0===r||0===c)return{sequence:[],indices1:[],indices2:[]};if(t.match(e,n,r-1,c-1,a)){var i=backtrack(t,e,n,r-1,c-1,a);return i.sequence.push(e[r-1]),i.indices1.push(r-1),i.indices2.push(c-1),i}return t[r][c-1]>t[r-1][c]?backtrack(t,e,n,r,c-1,a):backtrack(t,e,n,r-1,c,a)},get=function(t,e,n,r){r=r||{};var c=lengthMatrix(t,e,n||defaultMatch,r),a=backtrack(c,t,e,t.length,e.length,r);return"string"==typeof t&&"string"==typeof e&&(a.sequence=a.sequence.join("")),a};exports.get=get;
|
||||
},{}],12:[function(require,module,exports){
|
||||
var DiffContext=require("../contexts/diff").DiffContext,PatchContext=require("../contexts/patch").PatchContext,ReverseContext=require("../contexts/reverse").ReverseContext,collectChildrenDiffFilter=function(e){if(e&&e.children){for(var t,l=e.children.length,r=e.result,i=0;l>i;i++)t=e.children[i],"undefined"!=typeof t.result&&(r=r||{},r[t.childName]=t.result);r&&e.leftIsArray&&(r._t="a"),e.setResult(r).exit()}};collectChildrenDiffFilter.filterName="collectChildren";var objectsDiffFilter=function(e){if(!e.leftIsArray&&"object"===e.leftType){var t,l;for(t in e.left)l=new DiffContext(e.left[t],e.right[t]),e.push(l,t);for(t in e.right)"undefined"==typeof e.left[t]&&(l=new DiffContext(void 0,e.right[t]),e.push(l,t));return e.children&&0!==e.children.length?void e.exit():void e.setResult(void 0).exit()}};objectsDiffFilter.filterName="objects";var patchFilter=function(e){if(e.nested&&!e.delta._t){var t,l;for(t in e.delta)l=new PatchContext(e.left[t],e.delta[t]),e.push(l,t);e.exit()}};patchFilter.filterName="objects";var collectChildrenPatchFilter=function(e){if(e&&e.children&&!e.delta._t){for(var t,l=e.children.length,r=0;l>r;r++)t=e.children[r],e.left.hasOwnProperty(t.childName)&&void 0===t.result?delete e.left[t.childName]:e.left[t.childName]!==t.result&&(e.left[t.childName]=t.result);e.setResult(e.left).exit()}};collectChildrenPatchFilter.filterName="collectChildren";var reverseFilter=function(e){if(e.nested&&!e.delta._t){var t,l;for(t in e.delta)l=new ReverseContext(e.delta[t]),e.push(l,t);e.exit()}};reverseFilter.filterName="objects";var collectChildrenReverseFilter=function(e){if(e&&e.children&&!e.delta._t){for(var t,l=e.children.length,r={},i=0;l>i;i++)t=e.children[i],r[t.childName]!==t.result&&(r[t.childName]=t.result);e.setResult(r).exit()}};collectChildrenReverseFilter.filterName="collectChildren",exports.collectChildrenDiffFilter=collectChildrenDiffFilter,exports.objectsDiffFilter=objectsDiffFilter,exports.patchFilter=patchFilter,exports.collectChildrenPatchFilter=collectChildrenPatchFilter,exports.reverseFilter=reverseFilter,exports.collectChildrenReverseFilter=collectChildrenReverseFilter;
|
||||
},{"../contexts/diff":3,"../contexts/patch":4,"../contexts/reverse":5}],13:[function(require,module,exports){
|
||||
var TEXT_DIFF=2,DEFAULT_MIN_LENGTH=60,cachedDiffPatch=null,getDiffMatchPatch=function(t){if(!cachedDiffPatch){var e;if("undefined"!=typeof diff_match_patch)e="function"==typeof diff_match_patch?new diff_match_patch:new diff_match_patch.diff_match_patch;else if("function"==typeof require)try{var i="diff_match_patch_uncompressed",f=require("../../public/external/"+i);e=new f.diff_match_patch}catch(r){e=null}if(!e){if(!t)return null;var a=new Error("text diff_match_patch library not found");throw a.diff_match_patch_not_found=!0,a}cachedDiffPatch={diff:function(t,i){return e.patch_toText(e.patch_make(t,i))},patch:function(t,i){for(var f=e.patch_apply(e.patch_fromText(i),t),r=0;r<f[1].length;r++)if(!f[1][r]){var a=new Error("text patch failed");a.textPatchFailed=!0}return f[0]}}}return cachedDiffPatch},diffFilter=function(t){if("string"===t.leftType){var e=t.options&&t.options.textDiff&&t.options.textDiff.minLength||DEFAULT_MIN_LENGTH;if(t.left.length<e||t.right.length<e)return void t.setResult([t.left,t.right]).exit();var i=getDiffMatchPatch();if(!i)return void t.setResult([t.left,t.right]).exit();var f=i.diff;t.setResult([f(t.left,t.right),0,TEXT_DIFF]).exit()}};diffFilter.filterName="texts";var patchFilter=function(t){if(!t.nested&&t.delta[2]===TEXT_DIFF){var e=getDiffMatchPatch(!0).patch;t.setResult(e(t.left,t.delta[0])).exit()}};patchFilter.filterName="texts";var textDeltaReverse=function(t){var e,i,f,r,a,c,l,n,h=null,d=/^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/;for(f=t.split("\n"),e=0,i=f.length;i>e;e++){r=f[e];var o=r.slice(0,1);"@"===o?(h=d.exec(r),c=e,l=null,n=null,f[c]="@@ -"+h[3]+","+h[4]+" +"+h[1]+","+h[2]+" @@"):"+"===o?(l=e,f[e]="-"+f[e].slice(1),"+"===f[e-1].slice(0,1)&&(a=f[e],f[e]=f[e-1],f[e-1]=a)):"-"===o&&(n=e,f[e]="+"+f[e].slice(1))}return f.join("\n")},reverseFilter=function(t){t.nested||t.delta[2]===TEXT_DIFF&&t.setResult([textDeltaReverse(t.delta[0]),0,TEXT_DIFF]).exit()};reverseFilter.filterName="texts",exports.diffFilter=diffFilter,exports.patchFilter=patchFilter,exports.reverseFilter=reverseFilter;
|
||||
},{}],14:[function(require,module,exports){
|
||||
var isArray="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},diffFilter=function(e){if(e.left===e.right)return void e.setResult(void 0).exit();if("undefined"==typeof e.left){if("function"==typeof e.right)throw new Error("functions are not supported");return void e.setResult([e.right]).exit()}if("undefined"==typeof e.right)return void e.setResult([e.left,0,0]).exit();if("function"==typeof e.left||"function"==typeof e.right)throw new Error("functions are not supported");return e.leftType=null===e.left?"null":typeof e.left,e.rightType=null===e.right?"null":typeof e.right,e.leftType!==e.rightType?void e.setResult([e.left,e.right]).exit():"boolean"===e.leftType||"number"===e.leftType?void e.setResult([e.left,e.right]).exit():("object"===e.leftType&&(e.leftIsArray=isArray(e.left)),"object"===e.rightType&&(e.rightIsArray=isArray(e.right)),e.leftIsArray!==e.rightIsArray?void e.setResult([e.left,e.right]).exit():void 0)};diffFilter.filterName="trivial";var patchFilter=function(e){return"undefined"==typeof e.delta?void e.setResult(e.left).exit():(e.nested=!isArray(e.delta),e.nested?void 0:1===e.delta.length?void e.setResult(e.delta[0]).exit():2===e.delta.length?void e.setResult(e.delta[1]).exit():3===e.delta.length&&0===e.delta[2]?void e.setResult(void 0).exit():void 0)};patchFilter.filterName="trivial";var reverseFilter=function(e){return"undefined"==typeof e.delta?void e.setResult(e.delta).exit():(e.nested=!isArray(e.delta),e.nested?void 0:1===e.delta.length?void e.setResult([e.delta[0],0,0]).exit():2===e.delta.length?void e.setResult([e.delta[1],e.delta[0]]).exit():3===e.delta.length&&0===e.delta[2]?void e.setResult([e.delta[0]]).exit():void 0)};reverseFilter.filterName="trivial",exports.diffFilter=diffFilter,exports.patchFilter=patchFilter,exports.reverseFilter=reverseFilter;
|
||||
},{}],15:[function(require,module,exports){
|
||||
var Pipe=function(t){this.name=t,this.filters=[]};Pipe.prototype.process=function(t){if(!this.processor)throw new Error("add this pipe to a processor before using it");for(var e=this.debug,r=this.filters.length,i=t,s=0;r>s;s++){var o=this.filters[s];if(e&&this.log("filter: "+o.filterName),o(i),"object"==typeof i&&i.exiting){i.exiting=!1;break}}!i.next&&this.resultCheck&&this.resultCheck(i)},Pipe.prototype.log=function(t){console.log("[jsondiffpatch] "+this.name+" pipe, "+t)},Pipe.prototype.append=function(){return this.filters.push.apply(this.filters,arguments),this},Pipe.prototype.prepend=function(){return this.filters.unshift.apply(this.filters,arguments),this},Pipe.prototype.indexOf=function(t){if(!t)throw new Error("a filter name is required");for(var e=0;e<this.filters.length;e++){var r=this.filters[e];if(r.filterName===t)return e}throw new Error("filter not found: "+t)},Pipe.prototype.list=function(){for(var t=[],e=0;e<this.filters.length;e++){var r=this.filters[e];t.push(r.filterName)}return t},Pipe.prototype.after=function(t){var e=this.indexOf(t),r=Array.prototype.slice.call(arguments,1);if(!r.length)throw new Error("a filter is required");return r.unshift(e+1,0),Array.prototype.splice.apply(this.filters,r),this},Pipe.prototype.before=function(t){var e=this.indexOf(t),r=Array.prototype.slice.call(arguments,1);if(!r.length)throw new Error("a filter is required");return r.unshift(e,0),Array.prototype.splice.apply(this.filters,r),this},Pipe.prototype.clear=function(){return this.filters.length=0,this},Pipe.prototype.shouldHaveResult=function(t){if(t===!1)return void(this.resultCheck=null);if(!this.resultCheck){var e=this;return this.resultCheck=function(t){if(!t.hasResult){console.log(t);var r=new Error(e.name+" failed");throw r.noResult=!0,r}},this}},exports.Pipe=Pipe;
|
||||
},{}],16:[function(require,module,exports){
|
||||
var Processor=function(e){this.selfOptions=e,this.pipes={}};Processor.prototype.options=function(e){return e&&(this.selfOptions=e),this.selfOptions},Processor.prototype.pipe=function(e,t){if("string"==typeof e){if("undefined"==typeof t)return this.pipes[e];this.pipes[e]=t}if(e&&e.name){if(t=e,t.processor===this)return t;this.pipes[t.name]=t}return t.processor=this,t},Processor.prototype.process=function(e,t){var s=e;s.options=this.options();for(var r,o,i=t||e.pipe||"default";i;)"undefined"!=typeof s.nextAfterChildren&&(s.next=s.nextAfterChildren,s.nextAfterChildren=null),"string"==typeof i&&(i=this.pipe(i)),i.process(s),o=s,r=i,i=null,s&&s.next&&(s=s.next,i=o.nextPipe||s.pipe||r);return s.hasResult?s.result:void 0},exports.Processor=Processor;
|
||||
},{}]},{},[1])(1)
|
||||
});
|
||||
|
||||
|
||||
//# sourceMappingURL=jsondiffpatch.min.map
|
||||
@@ -0,0 +1,67 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
|
||||
<script type="text/javascript" src="js/jsondiffpatch.min.js"></script>
|
||||
<script type="text/javascript" src="js/jsondiffpatch-formatters.min.js"></script>
|
||||
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||||
<link rel="stylesheet" href="css/html.css" type="text/css" />
|
||||
<link rel="stylesheet" href="css/annotated.css" type="text/css" />
|
||||
</head>
|
||||
<body ng-app="DiffApp">
|
||||
<div ng-controller="DiffCtrl as d">
|
||||
<button type="button" ng-click="d.get_data()">Get Data</button>
|
||||
<button type="button" ng-click="d.compare()">Compare</button>
|
||||
<br/>
|
||||
<textarea id="text1" columns="40" rows="10" ng-model="d.left"></textarea>
|
||||
<div id="visual"></div>
|
||||
<textarea id="text2" columns="40" rows="10" ng-model="d.right"></textarea>
|
||||
<hr/>
|
||||
<div id="annotated"></div>
|
||||
</div>
|
||||
<script>
|
||||
(function(angular) {
|
||||
'use strict';
|
||||
|
||||
angular.module('DiffApp',[]);
|
||||
|
||||
function DiffCtrl($scope) {
|
||||
var self = this;
|
||||
this.left = "";
|
||||
this.right = "";
|
||||
console.log("HEELLLLO!!!");
|
||||
this.get_data = function() {
|
||||
console.log("Starting to load data...");
|
||||
jQuery.getJSON("data.json", function(data) {
|
||||
console.log("Loaded data.json");
|
||||
self.left = JSON.stringify(data, null, 2);
|
||||
$scope.$apply();
|
||||
|
||||
})
|
||||
.fail(function(fail) {
|
||||
console.log("FAIL", fail);
|
||||
});
|
||||
jQuery.getJSON("data2.json", function(json) {
|
||||
console.log("Loaded data2.json");
|
||||
self.right = JSON.stringify(json, null, 2);
|
||||
$scope.$apply();
|
||||
});
|
||||
};
|
||||
this.compare = function() {
|
||||
console.log("Running compare");
|
||||
// beautiful html diff
|
||||
var jsonLeft = JSON.parse(self.left);
|
||||
var jsonRight = JSON.parse(self.right);
|
||||
var delta = jsondiffpatch.diff(jsonLeft, jsonRight);
|
||||
document.getElementById('visual').innerHTML = jsondiffpatch.formatters.html.format(delta, jsonLeft);
|
||||
|
||||
// self-explained json
|
||||
document.getElementById('annotated').innerHTML = jsondiffpatch.formatters.annotated.format(delta, jsonLeft);
|
||||
};
|
||||
};
|
||||
|
||||
angular.module('DiffApp').controller('DiffCtrl', ['$scope', DiffCtrl]);
|
||||
}(window.angular));
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -7,21 +7,21 @@
|
||||
|
||||
var self = this;
|
||||
|
||||
var adjectives = Array('Bold','Breaking','Brilliant','Crescent','Dark|Darkness','Desert|Desert','Eternal','Evening|Darkness','Final','First','Forever','Glorious','Joyful','July','Last','Liberty|Liberty','Magic|Magic','Morning|Morning','Power|Power','Phantom','Present','Roaring|Roar|Scream','Rolling','Sand','Screaming|Roar|Scream','Soaring','Standing|Stand','Star|Star','Twisted','Urgent','Utopian','Valiant');
|
||||
var nouns = Array('Action','Alert','Beauty','Claw','Darkness','Dawn','Day','Desert','Envy','Fall','Fist','Flight','Fury','Guard','Hammer','Hand','Honor','Hope','Hurricane','Liberty','Light','Lightning','Magic','Morning','October','Power','Rain','Repose','Roar','Scream','Skull','Sky','Skies','Shield','Stand','Star','Storm','Streak','Strike','Sun','Thunder','Victory','Whisper','Wind','Wrath');
|
||||
var colors = Array('Black','Blue','Brown','Gray','Green','Indego','Orange','Purple','Rainbow','Red','Scarlet','Silver','Violet','White','Yellow');
|
||||
var actors = Array('Cobra','Condor','Dragon','Eagle','Guardian','Hawk','Hydra','Jackal','King','Knight','Lady','Lion','Scorpion','Spartan','Titan','Victor','Viking','Warrior');
|
||||
var adjectives = Array('Ancient','Bold','Breaking','Brightest','Brilliant','Crescent','Dark|Darkness','Darkest|Darkness','Desert|Desert','Eternal','Evening|Darkness','Final','First','Forever','Giant|Giant','Glorious|Glory','Joyful|Joy','July','Last','Liberty|Liberty','Magic|Magic','Morning|Morning','Power|Power','Phantom','Present','Righteous','Roaring|Roar|Scream','Rolling','Sand','Screaming|Roar|Scream','Silent','Soaring','Standing|Stand','Star|Star','Stunning','Super','Thunderous|Thunder','Twisted','Urgent','Utopian','Valiant');
|
||||
var nouns = Array('Action','Alert','Bane','Beauty','Claw','Darkness','Dawn','Day','Defense','Desert','Envy','Fall','Fist','Flight','Fury','Guard','Glory','Hammer','Hand','Honor','Hope','Hunt','Hurricane','Joy','Liberty','Light','Lightning','Magic','Morning','October','Power','Rain','Response','Repose','Roar','Scream','Skull','Sky','Skies','Shield','Shout','Stand','Star','Storm','Streak','Strike','Sun','Thunder','Victory','Whisper','Wind','Wrath');
|
||||
var colors = Array('Black','Blue','Brown','Golden','Gray','Green','Indego','Orange','Purple','Rainbow','Red','Scarlet','Silver','Violet','White','Yellow');
|
||||
var actors = Array('Cobra','Condor','Dragon','Eagle','Giant','Guardian','Hawk','Hydra','Jackal','King','Knight','Lady','Lion','Scorpion','Spartan','Stranger','Titan','Victor','Viking','Warrior');
|
||||
var mission_grammars = Array(
|
||||
{chance:30, grammar: "{adj1} {noun1}"},
|
||||
{chance:20, grammar: "{adj1} {actor}"},
|
||||
{chance:10, grammar: "{color} {noun1}"},
|
||||
{chance:10, grammar: "{color} {actor}"},
|
||||
{chance:10, grammar: "{actor}'s {noun1}"},
|
||||
{chance:10, grammar: "{noun1} of the {noun2}"},
|
||||
{chance:20, grammar: "{actor}'s {noun1}"},
|
||||
//{chance:10, grammar: "{noun1} of the {noun2}"}, //this one has been producing too many odd lines
|
||||
{chance:10, grammar: "{noun1} of the {actor}"},
|
||||
{chance:10, grammar: "{actor} of the {noun1}"},
|
||||
{chance:10, grammar: "{noun1} of {noun2}"},
|
||||
{chance:10, grammar: "{noun1} of {color} {noun2}"},
|
||||
{chance:5, grammar: "{noun1} of {noun2}"},
|
||||
{chance:5, grammar: "{noun1} of {color} {noun2}"},
|
||||
{chance:10, grammar: "{adj1} {noun1} and {adj2} {noun2}"},
|
||||
{chance:3, grammar: "Attack of the {actor}s"},
|
||||
{chance:3, grammar: "Return of the {actor}s"}
|
||||
|
||||
Reference in new issue
Block a user