Spaces:
Runtime error
Runtime error
naqibhakimi
commited on
Commit
•
797a2e2
1
Parent(s):
efb24f7
initial
Browse files- .DS_Store +0 -0
- .gitattributes +0 -34
- README.md +0 -12
- __pycache__/kb.cpython-39.pyc +0 -0
- __pycache__/utils.cpython-39.pyc +0 -0
- app.py +171 -0
- data/session_01.csv +1 -0
- data/session_01.html +0 -0
- kb.py +96 -0
- lib/bindings/utils.js +189 -0
- lib/tom-select/tom-select.complete.min.js +356 -0
- lib/tom-select/tom-select.css +334 -0
- lib/vis-9.0.4/vis-network.css +0 -0
- lib/vis-9.0.4/vis-network.min.js +0 -0
- lib/vis-9.1.2/vis-network.css +0 -0
- lib/vis-9.1.2/vis-network.min.js +0 -0
- networks/network.html +178 -0
- requirements.txt +6 -0
- utils.py +211 -0
.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
.gitattributes
DELETED
@@ -1,34 +0,0 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
@@ -1,12 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Sk
|
3 |
-
emoji: 💩
|
4 |
-
colorFrom: indigo
|
5 |
-
colorTo: purple
|
6 |
-
sdk: streamlit
|
7 |
-
sdk_version: 1.17.0
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__pycache__/kb.cpython-39.pyc
ADDED
Binary file (4.08 kB). View file
|
|
__pycache__/utils.cpython-39.pyc
ADDED
Binary file (6.13 kB). View file
|
|
app.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import contextlib
|
2 |
+
import streamlit as st
|
3 |
+
import streamlit.components.v1 as components
|
4 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
5 |
+
import utils
|
6 |
+
from kb import KB
|
7 |
+
|
8 |
+
|
9 |
+
import wikipedia
|
10 |
+
MAX_TOPICS= 5
|
11 |
+
BUTTON_COLUMS = 4
|
12 |
+
|
13 |
+
st.header("Extracting a Knowledge Graph from text")
|
14 |
+
|
15 |
+
# Loading the model
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
def load_model():
|
20 |
+
tokenizer = AutoTokenizer.from_pretrained("Babelscape/rebel-large")
|
21 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("Babelscape/rebel-large")
|
22 |
+
return tokenizer, model
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
def generate_kb():
|
28 |
+
st_model_load = st.text('Loading NER model... It may take a while.')
|
29 |
+
tokenizer, model = load_model()
|
30 |
+
st.success('Model loaded!')
|
31 |
+
st_model_load.text("")
|
32 |
+
|
33 |
+
kb = utils.from_text_to_kb(' '.join(st.session_state['wiki_text']), model, tokenizer, "", verbose=True)
|
34 |
+
utils.save_network_html(kb, filename="networks/network.html")
|
35 |
+
st.session_state.kb_chart = "networks/network.html"
|
36 |
+
st.session_state.kb_text = kb.get_textual_representation()
|
37 |
+
st.session_state.error_url = None
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
def show_textbox():
|
42 |
+
if len(st.session_state['wiki_text']) != 0:
|
43 |
+
for i, t in enumerate(st.session_state['wiki_text']):
|
44 |
+
new_expander = st.expander(label=f"{t[:30]}...", expanded=(i==0))
|
45 |
+
with new_expander:
|
46 |
+
st.markdown(t)
|
47 |
+
|
48 |
+
|
49 |
+
def wiki_show_text(page_title):
|
50 |
+
with st.spinner(text="Fetching wiki page..."):
|
51 |
+
# print(st.session_state['wiki_suggestions'])
|
52 |
+
try:
|
53 |
+
page = wikipedia.page(title=page_title, auto_suggest=False)
|
54 |
+
st.session_state['wiki_text'].append(page.summary)
|
55 |
+
st.session_state['topics'].append(page_title.lower())
|
56 |
+
st.session_state['wiki_suggestions'].remove(page_title)
|
57 |
+
show_textbox()
|
58 |
+
|
59 |
+
except wikipedia.DisambiguationError as e:
|
60 |
+
with st.spinner(text="Woops, ambigious term, recalculating options..."):
|
61 |
+
st.session_state['wiki_suggestions'].remove(page_title)
|
62 |
+
temp = st.session_state['wiki_suggestions'] + e.options[:3]
|
63 |
+
st.session_state['wiki_suggestions'] = list(set(temp))
|
64 |
+
show_textbox()
|
65 |
+
except wikipedia.WikipediaException:
|
66 |
+
st.session_state['wiki_suggestions'].remove(page_title)
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
def wiki_add_text(term):
|
71 |
+
|
72 |
+
if len(st.session_state['wiki_text']) > MAX_TOPICS:
|
73 |
+
return
|
74 |
+
try:
|
75 |
+
page = wikipedia.page(title=term, auto_suggest=False)
|
76 |
+
extra_text = page.summary
|
77 |
+
|
78 |
+
st.session_state['wiki_text'].append(extra_text)
|
79 |
+
st.session_state['topics'].append(term.lower())
|
80 |
+
st.session_state['nodes'].remove(term)
|
81 |
+
|
82 |
+
except wikipedia.DisambiguationError as e:
|
83 |
+
with st.spinner(text="Woops, ambigious term, recalculating options..."):
|
84 |
+
st.session_state['nodes'].remove(term)
|
85 |
+
temp = st.session_state['nodes'] + e.options[:3]
|
86 |
+
st.session_state['nodes'] = list(set(temp))
|
87 |
+
except wikipedia.WikipediaException as e:
|
88 |
+
st.session_state['nodes'].remove(term)
|
89 |
+
|
90 |
+
def reset_thread():
|
91 |
+
st.session_state['wiki_text'] = []
|
92 |
+
st.session_state['topics'] = []
|
93 |
+
st.session_state['nodes'] = []
|
94 |
+
st.session_state['has_run_wiki'] = False
|
95 |
+
st.session_state['wiki_suggestions'] = []
|
96 |
+
st.session_state['html_wiki'] = ''
|
97 |
+
|
98 |
+
|
99 |
+
def show_wiki_hub_page():
|
100 |
+
cols = st.columns([7, 1])
|
101 |
+
b_cols = st.columns([2, 1.2, 8])
|
102 |
+
|
103 |
+
with cols[0]:
|
104 |
+
st.text_input("Search", on_change=wiki_show_suggestion, key="text", value="graphs, are, awesome")
|
105 |
+
with cols[1]:
|
106 |
+
st.text('')
|
107 |
+
st.text('')
|
108 |
+
st.button("Search", on_click=wiki_show_suggestion, key="show_suggestion_key")
|
109 |
+
with b_cols[0]:
|
110 |
+
st.button("Generate KB", on_click=generate_kb)
|
111 |
+
with b_cols[1]:
|
112 |
+
st.button("Reset", on_click=reset_thread)
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
def wiki_show_suggestion():
|
117 |
+
with st.spinner(text="Fetching wiki topics..."):
|
118 |
+
text = st.session_state.text
|
119 |
+
if (text is not None) and (text != ""):
|
120 |
+
subjects = text.split(",")[:MAX_TOPICS]
|
121 |
+
for subj in subjects:
|
122 |
+
st.session_state['wiki_suggestions'] += wikipedia.search(subj, results = 3)
|
123 |
+
show_wiki_suggestions_buttons()
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
def show_wiki_suggestions_buttons():
|
128 |
+
if len(st.session_state['wiki_suggestions']) == 0:
|
129 |
+
return
|
130 |
+
num_buttons = len(st.session_state['wiki_suggestions'])
|
131 |
+
# st.session_state['wiki_suggestions'] = list(set(st.session_state['wiki_suggestions']))
|
132 |
+
num_cols = num_buttons if 0 < num_buttons < BUTTON_COLUMS else BUTTON_COLUMS
|
133 |
+
columns = st.columns([1] * num_cols )
|
134 |
+
for q in range(1 + num_buttons//num_cols):
|
135 |
+
for i, (c, s) in enumerate(zip(columns, st.session_state['wiki_suggestions'][q*num_cols: (q+1)*num_cols])):
|
136 |
+
with c:
|
137 |
+
with contextlib.suppress(Exception):
|
138 |
+
st.button(s, on_click=wiki_show_text, args=(s,), key=str(i)+s+"wiki_suggestion")
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
def init_variables():
|
143 |
+
if 'wiki_suggestions' not in st.session_state:
|
144 |
+
st.session_state['wiki_text'] = []
|
145 |
+
st.session_state['topics'] = []
|
146 |
+
st.session_state['nodes'] = []
|
147 |
+
st.session_state['has_run_wiki'] = True
|
148 |
+
st.session_state['wiki_suggestions'] = []
|
149 |
+
st.session_state['html_wiki'] = ''
|
150 |
+
|
151 |
+
|
152 |
+
init_variables()
|
153 |
+
show_wiki_hub_page()
|
154 |
+
# kb chart session state
|
155 |
+
if 'kb_chart' not in st.session_state:
|
156 |
+
st.session_state.kb_chart = None
|
157 |
+
if 'kb_text' not in st.session_state:
|
158 |
+
st.session_state.kb_text = None
|
159 |
+
if 'error_url' not in st.session_state:
|
160 |
+
st.session_state.error_url = None
|
161 |
+
|
162 |
+
# show graph
|
163 |
+
if st.session_state.error_url:
|
164 |
+
st.markdown(st.session_state.error_url)
|
165 |
+
elif st.session_state.kb_chart:
|
166 |
+
with st.container():
|
167 |
+
st.subheader("Generated KB")
|
168 |
+
st.markdown("*You can interact with the graph and zoom.*")
|
169 |
+
html_source_code = open(st.session_state.kb_chart, 'r', encoding='utf-8').read()
|
170 |
+
components.html(html_source_code, width=700, height=700)
|
171 |
+
st.markdown(st.session_state.kb_text)
|
data/session_01.csv
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu. ERIK DEMAINE: Welcome to 6.851 Advanced Data Structures. I am Erik Demaine. You can call me Erik. We have two TAs, Tom Morgan and Justin Zhang. Tom's back there. Justin is late. And this class is about all kinds of very cool data structures. You should have already seen basic data structures like balance binary search trees and things like that, log n time to do wherever you want in one dimension. And here we're going to turn all those data structures on their head and consider them in all sorts of different models and additional cool problems. Today we're going to talk about time travel or temporal data structures, where you're manipulating time as any good time traveler should. Then we'll do geometry where we have higher dimensional data, more than one dimension. Then we'll look at a problem called dynamic optimality, which is, is there one best binary search tree that rules them all? Then we'll look at something called memory hierarchy, which is a way to model more realistic computers which have cache and then more cache and then main memory and then dish and all these different levels. How do you optimize for that? Hashing is probably the most famous, and most popular, most used data structure in computer science. We'll do a little bit on that. Integers, when you know that your data is integers and not just arbitrary black boxes that you can compare or do whatever, you can do a lot better with integers. You usually beat log n time. Often you can get constant time. For example, if you want to do priority queues, you can do square root log log n time. That's the best known randomized. Dynamic graphs, you have a graph you want to store, and the edges are being added and maybe deleted, like you're representing a social network. And people are friending and de-friending. You want to maintain some interesting information about that graph. Strings, you have a piece of text, such as the entire worldwide web. And you want to search for a substring. How do you do that efficiently? It's sort of the Google problem. Or you searching through DNA for patterns, whenever. And finally succinct data structures, which is all about taking what we normally consider optimal space or n space and reducing it down to the very bare minimum of bits of space. Usually if you want to store something where there's 2 to the n possibilities, you want to get away with n bits of space, maybe plus square root of n or something very tiny. So that's the sync data structures. So that's an overview of the entire class. And these are sort of the sections we'll be following. Let me give you a quick administrative overview of what we're doing. Requirements for the class-- I guess, first, attending lecture. Obviously if you don't attend lecture, there'll be videos online. So that's resolvable. But let me know if you're not going to make it. We're going to have problems sets roughly every week. If you're taking the class for credit, they have a very simple rule of one page in, one page out. This is more constraint on us to write problems that have easy or short answers. You probably need to think about them a little bit before they're transparent, but then easy to write up. And then scribing lectures-- so we have a scribe for today, I hope. Here? Yes, good. So most of the lectures have already been scribed in some version, and your goal is to revise that scribe notes that if you don't like handwritten notes, which are also online, then easier for people to read. Let's see. Listeners welcome. We're going to have an open problem session. I really like open problems. I really like solving open problems. So we've done this every time this class has been offered. So if you're interested in also solving open problems, it's optional. I will organize-- in a couple of weeks, we'll have a weekly open problem session and try to solve all the things that push the frontier of advanced data structures. So in classes, we'll see the state of the art. And then we'll change the state of the art in those sessions. I think that's it. Any questions about the class before we get into the fun stuff? All right. Let's do some time traveling. Before I get to time traveling, though, I need to define our model of computation. A theme in this class is that the model of computation you're working with matters. Models matter. And there's lots of different models of computation. We'll see a few of the main ones in this class. And the starting point, and the one we'll be using throughout today, is called a pointer machine. It's an old one from the '80s. And it corresponds to what you might think about if you've done a lot of object-oriented programming, and before that, structure-oriented programming, I guess. So you have a bunch of nodes. They have some fields in them, a constant number of fields. You can think of these as objects or strucs in c It used to be records back in Pascal days, so a lot of the papers call them records. You could just have a constant number of fields. You could think of those numbered, labeled. It doesn't really matter because there's only a constant number of them. Each of the fields could be a pointer to another node, could be a null pointer, or could have some data in it. So I'll just assume that all my data is integers. You can have a pointer to yourself. You can have a pointer over here, whatever you want. A pointer machine would look something like this. In any moment, this is the state of the pointer machine. So you think this as the memory of your computer storing. And then you have some operations that you're allowed to do. That's the computation part of the model. You can think of this as the memory model. What you're allowed to do are create nodes. You can say something like, x equals new node. You can, I don't know, look at fields. You can do x equals y.field. You can set fields, x.field equals y. You can compute on these data, so you can add 5 and 7, do things like that. I'm not going to worry about-- I'll just write et cetera. This is more a model about how everything's organized in memory, not so much about what you're allowed to do to the data items. In this lecture, it won't matter what you're doing to the data items. We never touch them. We just copy them around. So am I missing anything? Probably. I guess you could destroy nodes if you felt like it. But we won't have to today, because we don't want to throw anything away when you're time traveling. It's too dangerous. And then the one catch here is, what are x and y? There's going to be one node in this data structure or in your memory called the root node. And you could think of that as that's the thing you always have in your head. This is like your cache, if you will. It's just got a constant number of things, just like any other node. And x and y are fields of the root. So that sort of ties things down. You're always working relative to the root. But you can look at the data, basically follow this pointer, by looking at the field. You could set one of these pointers-- I think I probably need another operation here, like x equals y.field1, field2, that sort of thing, and maybe the reverse. But you can manipulate all nodes sort of via the root is the idea. You follow pointers, do whatever. So pretty obvious, slightly annoying to write down formally. But that is pointer machine. And what we're going to be talking about today in time travel is suppose someone gives me a pointer machine data structure, for example, balanced binary search tree, linked list. A lot of data structures, especially classic data structures, follow pointer machine model. What we'd like to do is transform that data structure or make a new pointer machine data structure that does extra cool things, namely travel through time. So that's what we're going to do. There's two senses of time travel or temporal data structures that we're going to cover in this class. The one for today is called persistence, where you don't forget anything, like an elephant. And the other one is retroactivity. Persistence will be today. Retroactivity is next class. Basically, these correspond to two models of time travel. Persistence is the branching universe time travel model, where if you make a change in the past, you get a new universe. You never destroy old universes. Retroactivity is more like Back to the Future, when you go back, make a change, and then you can return to the present and see what happened. This is a lot harder to do. And we'll work on that next class. Persistence is what we will do today. So persistence. The general idea of persistence is to remember everything-- the general goal, I would say. And by everything, I mean different versions of the data structure. So you're doing data structures in general. We have update operations and query operations. We're mainly concerned about updates here. Every time you do an update, you think of it as taking a version of the data structure and making a new one. And you never want to destroy old versions. So even though an update like an insert or something changes the data structure, we want to remember that past data as well. And then let's make this reasonable. All data structure operations are relative to a specified version. So an update makes and returns a new version. So when you do an insert, you specify a version of your data structure and the thing you want to insert. And the output is a new version. So then you could insert into that new version, keep going, or maybe go back to the old version, modify that. I haven't said exactly what's allowed here, but this is sort of the general goal. And then there are four levels of persistence that you might want to get. First level is called partial persistence. This is the easiest to obtain. And in partial persistence, you're only allowed to update the latest version, which means the versions are linearly ordered. This is the easiest to think about. And time travel can easily get confusing, so start simple. We have a timeline of various versions on it. This is the latest. And what we can do is update that version. We'll get a new version, and then our latest is this one. What this allows is looking back at the past to an old version and querying that version. So you can still ask questions about the old version, if you want to be able to do a search on any of these data structures. But you can't change them. You can only change the most recent version. So that's nice. It's kind of like time machine on Mac, I guess. If you've ever seen the movie Deja Vu, which is not very common, but it's a good time travel movie, in the first half of the movie, all they can do is look back at the past. Later they discover that actually they have a full persistence model. It takes a while for dramatic effect. In full persistence, you can update anything you want-- so update any version. and so then the versions form a tree. OK. So in this model, maybe you initially have a nice line of versions. But now if I go back to this version and update it, I branch, get a new version here. And then I might keep modifying that version sometimes. Any of these guys can branch. So this is why I call it the branching universe model, when you update your branch. So no version ever gets destroyed here. Again, you can query all versions. But now you can also update any version. But you just make a new version. It's a totally new world. When I update this version, this version knows nothing about all the-- this doesn't know about this future. It's created its own future. There's no way to sort of merge those universes together. It's kind of sad. That's why we have the third level of persistence, which lets us merge timelines. It's great for lots of fiction out there. If you've seen the old TV show Sliders, that would be confluent persistence. So confluent persistence, you can combine two versions to create a new version. And in this case, again, you can't destroy old versions. In persistence, you never destroy versions. So now the versions form a DAG, directed acyclic graph. So now we're allowing-- OK, you make some changes, whatever. You branch your universe, make some changes. And now I can say, OK, take this version of the data structure and this version and recombine them. Get a new version, and then maybe make some more changes. OK, what does combine mean? Well, it depends on your data structure. A lot of data structures have combine operations like if you have linked lists, you have two linked lists, you can concatenate them. That's an easy operation. Even if you have binary search trees, you can concatenate them reasonably easy and combine it into one big binary search tree. So if your data structure has an operation that takes as input two data structures, then what we're saying is now it can take two versions, which is more general. So I could take the same data structure, make some changes in one way, separately make some changes in a different way, and then try to concatenate them or do something crazy. This is hard to do, and most of it is an open problem whether it can be done. But I'll tell you about it. Then there's another level even more than confluent persistence. This is hard to interpret in the time travel world, but it would be functional data structures. If you've ever programmed in a functional programming language, it's a little bit annoying from an algorithm's perspective, because it constrains you to work in a purely functional world. You can never modify anything. OK. Now, we don't want to modify versions. That's fine. But in a functional data structure, you're not allowed to modify any nodes ever. All you can do is make new notes. This is constraining, and you can't always get optimal running times in the functional world. But if you can get a functional data structure, you have all these things, because you can't destroy anything. If you can't destroy nodes, then in particular, you can't destroy versions. And all of these things just work for free. And so a bunch of special cases are known, interesting special cases, like search trees you can do in the functional world. And that makes all of these things easy. So the rest of this lecture is going to be general techniques for doing partial full persistence, what we know about confluent, and what we know about functional, brief overview. Any questions about those goals, problem definitions? Yeah. AUDIENCE: I'm still confused about functional, because-- ERIK DEMAINE: What does functional mean? AUDIENCE: [INAUDIBLE] ERIK DEMAINE: Yeah, I guess you'll see what-- functional looks like all the other things, I agree. You'll see in a moment how we actually implement partial and persistence. We're going to be changing nodes a lot. As long as we still represent the same data in the old versions, we don't have to represent it in the same way. That lets us do things more efficiently. Whereas in functional, you have to represent all the old versions in exactly the way you used to represent them. Here we can kind of mangle things around and it makes things faster. Yeah, good question. So it seems almost the same, but it's nodes versus versions. I haven't really defined a version. But it's just that all the queries answer the same way. That's what you need for persistence. Other questions? All right. Well, let's do some real data structures. We start with partial persistence. This is the easiest. For both partial and full persistence, there is the following result. Any pointer machine data structure, one catch with a constant number of pointers to any node-- so this is constant n degree. In a pointer machine, you always have a constant number of pointers out of a node at most. But for this result to hold, we also need a constant number of pointers into any node. So this is an extra constraint. Can be transformed into another data structure that is partially persistent and does all the things it used to do-- so I'll just say, can be made partially persistent. You have to pay something, but you have to pay very little-- constant amortized factor overhead, multiplicative overhead and constant amount of additive space per change in the data structure. So every time you do a modification in your pointer machine-- you set one of the fields to something-- you have to store that forever. So, I mean, this is the best you could hope to do. You've got to store everything that happened. You pay a constant factor overhead, eh. We're theoreticians. That doesn't matter. Then you get any data structure in this world can be made partially persistent. That's nice. Let's prove it. OK, the idea is pretty simple. Pointer machines are all about nodes and fields. So we just need to simulate whatever the data structure is doing to those nodes and fields in a way that we don't lose all the information and we can still search it very quickly. First idea is to store back pointers. And this is why we need the constant n degree constraint. So if we have a node-- how do I want to draw a node here? So maybe these are the three fields of the node. I want to also store some back pointers. Whenever there is a node that points to this node, I want to have a back pointer that points back so I know where all the pointers came from. If there's only p pointers, then this is fine. There'll be p fields here. So still constant, still in the pointier machine model. OK, I'm going to need some other stuff too. So this is a simple thing, definitely want this. Because if my nodes ever move around, I've got to update the pointers to them. And where are those pointers? Well, the back pointers tell you where they are. Nodes will still be constant size, remain in pointer machine data structure. OK. That's idea one. Idea two is this part. This is going to store something called mods. It could stand for something, but I'll leave it as mods. So these are two of the fields of the data structure. Ah, one convenience here is for back pointers, I'm only going to store it for the latest version of the data structure. Sorry. I forgot about that. We'll come back to that later. And then the idea is to store these modifications. How many modifications? Let's say up to p, twice p. p was the bound on the n degree of a node. So I'm going to allow 2p modifications over here. And what's a modification look like? It's going to consist of three things-- get them in the right order-- the version in which something was changed, the field that got changed, and the value it go changed to. So the idea is that these are the fields here. We're not going to touch those. Once they're set to something-- or, I mean, whatever they are initially, they will stay that way. And so instead of actually changing things like the data structure normally would, we're just going to add modifications here to say, oh, well at this time, this field changed to the value of 5. And then later on, it changed to the value 7. And then later on, this one changed to the value 23, whatever. So that's what they'll look like. There's a limit to how many-- we can only store a constant number of mods to each node. And our constant will be 2p. OK. Those are the ideas, and now it's just a matter of making this all work and analyzing that it's constant amortized overhead. So first thing is if you want to read a field, how would I read a field? This is really easy. First you look at what the field is in the node itself. But then it might have been changed. And so remember when I say read the field, I actually mean while I'm given some version, v, I want to know what is the value of this field at version v, because I want to be able to look at any of the old data structures too. So this would be at version v. I just look through all the modifications. There's constantly many, so it takes constant time to just flip through them and say, well, what changes have happened up to version v? So I look at mods with version less than or equal to v. That will be all the changes that happened up to this point. I see, did this field change? I look at the latest one. That will be how I read the field of the node, so constant time. There's lots of ways to make this efficient in practice. But for our purposes, it doesn't matter. It's constant. The hard part is how do you change a field? Because there might not be any room in the mod structure. So to modify, say we want to set node.field equal to x. What we do is first we check, is there any space in the mod structure? If there's any blank mods, so if the node is not full, we just add a mod. So a mod will look like now field x. Just throw that in there. Because right at this moment-- so we maintain a time counter, just increment it ever time we do a change. This field changed that value. So that's the easy case. The trouble, of course, is if the node is full-- the moment you've all been waiting for. So what we're going to do here is make a new node. We've ran out of space. So we need to make a new node. We're not going to touch the old node, just going to let it sit. It still maintains all those old versions. Now we want a new node that represents the latest and greatest of this node. OK. So make a new node. I'll call it node prime to distinguish from node, where with all the mods, and this modification in particular, applied. OK, so we make a new version of this node. It's going to have some different fields, whatever was the latest version represented by those mods. It's still going to have back pointers, so we have to maintain all those back pointers. And now the mod, initially, is going to be empty, because we just applied them all. So this new node doesn't have any recent mods. Old node represents the old versions. This node is going to represent the new versions. What's wrong with this picture? AUDIENCE: Update pointers. ERIK DEMAINE: Update pointers. Yeah, there's pointers to the old version of the node, which are fine for the old versions of the data structure. But for the latest version of the data structure, this node has moved to this new location. So if there are any old pointers to that node, we've got to update them in the current version. We have to update them to point to this node instead. The old versions are fine, but the new version is in trouble. Other questions or all the same answer? Yeah. AUDIENCE: So if you wanted to read an old version but you just have the new version, [INAUDIBLE]? ERIK DEMAINE: OK-- AUDIENCE: [INAUDIBLE] ERIK DEMAINE: The question is essentially, how do we hold on to versions? Essentially, you can think of a version of the data structure as where the root node is. That's probably the easiest. I mean, in general, we're representing versions by a number, v. But we always start at the root. And so you've given the data structure, which is represented by the root node. And you say, search for the value 5. Is it in this binary search tree or whatever? And then you just start navigating from the root, but you know I'm inversion a million or whatever. I know what version I'm looking for. So you start with the root, which never changes, let's say. And then you follow pointers that essentially tell you for that version where you should be going. I guess at the root version, it's a little trickier. You probably want a little array that says for this version, here's the root node. But that's a special case. Yeah. Another question? AUDIENCE: So on the new node that you created, the fields that you copied, you also have to have a version for them, right? Because [INAUDIBLE]? ERIK DEMAINE: These-- AUDIENCE: Or do you version the whole node? ERIK DEMAINE: Here we're versioning the whole node. The original field values represent what was originally there, whenever this node was created. Then the mods specify what time the fields change. So I don't think we need times here. All right. So we've got to update two kinds of pointers. There's regular pointers, which live in the fields, which are things pointing to the node. But then there's also back pointers. Because if this is a pointer to a node, then there'll be a back pointer back to the node. And all of those have to change. Conveniently, the back pointers are easy. So if they're back pointers to the node, we change them to the node prime. How do we find the back pointers? Well, we just follow all the pointers and then there will be back pointers there. Because I said we're only maintaining backed pointers for the latest version, I don't need to preserve the old versions of those backed pointers. So I just go in and I change them. It takes constant time, because the constant number of things I point to, each one as a back pointer. So this is cheap. There's no persistence here. That's an advantage of partial persistence. The hard part is updating the pointers because those live in fields. I need to remember the old versions of those fields. And that we do recursively. Because to change those pointers, that's a field update. That's something exactly of this form. So that's the same operation but on a different node. So I just do that. I claim this is good. That's the end of the algorithm. Now we need to analyze it. How do we analyze it? Any guesses? AUDIENCE: Amortize it. ERIK DEMAINE: Amortized analysis, exactly the answer I was looking for. OK. [INAUDIBLE] amortization. The most powerful technique in amortization is probably the potential method. So we're going to use that. There's a sort of more-- you'll see a charging argument in a moment. We want the potential function to represent when this data structure is in a bad state. Intuitively, it's in a bad state when a lot of nodes are full. Because then as soon as you make a change in them, they will burst, and you have to do all this crazy recursion and stuff. This case is nice and cheap. We just add a modification, constant time. This case, not so nice because we recurse. And then that's going to cause more recursions and all sorts of chaos could happen. So there's probably a few different potential functions that would work here. And an old version of these nodes I said should be the number of full nodes. But I think we can make life a little bit easier by the following. Basically, the total number of modifications-- not quite the total, almost the total. So I'm going to do c times the sum of the number of mods in latest version nodes. OK. So because we sort of really only care about-- we're only changing the latest version, so I really only care about nodes that live in the latest version. What do I mean by this? Well, when I made this new node prime, this becomes the new representation of that node. The old version is dead. We will never change it again. If we're modifying, we will never even look at it again. Because now everything points to here. So I don't really care about that node. It's got a ton of mods. But what's nice is that when I create this new node, now the mod list is empty. So I start from scratch, just like reinstalling your operating system. It's a good feeling. And so the potential goes down by, I guess, c times 2 times p. When I do this change, potential goes down by basically p. AUDIENCE: Is c any constant or-- ERIK DEMAINE: c will be a constant to be determined. I mean, it could be 1. It depends how you want to define it. I'm going to use the CLRS notion of amortized cost, which is actual cost plus change in potential. And then I need a constant here, because I'm measuring a running time versus some combinatorial quantity. So this will be to match the running time that we'll get to. OK. So what is amortized cost? There's sort of two cases modification. There's the cheap case and the not so cheap case. In general, amortized cost-- in both cases, it's going to be at most-- well, first of all, we do some constant work just to figure out all this stuff, make copies, whatever. So that's some constant time. That's the part that I don't want to try to measure. Then potentially, we add a new mod. If we add a mod, that increases the potential by c. Because we're just counting mods, multiplying by c. So we might get plus 1 mod. This is going to be an upper bound. We don't always add 1, but worst case, we always had 1, let's say. And then there's this annoying part. And this might happen, might not happen. So then there's a plus maybe. If this happens, we decrease the potential because we empty out the mods for that node in terms of the latest version. So then we get a negative 2cp, change in potential. And then we'd have to pay I guess up to p recursions. Because we have to-- how many pointers are there to me? Well, at most p of them, because there are at most p pointers to any node. OK. This is kind of a weird-- it's not exactly algebra here. I have this thing, recursions. But if you think about how this would expand, all right, this is constant time. That's good. And then if we do this-- I'll put a question mark here. It might be here. It might not. If it's not here, find constant. If it is here, then this gets expanded into this thing. It's a weird way to write a recurrence. But we get p times whatever is in this right hand side. OK. But then there's this minus 2cp. So we're going to get p times 2c here. That's the initial cost. So that will cancel with this. And then we might get another recursion. But every time we get a recursion, all the terms cancel. So it doesn't matter whether this is here or not. You get 0, which is great. And you're left with the original 2c. Constant. OK. [INAUDIBLE] potential functions are always a little crazy. What's happening here is that, OK, maybe you add a mod. That's cheap. But when we have to do this work and we have to do this recursion-- this is up to 2p updates or recursions-- we are charging it to the emptying of this node. The number of mods went from 2p down to 0. And so we're just charging this update cost to that modification. So if you like charging schemes, this is much more intuitive. But with charging schemes, it's always a little careful. You have to make sure you're not double charging. Here it's obvious that you're not double charging. Kind of a cool and magical. This is a paper by Driscoll, Sarnak, Sleator, Tarjan from 1989. So it's very early days of amortization. But they knew how to do it. Question? AUDIENCE: [INAUDIBLE] ERIK DEMAINE: What happens if you overflow the root? Yeah, I never thought about the root before today. But I think the way to fix the root is just you have one big table that says, for a given version-- I guess a simple way would be to say, not only is a version a number, but it's also a pointer to the root. There we go. Pointer machine. So that way you're just always explicitly maintaining the root copy or the pointer. Because otherwise, you're in trouble. AUDIENCE: Then can you go back to [INAUDIBLE]. ERIK DEMAINE: So in order to refer to an old version, you have to have the pointer to that root node. If you want to do it just from a version number, look at the data structure. Just from a version number, you would need some kind of lookup table, which is outside the pointer machine. So you could do it in a real computer, but a pointer machine is not technically allowed. So it's slightly awkward. No arrays are allowed in pointer machines, in case that wasn't clear. Another question? AUDIENCE: [INAUDIBLE] constant space to store for [INAUDIBLE]. And also, what if we have really big numbers [INAUDIBLE]? ERIK DEMAINE: In this model, in the pointer machine model, we're assuming that whatever the data is in the items take constant space each. If you want to know about bigger things in here, then refer to future lectures. This is time travel, after all. Just go to a future class and then come back. [LAUGHS] So we'll get there, but right now, we're not thinking about what's in here. Whatever big thing you're trying to store, you reduce it down to constant size things. And then you spread them around nodes of a pointer machine. How you do that, that's up to the data structure. We're just transforming the data structure to be persistent. OK, you could ask about other models than pointer machines, but we're going to stick to pointer machines here. All right. That was partial persistence. Let's do full persistence. That was too easy. Same paper does full persistence. Systems That was just a warm up. Full persistence is actually not that much harder. So let me tell you basically what changes. There are two issues. One is that everything here has to change and not by much. We're still going to use back pointers. We're still going to have my mods. The number of mods is going to be slightly different but basically the same. Back pointers no longer just refer to the latest version. We have to maintain back pointers in all versions. So that's annoying. But hey, that's life. The amortization, the potential function will change slightly but basically not much. Sort of the bigger issue you might first wonder about, and it's actually the most challenging technically, is versions are no longer numbers. Because it's not a line. Versions are nodes in a tree. You should probably call them vertices in a tree to distinguish them from nodes in the pointer machine. OK, so you've got this tree of versions. And then versions are just some point on that tree. This is annoying because we like lines. We don't like trees as much. So what we're going to do is linearize the tree. Like, when in doubt, cheat. How do we do this? With tree traversal. Imagine I'm going to draw a super complicated tree of versions. Say there are three versions. OK. I don't want to number them, because that would be kind of begging the question. So let's just call them x, y, and z. All right. I mean, it's a directed tree, because we have the older versions. This is like the original version. And we made a change. We made a different change on the same version. What I'd like to do is a traversal of that tree, like a regular, as if you're going to sort those nodes. Actually, let me use color, high def here. So here's our traversal of the tree. And I want to look at the first and the last time I visit each node. So here's the first time I visit x. So I'll write this is the beginning of x. Capital X. Then this is the first time I visit y, so it's beginning of y. And then this is the last time I visit y, so it's the end of y. And then, don't care. Then this is the beginning of z. And this is the end of z. And then this is the end x. If I write those sequentially, I get bxbyeybzez, because this is so easy, ex. OK, you can think of these as parentheses, right? For whatever reason I chose b and e for beginning and ending, but this is like open parens, close parens. This is easy to do in linear time. I think you all know how. Except it's not a static problem. Versions are changing all the time. We're adding versions. We're never deleting versions, but we're always adding stuff to here. It's a little awkward, but the idea is I want to maintain this order, maintain the begin and the end of each you might say subtree of versions. This string, from bx to ex, represents all of the stuff in x's subtree, in the rooted tree starting at x. How do I maintain that? Using a data structure. So we're going to use something, a data structure we haven't yet seen. It will be in lecture 8. This is a time travel data structure, so I'm allowed to do that. So order maintenance data structure. You can think of this as a magical linked list. Let me tell you what the magical linked list can do. You can insert-- I'm going to call it an item, because node would be kind of confusing given where we are right now. You can insert a new item in the list immediately before or after a given item. OK. This is like a regular linked list. Here's a regular linked list. And if I'm given a particular item like this one, I can say, well, insert a new item right here. You say, OK. Fine. I'll just make a new node and relink here, relink there. Constant time, right? So in an order maintenance data structure, you can do this in constant time. Wow! So amazing. OK, catch is the second operation you can do. Maybe I'll number these. This is the update. Then there's the query. The query is, what is the relative order of two notes, of two items? x and y. So now I give you this node and this node. And I say, which is to the left? Which is earlier in the order? I want to know, is x basically less than y in terms of the order in the list? Or is y less than x? And an order maintenance data structure can do this in constant time. Now it doesn't look like your mother's linked list, I guess. It's not the link list you learned in school. It's a magical linked list that can somehow answer these queries. How? Go to lecture 7. OK. Forward reference, lecture 8, sorry. For now, we're just going to assume that this magical data structure exists. So in constant time, this is great. Because if we're maintaining these b's and e's, we want to maintain the order that these things appear in. If we want to create a new version, like suppose we were just creating version z, well, it used to be everything without this bz, ez. And we'd just insert two items in here, bz and ez. They're right next to each other. And if we were given version x, we could just say, oh, we'll look at ex and insert two items right before it. Or you can put them right after bx. I mean, there's no actual order here. So it could have been y first and then z or z first and then y. So it's really easy to add a new version in constant time. You just do two of these insert operations. And now you have this magical order operation, which if I'm given two versions-- I don't know, v and w-- and I want to know is v an ancestor of w, now I can do it in constant time. So this lets me do a third operation, which is, is version v an ancestor of version w? Because that's going to be true if and only if bv is an ev nest around bw and ew. OK. So that's just three tests. They're probably not all even necessary. This one always holds. But if these guys fit in between these guys, then you know-- now, what this tells us, what we care about here, is reading fields. When we read a field, we said, oh, we'll apply all the modifications that apply to version v. Before that, that was a linear order. So it's just all versions less than or equal to v. Now it's all versions that are ancestors of v. Given a mod, we need to know, does this mod apply to my version? And now I tell you, I can do that in constant time through magic. I just test these order relations. If they hold, then that mod applies to my version. So w's the version we're testing. v is some version in the mod. And I want to know, am descendant of that version? If so, the mod applies. And I update what the field is. I can do all pairwise ancestor checks and figure out, what is the most recent version in my ancestor history that modified a given field? That lets me read a field in constant time. Constants are getting kind of big at this point, but it can be done. Clear? A little bit of a black box here. But now we've gotten as far as reading. And we don't need to change much else. So this is good news Maybe I'll give you a bit of a diff. So full persistence, fully persistent theorem-- done. OK. Same theorem just with full persistence. How do we do it? We store back pointers now for all versions. It's a little bit annoying. But how many mods do we use? There's lots of ways to get this to work, but I'm going to change this number to 2 times d plus p plus 1. Wait, what's d? d is the number of fields here. OK. We said it was constant number fields. I never said what that constant is. d for out degree, I guess. So p is in degree, max in degree. d is max out degree. So just slightly more-- that main reason for this is because back pointers now are treated like everyone else. We have to treat both the out pointers and the in pointers as basically the same. So instead of p, we have d plus p. And there's a plus 1 just for safety. It gets my amortization to work, hopefully. OK. Not much else-- this page is all the same. Mods are still, you give versions, fields, values, reading. OK, well, this is no longer less than or equal to v. But this is now with a version, sort of the nearest version, that's an ancestor of v. That's what we were just talking about. So that can be done in constant time. Check it for all of them, constant work. OK. That was the first part. Now we get to the hard part, which is modification. This is going to be different. Maybe you I should just erase-- yeah, I think I'll erase everything, except the first clause. OK. If a node is not full, we'll just add a mod, just like before. What changes is when a node is full. Here we have to do something completely different. Why? Because if we just make a new version of this node that has empty mods, this one's still full. And I can keep modifying the same version. This new node that I just erased represents some new version. But if I keep modifying an old version, which I can do in full persistence, this node keeps being full. And I keep paying potentially huge cost. If all the nodes were full, and when I make this change every node gets copied, and then I make a change to the same version, every node gets copied again. This is going to take linear time per operation. So I can't do the old strategy. I need to somehow make this node less full. This is where we're definitely not functional. None of this was functional, but now I'm going to change an old node, not just make a new one in a more drastic way. Before I was adding a mod. That's not a functional operation. Now I'm actually going to remove mods from a node to rebalance. So what I'd like to do is split the node into two halves. OK. So I had some big node that was-- I'll draw it-- completely full. Now I'm going to make two nodes. Here we go. This one is going to be half full. This one's going to be half full of mods. OK. The only question left is, what do I do with all these things? Basically what I'd like to do is have the-- on the one hand, I want to have the old node. It's just where it used to be. I've just removed half of the mods, the second half, the later half. What does that mean? I don't know. Figure it out. It's linearized. I haven't thought deeply about that. Now we're going to make a new node with the second half of the mods. It's more painful than I thought. In reality, these mods represent a tree of modifications. And what you need to do is find a partition of that tree into two roughly equal halves. You can actually do a one third, 2/3 split. That's also in a future lecture, which whose number I forget. So really, you're splitting this tree into two roughly balanced halves. And so this 2 might actually need to change to a 3, but it's a constant. OK. What I want is for this to represent a subtree of versions. Let me draw the picture. So here's a tree of versions represented by the old mods. I'd like to cut out a subtree rooted at some node. So let's just assume for now this has exactly half the nodes. And this has half the nodes. In reality, I think it can be one third, 2/3. OK. But let's keep it convenient. So I want the new node to represent this subtree and this node to represent everything else. This node is as if this stuff hasn't happened yet. I mean, so it represents all these old versions that do not, that are not in the subtree. This represents all the latest stuff. So what I'm going to do is like before, I want to apply some mods to these fields. And whatever minds were relevant at this point, whatever had been applied, I apply those to the fields here. And so that means I can remove all of these mods. I only cared about these ones. Update these fields accordingly. I still have the other mods to represent all the other changes that could be in that subtree. OK. So we actually split the tree, and we apply mods to new nodes. Anything else I need to say? Oh, now we need to update pointers. That's always the fun part. Let's go over here. So old node hasn't moved. But this new node has moved. So for all of these versions, I want to change the pointer that used to point to old node should now point to new node. In this version, it's fine. It should still point to old node, because this represents all those old versions. But for the new version, that version in the subtree, I've got to point here instead. OK. So how many pointers could there be to this node that need to change. That's a tricky part in this analysis. Think about it for a while. I mean, in this new node, whatever is pointed to by either here or here in the new node also has a return pointer. All pointers are bidirectional. So we don't really care about whether they're forward or backward. How many pointers are there here? Well, there's d here and there's p here. But then there's also some additional pointers represented over here. How many? Well, if we assume this magical 50/50 split, there's right now d plus p plus 1 mods over here, half of them. Each of them might be a pointer to some other place, which has a return pointer in that version. So number of back pointers that we need to update is going to be this, 2 times d 2 times p plus 1. So recursively update at most 2 times d plus 2 times p plus 1 pointers to the node. The good news is this is really only half of them or some fraction of them. It used to be-- well, there were more pointers before. We don't have to deal with these ones. That's where we're saving, and that's why this amortization works. Let me give you a potential function that makes this work-- is minus c times sum of the number of empty mod slots. It's kind of the same potential but before we had this notion of dead and alive nodes. Now everything's alive because everything could change at any moment. So instead, I'm going to measure how much room I have in each node. Before I had no room in this node. Now I have half the space in both nodes. So that's good news. Whenever we have this recursion, we can charge it to a potential decrease. Fee goes down by-- because I have a negative sign here-- c times, oh man, 2 times d plus p plus 1, I think. Because there's d plus p plus 1 space here, d plus p plus 1 space here. I mean, we added one whole new node. And total capacity of a node in mods is 2 times d plus p plus 1. So we get that times c. And this is basically just enough, because this is 2 times d plus 2 times p plus 2. And here we have a plus 1. And so the recursion gets annihilated by 2 times d plus 2 times p plus 1. And then there's one c left over to absorb whatever constant cost there was to do all this other work. So I got the constants just to work, except that I cheated and it's really a one third, 2/3 split. So probably all of these constants have to change, such is life. But I think you get the idea. Any questions about full persistence? This is fun stuff, time travel. Yeah? AUDIENCE: So in the first half of the thing where the if, there's room you can put it in. ERIK DEMAINE: Right. AUDIENCE: I have a question about how we represent the version. Because before when we said restore now [INAUDIBLE]. It made more sense if now was like a timestamp or something. ERIK DEMAINE: OK. Right, so how do we represent a version even here or anywhere? When we do a modification, an update, in the data structure, we want to return the new version. Basically, we're going to actually store the DAG of versions. And a version is going to be represented by a pointer into this DAG. One of the nodes in this DAG becomes a version. Every node in this DAG is going to store a pointer to the corresponding b character and a corresponding e character in this data structure, which then lets you do anything you want. Then you can query against that version, whether it's an ancestor of another version. So yeah, I didn't mention that. Versions are nodes in here. Nodes in here have pointers to the b's and e's. And vice versa, the b's and e's have pointers back to the corresponding version node. And then you can keep track of everything. Good question. Yeah? AUDIENCE: [INAUDIBLE] question. Remind me what d is in this. ERIK DEMAINE: Oh, d was the maximum out degree. It's the number of fields in a node, as defined right here. Other questions? Whew. OK, a little breather. That was partial persistence, full persistence. This is, unfortunately, the end of the really good results. As long as we have constant degree nodes, in and out degree, we can do all. We can do for persistence for free. Obviously there are practical constants involved here. But in theory, you can do this perfectly. Before we go on to confluence, there is one positive result, which is what if you don't like amortize bounds. There are various reasons amortize bounds might not be good. Maybe you really care about every operation being no slower than it was except by a constant factor. We're amortizing here, so some operations get really slow. But the others are all fast to compensate. You can deamortize, it's called. You can get constant worst case slowdown for partial persistence. This is a result of Garret Brodle from the late '90s, '97. For full persistence-- so it's an open problem. I don't know if people have worked on that. All right. So some, mostly good results. Let's move on to confluent persistence where things get a lot more challenging. Lots of things go out the window with confluent persistence. In particular, your versions are now a DAG. It's a lot harder to linearize a DAG. Trees are not that far from pads. But DAGs are quite far from pads, unfortunately. But that's not all that goes wrong. Let me first tell you the kind of end effect as a user. Imagine you have a data structure. Think of it as a list, I guess, which is a list of characters in your document. You're using vi or Word, your favorite, whatever. It's a text editor. You've got a string of words. And now you like to do things like copy and paste. It's a nice operation. So you select an interval of the string and you copy it. And then you paste it somewhere else. So now you've got two copies of that string. This is, in some sense, what you might call a confluent operation, because-- yeah, maybe a cleaner way to think of it is the following. You have your string. Now I have an operation, which is split it. So now I have two strings. OK. And now I have an operation, which is split it. Now I have three strings. OK. Now I have an operation which is concatenate. So I can, for example, reconstruct the original string-- actually, I have the original string. No biggie. Let's say-- because I have all versions. I never lose them. So now instead, I'm going to cut the string here, let's say. So now I have this and this. And now I can do things like concatenate from here to here to here. And I will get this plus this plus this. OK. This guy moved here. So that's a copy/paste operation with a constant number of splits and concatenates. I could also do cut and paste. With confluence, I can do crazy cuts and pastes in all sorts of ways. So what? Well, the so what is I can actually double the size of my data structure in a constant number of operations. I can take, for example, the entire string and concatenate it to itself. That will double the number of characters, number of elements in there. I can do that again and again and again. So in u updates, I can potentially get a data structure size 2 to the u. Kind of nifty. I think this is why confluence is cool. It's also why it's hard. So not a big surprise. But, here we go. In that case, the version DAG, for reference, looks like this. You're taking the same version, combining it. So here I'm assuming I have a concatenate operation. And so the effect here, every time I do this, I double the size. All right. What do I want to say about confluent persistence? All right. Let me start with the most general result, which is by Fiat and Kaplan in 2003. They define a notion called effective depth of a version. Let me just write it down. It's kind of like if you took this DAG and expanded it out to be a tree of all possible paths. Instead of point to the same node, you could just duplicate that node and then have pointers left and right. OK. So if I did that, of course, this size grows exponentially. It explicitly represents the size of my data structure. At the bottom, if I have u things, I'm going to have 2 to the u leaves at the bottom. But then I can easily measure the number of paths from the root to the same version. At the bottom, I still label it, oh, those are all v. They're all the same version down there. So exponential number of paths, if I take log, I get what I call effective depth. It's like if you somehow could rebalance that tree, this is the best you could hope to do. It's not really a lower bound. But it's a number. It's a thing. OK. Then the result they achieve is that the overhead is log the number of updates plus-- this is a multiplicative overhead, so you take your running time. You multiply it by this. And this is a time and a space overhead. So maximum effective depth of all versions, maybe even sum of effective depths, but we'll just say max to be safe. Sorry-- sum over all the operations. This is per operation. You pay basically the effective depth of that operation as a factor. Now, the annoying thing is if you have this kind of set up where the size grew exponentially, then number of paths is exponential. Log of the number of paths is linear in u. And so this factor could be as much as u, linear slowdown. Now, Fiat and Kaplan argue linear slowdown is not that bad, because if you weren't even persistent, if you did this in the naive way of just recopying the data, you were actually spending exponential time to build the final data structure. It has exponential size. Just to represent it explicitly requires exponential time, so losing a linear factor to do u operations and now u squared time instead of 2 to the u. So it's a big improvement to do this. The downside of this approach is that even if you have a version DAG that looks like this, even if the size of the data structure is staying normal, staying linear, so this potential, you could be doubling the size. But we don't know what this merge operation is. Maybe it just throws away one of the versions or does something-- somehow takes half the nodes from one side, half the nodes from the other side maybe. These operations do preserve size. Then there's no great reason why it should be a linear slowdown, but it is. OK? So it's all right but not great. And it's the best general result we know. They also prove a lower bound. So lower bound is some effect of depth, total bits of space. OK. What does this mean? So even if this is not happening, the number of bits of space you need in the worst case-- this does not apply to every data structure. That's one catch. They give a specific data structure where you need this much space. So it's similar to this kind of picture. We'll go into the details. And you need this much space. Now, this is kind of bad, because if there's u operations, and each of these is u, that's u squared space. So we actually need a factor u blow up in space. It looks like. But to be more precise, what this means is that you need omega e of v space, and therefore time overhead per update, if-- this is not written in the paper-- queries are free. Implicit here, they just want to slow down and increase space for the updates you do, which is pretty natural. Normally you think of queries as not increasing space. But in order to construct this lower bound, they actually do this many queries. So they do e of v queries and then one update. And they say, oh well, space had to go up by an extra e of v. So if you only charge updates for the space, then yes, you have to lose potentially a linear factor, this effect of death, potentially u. But if you also charge the queries, it's still constant in their example. So open question, for confluent persistence, can you achieve constant everything? Constant time and space overheads, multiplicative factor per operation, both updates and queries. So if you charge the queries, potentially you could get constant everything. This is a relatively new realization. And no one knows how to do this yet. Nice challenge. I think maybe we'll work on that in our first problem session. I would like to. Questions about that result? I'm not going to prove the result. But it is a fancy rebalancing of those kinds of pictures to get this log. There are other results I'd like to tell you about. So brand new result-- that was from 2003. This is from 2012-- no, '11, '11, sorry. It's SOTO, which is in January, so it's a little confusing. Is it '11? Maybe '12. Actually now I'm not sure. It's February already, right? A January, either this year or last year. It's not as general a transformation. It's only going to hold in what's called a disjoint case. But it gets a very good bound-- not quite constant, but logarithmic. OK, logarithmic would also be nice. Or log, log n, whatever n is. Pick your favorite n, number of operations, say. OK. If you assume that confluent operations are performed only on two versions with no shared nodes-- OK, this would be a way to forbid this kind of behavior where I concatenate the data structure with itself. All the nodes are common. If I guarantee that maybe I, you know, slice this up, slice it, dice it, wherever, and then re-emerge them in some other order, but I never use two copies of the same piece, that would be a valid confluent operation over here. This is quite a strong restriction that you're not allowed. If you try to, who knows what happens. Behavior's undefined. So won't tell you, oh, those two versions have this node in common. You've got to make a second copy of it. So somehow you have to guarantee that control and operations never overlap. But they can be reordered. Then you can get order log n overhead. n is the number of operations. I have a sketch of a proof of this but not very much time to talk about it. All right. Let me give you a quick picture. In general, the versions form a DAG. But if you make this assumption, and you look at a single node, and look at all the versions where that node appears, that is a tree. Because you're not allowed to remerge versions that have the same node. So while the big picture is a DAG, the small picture of a single guy is some tree. I'm drawing all these wiggly lines because there are all these versions where the node isn't changing. This is the entire version DAG. And then some of these nodes-- some of these versions, I should say-- that node that we're thinking about changes. OK, whenever it branches, it's probably because the actual node changed, maybe. I don't know. Anyway there are some dots here where the version changed, some of the leaves, maybe, that changed. Maybe some of them haven't yet. In fact, let's see. Here where it's change, it could be that we destroyed the node. Maybe it's gone from the actual data structure. But there still may be versions down here. It's not really a tree. It's a whole DAG of stuff down there. So that's kind of ugly. Where never the node still exists, I guess that is an actual leaf of the DAG. So those are OK. But as soon as I maybe delete that node, then there can be a whole subtree down there. OK. So now if you look at an arbitrary version, so what we're thinking about is how to implement reading, let's say. Reading and writing are more or less the same. I give you a version. I give you a node, and I give you a field. I want to know, what is the value of that field, that node, that version? So now where could a version fall? Well it has to be in this subtree. Because the node has to exist. And then it's maybe a pointer. A pointer could be to another node, which also has this kind of picture. They could be overlapping trees. In general, there are three cases. Either you're lucky, and the version you're talking about is a version where the node was changed. In that case, the data is just stored right there. That's easy. So you could just say, oh, how did the node change? Oh, that's what the field is. OK, follow the pointer. A slightly harder case it's a version in between two such changes. And maybe these are not updates. So I sort of want to know, what was the previous version where this node changed in constant time? It can be done. Not constant time, actually, logarithmic time, using a data structure called link-cut trees, another fun black box for now, which we will cover in lecture 19, far in the future. OK. Well, that's one case. There's also the version where maybe a version is down here in a subtree. I guess then the node didn't exist. Well, all these things can happen. And that's even harder. It's messy. They use another trick, which is called fractional cascading, which I'm not even going to try to describe what it means. But it's got a very cool name. Because we'll be covering it in lecture 3. So stay tuned for that. I'm not going to say how it applies to this setting, but it's a necessary step in here. In the remaining zero minutes, let me tell you a little bit about functional data structures. [LAUGHTER] Beauty of time travel. Functional-- I just want to give you some examples of things that can be done functionally. There's a whole book about functional data structures by Okasaki. It's pretty cool. A simple example is balanced BSTs. So if you just want to get log n time for everything, you can do that functionally. It's actually really easy. You pick your favorite balance BST, like red black trees. You implement it top down so you never follow parent pointers. So you don't need parent pointers. So then as you make changes down the tree, you just copy. It's called path copying. Whenever you're about to make a change, make a copy of that node. So you end up copying all the change nodes and all their ancestors. There's only log n of them, so it takes log n time. Clear? Easy. It's a nice technique. Sometimes path copying is very useful. Like link-cut trees, for example, can be made functional. We don't know what they are, but they're basically a BST. And you can make them functional. We use that in a paper. All right. Deques. These are doubly ended queues. So it's like a stack and a queue and everything. You can insert and delete from the beginning and the end. People start to know what these are now, because Python calls him that. But you can also do concatenation with deques in constant time per operation. This is cool. Deques are not very hard to make functional. But you can do deques and you can concatenate them like we were doing in the figure that's right behind this board. Constant time split is a little harder. That's actually one of my open problems. Can you do lists with split and concatenate in constant time-- functionally or confluently, persistently, or whatever? Another example-- oh, you can do a mix of the two. You can get log n search in constant time deque operations, is you can do tries. So a try is a tree with a fixed topology. Think of it as a directory tree. So maybe you're using Subversion. Subversion has time travel operations. You can copy an entire subtree from one version and stick it into a new version, another version. So you get a version DAG. It's a confluently persistent data structure-- not implemented optimally, because we don't necessarily know how. But there is one paper. This actually came from the open problem section of this class four years ago, I think. It's with Eric Price and Stefan Langerman. You can get very good results. I won't write them down because it takes a while. Basically log the degree of the nodes factor and get functional, and you can be even fancier and get slightly better bounds like log log the degree and get confluently persistent with various tricks, including using all of these data structures. So if you want to implement subversion optimally, that is known how to be done but hasn't actually been done yet. Because there are those pesky constant factors. I think that's all. What is known about functional is there's a log n separation. You can be log n away from the best. That's the worst separation known, between functional and just a regular old data structure. It'd be nice to improve that. Lots of open problems here. Maybe we'll work on them next time.
|
data/session_01.html
ADDED
The diff for this file is too large to render.
See raw diff
|
|
kb.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import wikipedia
|
2 |
+
|
3 |
+
class KB():
|
4 |
+
def __init__(self):
|
5 |
+
self.entities = {} # { entity_title: {...} }
|
6 |
+
self.relations = [] # [ head: entity_title, type: ..., tail: entity_title,
|
7 |
+
# meta: { article_url: { spans: [...] } } ]
|
8 |
+
self.sources = {} # { article_url: {...} }
|
9 |
+
|
10 |
+
def merge_with_kb(self, kb2):
|
11 |
+
for r in kb2.relations:
|
12 |
+
article_url = list(r["meta"].keys())[0]
|
13 |
+
source_data = kb2.sources[article_url]
|
14 |
+
self.add_relation(r, source_data["article_title"],
|
15 |
+
source_data["article_publish_date"])
|
16 |
+
|
17 |
+
def are_relations_equal(self, r1, r2):
|
18 |
+
return all(r1[attr] == r2[attr] for attr in ["head", "type", "tail"])
|
19 |
+
|
20 |
+
def exists_relation(self, r1):
|
21 |
+
return any(self.are_relations_equal(r1, r2) for r2 in self.relations)
|
22 |
+
|
23 |
+
def merge_relations(self, r2):
|
24 |
+
r1 = [r for r in self.relations
|
25 |
+
if self.are_relations_equal(r2, r)][0]
|
26 |
+
|
27 |
+
# if different article
|
28 |
+
article_url = list(r2["meta"].keys())[0]
|
29 |
+
if article_url not in r1["meta"]:
|
30 |
+
r1["meta"][article_url] = r2["meta"][article_url]
|
31 |
+
|
32 |
+
# if existing article
|
33 |
+
else:
|
34 |
+
spans_to_add = [span for span in r2["meta"][article_url]["spans"]
|
35 |
+
if span not in r1["meta"][article_url]["spans"]]
|
36 |
+
r1["meta"][article_url]["spans"] += spans_to_add
|
37 |
+
|
38 |
+
def get_wikipedia_data(self, candidate_entity):
|
39 |
+
try:
|
40 |
+
page = wikipedia.page(candidate_entity, auto_suggest=False)
|
41 |
+
return {"title": page.title, "url": page.url, "summary": page.summary}
|
42 |
+
except Exception:
|
43 |
+
return None
|
44 |
+
|
45 |
+
def add_entity(self, e):
|
46 |
+
self.entities[e["title"]] = {k:v for k,v in e.items() if k != "title"}
|
47 |
+
|
48 |
+
def add_relation(self, r, article_title, article_publish_date):
|
49 |
+
# check on wikipedia
|
50 |
+
candidate_entities = [r["head"], r["tail"]]
|
51 |
+
entities = [self.get_wikipedia_data(ent) for ent in candidate_entities]
|
52 |
+
|
53 |
+
# if one entity does not exist, stop
|
54 |
+
if any(ent is None for ent in entities):
|
55 |
+
return
|
56 |
+
|
57 |
+
# manage new entities
|
58 |
+
for e in entities:
|
59 |
+
self.add_entity(e)
|
60 |
+
|
61 |
+
# rename relation entities with their wikipedia titles
|
62 |
+
r["head"] = entities[0]["title"]
|
63 |
+
r["tail"] = entities[1]["title"]
|
64 |
+
|
65 |
+
# add source if not in kb
|
66 |
+
article_url = list(r["meta"].keys())[0]
|
67 |
+
if article_url not in self.sources:
|
68 |
+
self.sources[article_url] = {
|
69 |
+
"article_title": article_title,
|
70 |
+
"article_publish_date": article_publish_date
|
71 |
+
}
|
72 |
+
|
73 |
+
# manage new relation
|
74 |
+
if not self.exists_relation(r):
|
75 |
+
self.relations.append(r)
|
76 |
+
else:
|
77 |
+
self.merge_relations(r)
|
78 |
+
|
79 |
+
def get_textual_representation(self):
|
80 |
+
res = "" + "### Entities\n"
|
81 |
+
for e in self.entities.items():
|
82 |
+
# shorten summary
|
83 |
+
e_temp = e[0], {
|
84 |
+
k: f"{v[:100]}..." if k == "summary" else v
|
85 |
+
for k, v in e[1].items()
|
86 |
+
}
|
87 |
+
res += f"- {e_temp}\n"
|
88 |
+
res += "\n"
|
89 |
+
res += "### Relations\n"
|
90 |
+
for r in self.relations:
|
91 |
+
res += f"- {r}\n"
|
92 |
+
res += "\n"
|
93 |
+
res += "### Sources\n"
|
94 |
+
for s in self.sources.items():
|
95 |
+
res += f"- {s}\n"
|
96 |
+
return res
|
lib/bindings/utils.js
ADDED
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
function neighbourhoodHighlight(params) {
|
2 |
+
// console.log("in nieghbourhoodhighlight");
|
3 |
+
allNodes = nodes.get({ returnType: "Object" });
|
4 |
+
// originalNodes = JSON.parse(JSON.stringify(allNodes));
|
5 |
+
// if something is selected:
|
6 |
+
if (params.nodes.length > 0) {
|
7 |
+
highlightActive = true;
|
8 |
+
var i, j;
|
9 |
+
var selectedNode = params.nodes[0];
|
10 |
+
var degrees = 2;
|
11 |
+
|
12 |
+
// mark all nodes as hard to read.
|
13 |
+
for (let nodeId in allNodes) {
|
14 |
+
// nodeColors[nodeId] = allNodes[nodeId].color;
|
15 |
+
allNodes[nodeId].color = "rgba(200,200,200,0.5)";
|
16 |
+
if (allNodes[nodeId].hiddenLabel === undefined) {
|
17 |
+
allNodes[nodeId].hiddenLabel = allNodes[nodeId].label;
|
18 |
+
allNodes[nodeId].label = undefined;
|
19 |
+
}
|
20 |
+
}
|
21 |
+
var connectedNodes = network.getConnectedNodes(selectedNode);
|
22 |
+
var allConnectedNodes = [];
|
23 |
+
|
24 |
+
// get the second degree nodes
|
25 |
+
for (i = 1; i < degrees; i++) {
|
26 |
+
for (j = 0; j < connectedNodes.length; j++) {
|
27 |
+
allConnectedNodes = allConnectedNodes.concat(
|
28 |
+
network.getConnectedNodes(connectedNodes[j])
|
29 |
+
);
|
30 |
+
}
|
31 |
+
}
|
32 |
+
|
33 |
+
// all second degree nodes get a different color and their label back
|
34 |
+
for (i = 0; i < allConnectedNodes.length; i++) {
|
35 |
+
// allNodes[allConnectedNodes[i]].color = "pink";
|
36 |
+
allNodes[allConnectedNodes[i]].color = "rgba(150,150,150,0.75)";
|
37 |
+
if (allNodes[allConnectedNodes[i]].hiddenLabel !== undefined) {
|
38 |
+
allNodes[allConnectedNodes[i]].label =
|
39 |
+
allNodes[allConnectedNodes[i]].hiddenLabel;
|
40 |
+
allNodes[allConnectedNodes[i]].hiddenLabel = undefined;
|
41 |
+
}
|
42 |
+
}
|
43 |
+
|
44 |
+
// all first degree nodes get their own color and their label back
|
45 |
+
for (i = 0; i < connectedNodes.length; i++) {
|
46 |
+
// allNodes[connectedNodes[i]].color = undefined;
|
47 |
+
allNodes[connectedNodes[i]].color = nodeColors[connectedNodes[i]];
|
48 |
+
if (allNodes[connectedNodes[i]].hiddenLabel !== undefined) {
|
49 |
+
allNodes[connectedNodes[i]].label =
|
50 |
+
allNodes[connectedNodes[i]].hiddenLabel;
|
51 |
+
allNodes[connectedNodes[i]].hiddenLabel = undefined;
|
52 |
+
}
|
53 |
+
}
|
54 |
+
|
55 |
+
// the main node gets its own color and its label back.
|
56 |
+
// allNodes[selectedNode].color = undefined;
|
57 |
+
allNodes[selectedNode].color = nodeColors[selectedNode];
|
58 |
+
if (allNodes[selectedNode].hiddenLabel !== undefined) {
|
59 |
+
allNodes[selectedNode].label = allNodes[selectedNode].hiddenLabel;
|
60 |
+
allNodes[selectedNode].hiddenLabel = undefined;
|
61 |
+
}
|
62 |
+
} else if (highlightActive === true) {
|
63 |
+
// console.log("highlightActive was true");
|
64 |
+
// reset all nodes
|
65 |
+
for (let nodeId in allNodes) {
|
66 |
+
// allNodes[nodeId].color = "purple";
|
67 |
+
allNodes[nodeId].color = nodeColors[nodeId];
|
68 |
+
// delete allNodes[nodeId].color;
|
69 |
+
if (allNodes[nodeId].hiddenLabel !== undefined) {
|
70 |
+
allNodes[nodeId].label = allNodes[nodeId].hiddenLabel;
|
71 |
+
allNodes[nodeId].hiddenLabel = undefined;
|
72 |
+
}
|
73 |
+
}
|
74 |
+
highlightActive = false;
|
75 |
+
}
|
76 |
+
|
77 |
+
// transform the object into an array
|
78 |
+
var updateArray = [];
|
79 |
+
if (params.nodes.length > 0) {
|
80 |
+
for (let nodeId in allNodes) {
|
81 |
+
if (allNodes.hasOwnProperty(nodeId)) {
|
82 |
+
// console.log(allNodes[nodeId]);
|
83 |
+
updateArray.push(allNodes[nodeId]);
|
84 |
+
}
|
85 |
+
}
|
86 |
+
nodes.update(updateArray);
|
87 |
+
} else {
|
88 |
+
// console.log("Nothing was selected");
|
89 |
+
for (let nodeId in allNodes) {
|
90 |
+
if (allNodes.hasOwnProperty(nodeId)) {
|
91 |
+
// console.log(allNodes[nodeId]);
|
92 |
+
// allNodes[nodeId].color = {};
|
93 |
+
updateArray.push(allNodes[nodeId]);
|
94 |
+
}
|
95 |
+
}
|
96 |
+
nodes.update(updateArray);
|
97 |
+
}
|
98 |
+
}
|
99 |
+
|
100 |
+
function filterHighlight(params) {
|
101 |
+
allNodes = nodes.get({ returnType: "Object" });
|
102 |
+
// if something is selected:
|
103 |
+
if (params.nodes.length > 0) {
|
104 |
+
filterActive = true;
|
105 |
+
let selectedNodes = params.nodes;
|
106 |
+
|
107 |
+
// hiding all nodes and saving the label
|
108 |
+
for (let nodeId in allNodes) {
|
109 |
+
allNodes[nodeId].hidden = true;
|
110 |
+
if (allNodes[nodeId].savedLabel === undefined) {
|
111 |
+
allNodes[nodeId].savedLabel = allNodes[nodeId].label;
|
112 |
+
allNodes[nodeId].label = undefined;
|
113 |
+
}
|
114 |
+
}
|
115 |
+
|
116 |
+
for (let i=0; i < selectedNodes.length; i++) {
|
117 |
+
allNodes[selectedNodes[i]].hidden = false;
|
118 |
+
if (allNodes[selectedNodes[i]].savedLabel !== undefined) {
|
119 |
+
allNodes[selectedNodes[i]].label = allNodes[selectedNodes[i]].savedLabel;
|
120 |
+
allNodes[selectedNodes[i]].savedLabel = undefined;
|
121 |
+
}
|
122 |
+
}
|
123 |
+
|
124 |
+
} else if (filterActive === true) {
|
125 |
+
// reset all nodes
|
126 |
+
for (let nodeId in allNodes) {
|
127 |
+
allNodes[nodeId].hidden = false;
|
128 |
+
if (allNodes[nodeId].savedLabel !== undefined) {
|
129 |
+
allNodes[nodeId].label = allNodes[nodeId].savedLabel;
|
130 |
+
allNodes[nodeId].savedLabel = undefined;
|
131 |
+
}
|
132 |
+
}
|
133 |
+
filterActive = false;
|
134 |
+
}
|
135 |
+
|
136 |
+
// transform the object into an array
|
137 |
+
var updateArray = [];
|
138 |
+
if (params.nodes.length > 0) {
|
139 |
+
for (let nodeId in allNodes) {
|
140 |
+
if (allNodes.hasOwnProperty(nodeId)) {
|
141 |
+
updateArray.push(allNodes[nodeId]);
|
142 |
+
}
|
143 |
+
}
|
144 |
+
nodes.update(updateArray);
|
145 |
+
} else {
|
146 |
+
for (let nodeId in allNodes) {
|
147 |
+
if (allNodes.hasOwnProperty(nodeId)) {
|
148 |
+
updateArray.push(allNodes[nodeId]);
|
149 |
+
}
|
150 |
+
}
|
151 |
+
nodes.update(updateArray);
|
152 |
+
}
|
153 |
+
}
|
154 |
+
|
155 |
+
function selectNode(nodes) {
|
156 |
+
network.selectNodes(nodes);
|
157 |
+
neighbourhoodHighlight({ nodes: nodes });
|
158 |
+
return nodes;
|
159 |
+
}
|
160 |
+
|
161 |
+
function selectNodes(nodes) {
|
162 |
+
network.selectNodes(nodes);
|
163 |
+
filterHighlight({nodes: nodes});
|
164 |
+
return nodes;
|
165 |
+
}
|
166 |
+
|
167 |
+
function highlightFilter(filter) {
|
168 |
+
let selectedNodes = []
|
169 |
+
let selectedProp = filter['property']
|
170 |
+
if (filter['item'] === 'node') {
|
171 |
+
let allNodes = nodes.get({ returnType: "Object" });
|
172 |
+
for (let nodeId in allNodes) {
|
173 |
+
if (allNodes[nodeId][selectedProp] && filter['value'].includes((allNodes[nodeId][selectedProp]).toString())) {
|
174 |
+
selectedNodes.push(nodeId)
|
175 |
+
}
|
176 |
+
}
|
177 |
+
}
|
178 |
+
else if (filter['item'] === 'edge'){
|
179 |
+
let allEdges = edges.get({returnType: 'object'});
|
180 |
+
// check if the selected property exists for selected edge and select the nodes connected to the edge
|
181 |
+
for (let edge in allEdges) {
|
182 |
+
if (allEdges[edge][selectedProp] && filter['value'].includes((allEdges[edge][selectedProp]).toString())) {
|
183 |
+
selectedNodes.push(allEdges[edge]['from'])
|
184 |
+
selectedNodes.push(allEdges[edge]['to'])
|
185 |
+
}
|
186 |
+
}
|
187 |
+
}
|
188 |
+
selectNodes(selectedNodes)
|
189 |
+
}
|
lib/tom-select/tom-select.complete.min.js
ADDED
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* Tom Select v2.0.0-rc.4
|
3 |
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
*/
|
5 |
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).TomSelect=t()}(this,(function(){"use strict"
|
6 |
+
function e(e,t){e.split(/\s+/).forEach((e=>{t(e)}))}class t{constructor(){this._events={}}on(t,i){e(t,(e=>{this._events[e]=this._events[e]||[],this._events[e].push(i)}))}off(t,i){var s=arguments.length
|
7 |
+
0!==s?e(t,(e=>{if(1===s)return delete this._events[e]
|
8 |
+
e in this._events!=!1&&this._events[e].splice(this._events[e].indexOf(i),1)})):this._events={}}trigger(t,...i){var s=this
|
9 |
+
e(t,(e=>{if(e in s._events!=!1)for(let t of s._events[e])t.apply(s,i)}))}}var i
|
10 |
+
const s="[̀-ͯ·ʾ]",n=new RegExp(s,"g")
|
11 |
+
var o
|
12 |
+
const r={"æ":"ae","ⱥ":"a","ø":"o"},l=new RegExp(Object.keys(r).join("|"),"g"),a=[[67,67],[160,160],[192,438],[452,652],[961,961],[1019,1019],[1083,1083],[1281,1289],[1984,1984],[5095,5095],[7429,7441],[7545,7549],[7680,7935],[8580,8580],[9398,9449],[11360,11391],[42792,42793],[42802,42851],[42873,42897],[42912,42922],[64256,64260],[65313,65338],[65345,65370]],c=e=>e.normalize("NFKD").replace(n,"").toLowerCase().replace(l,(function(e){return r[e]})),d=(e,t="|")=>{if(1==e.length)return e[0]
|
13 |
+
var i=1
|
14 |
+
return e.forEach((e=>{i=Math.max(i,e.length)})),1==i?"["+e.join("")+"]":"(?:"+e.join(t)+")"},p=e=>{if(1===e.length)return[[e]]
|
15 |
+
var t=[]
|
16 |
+
return p(e.substring(1)).forEach((function(i){var s=i.slice(0)
|
17 |
+
s[0]=e.charAt(0)+s[0],t.push(s),(s=i.slice(0)).unshift(e.charAt(0)),t.push(s)})),t},u=e=>{void 0===o&&(o=(()=>{var e={}
|
18 |
+
a.forEach((t=>{for(let s=t[0];s<=t[1];s++){let t=String.fromCharCode(s),n=c(t)
|
19 |
+
if(n!=t.toLowerCase()){n in e||(e[n]=[n])
|
20 |
+
var i=new RegExp(d(e[n]),"iu")
|
21 |
+
t.match(i)||e[n].push(t)}}}))
|
22 |
+
var t=Object.keys(e)
|
23 |
+
t=t.sort(((e,t)=>t.length-e.length)),i=new RegExp("("+d(t)+"[̀-ͯ·ʾ]*)","g")
|
24 |
+
var s={}
|
25 |
+
return t.sort(((e,t)=>e.length-t.length)).forEach((t=>{var i=p(t).map((t=>(t=t.map((t=>e.hasOwnProperty(t)?d(e[t]):t)),d(t,""))))
|
26 |
+
s[t]=d(i)})),s})())
|
27 |
+
return e.normalize("NFKD").toLowerCase().split(i).map((e=>{if(""==e)return""
|
28 |
+
const t=c(e)
|
29 |
+
if(o.hasOwnProperty(t))return o[t]
|
30 |
+
const i=e.normalize("NFC")
|
31 |
+
return i!=e?d([e,i]):e})).join("")},h=(e,t)=>{if(e)return e[t]},g=(e,t)=>{if(e){for(var i,s=t.split(".");(i=s.shift())&&(e=e[i]););return e}},f=(e,t,i)=>{var s,n
|
32 |
+
return e?-1===(n=(e+="").search(t.regex))?0:(s=t.string.length/e.length,0===n&&(s+=.5),s*i):0},v=e=>(e+"").replace(/([\$\(-\+\.\?\[-\^\{-\}])/g,"\\$1"),m=(e,t)=>{var i=e[t]
|
33 |
+
if("function"==typeof i)return i
|
34 |
+
i&&!Array.isArray(i)&&(e[t]=[i])},y=(e,t)=>{if(Array.isArray(e))e.forEach(t)
|
35 |
+
else for(var i in e)e.hasOwnProperty(i)&&t(e[i],i)},O=(e,t)=>"number"==typeof e&&"number"==typeof t?e>t?1:e<t?-1:0:(e=c(e+"").toLowerCase())>(t=c(t+"").toLowerCase())?1:t>e?-1:0
|
36 |
+
class b{constructor(e,t){this.items=e,this.settings=t||{diacritics:!0}}tokenize(e,t,i){if(!e||!e.length)return[]
|
37 |
+
const s=[],n=e.split(/\s+/)
|
38 |
+
var o
|
39 |
+
return i&&(o=new RegExp("^("+Object.keys(i).map(v).join("|")+"):(.*)$")),n.forEach((e=>{let i,n=null,r=null
|
40 |
+
o&&(i=e.match(o))&&(n=i[1],e=i[2]),e.length>0&&(r=v(e),this.settings.diacritics&&(r=u(r)),t&&(r="\\b"+r)),s.push({string:e,regex:r?new RegExp(r,"iu"):null,field:n})})),s}getScoreFunction(e,t){var i=this.prepareSearch(e,t)
|
41 |
+
return this._getScoreFunction(i)}_getScoreFunction(e){const t=e.tokens,i=t.length
|
42 |
+
if(!i)return function(){return 0}
|
43 |
+
const s=e.options.fields,n=e.weights,o=s.length,r=e.getAttrFn
|
44 |
+
if(!o)return function(){return 1}
|
45 |
+
const l=1===o?function(e,t){const i=s[0].field
|
46 |
+
return f(r(t,i),e,n[i])}:function(e,t){var i=0
|
47 |
+
if(e.field){const s=r(t,e.field)
|
48 |
+
!e.regex&&s?i+=1/o:i+=f(s,e,1)}else y(n,((s,n)=>{i+=f(r(t,n),e,s)}))
|
49 |
+
return i/o}
|
50 |
+
return 1===i?function(e){return l(t[0],e)}:"and"===e.options.conjunction?function(e){for(var s,n=0,o=0;n<i;n++){if((s=l(t[n],e))<=0)return 0
|
51 |
+
o+=s}return o/i}:function(e){var s=0
|
52 |
+
return y(t,(t=>{s+=l(t,e)})),s/i}}getSortFunction(e,t){var i=this.prepareSearch(e,t)
|
53 |
+
return this._getSortFunction(i)}_getSortFunction(e){var t,i,s
|
54 |
+
const n=this,o=e.options,r=!e.query&&o.sort_empty?o.sort_empty:o.sort,l=[],a=[]
|
55 |
+
if("function"==typeof r)return r.bind(this)
|
56 |
+
const c=function(t,i){return"$score"===t?i.score:e.getAttrFn(n.items[i.id],t)}
|
57 |
+
if(r)for(t=0,i=r.length;t<i;t++)(e.query||"$score"!==r[t].field)&&l.push(r[t])
|
58 |
+
if(e.query){for(s=!0,t=0,i=l.length;t<i;t++)if("$score"===l[t].field){s=!1
|
59 |
+
break}s&&l.unshift({field:"$score",direction:"desc"})}else for(t=0,i=l.length;t<i;t++)if("$score"===l[t].field){l.splice(t,1)
|
60 |
+
break}for(t=0,i=l.length;t<i;t++)a.push("desc"===l[t].direction?-1:1)
|
61 |
+
const d=l.length
|
62 |
+
if(d){if(1===d){const e=l[0].field,t=a[0]
|
63 |
+
return function(i,s){return t*O(c(e,i),c(e,s))}}return function(e,t){var i,s,n
|
64 |
+
for(i=0;i<d;i++)if(n=l[i].field,s=a[i]*O(c(n,e),c(n,t)))return s
|
65 |
+
return 0}}return null}prepareSearch(e,t){const i={}
|
66 |
+
var s=Object.assign({},t)
|
67 |
+
if(m(s,"sort"),m(s,"sort_empty"),s.fields){m(s,"fields")
|
68 |
+
const e=[]
|
69 |
+
s.fields.forEach((t=>{"string"==typeof t&&(t={field:t,weight:1}),e.push(t),i[t.field]="weight"in t?t.weight:1})),s.fields=e}return{options:s,query:e.toLowerCase().trim(),tokens:this.tokenize(e,s.respect_word_boundaries,i),total:0,items:[],weights:i,getAttrFn:s.nesting?g:h}}search(e,t){var i,s,n=this
|
70 |
+
s=this.prepareSearch(e,t),t=s.options,e=s.query
|
71 |
+
const o=t.score||n._getScoreFunction(s)
|
72 |
+
e.length?y(n.items,((e,n)=>{i=o(e),(!1===t.filter||i>0)&&s.items.push({score:i,id:n})})):y(n.items,((e,t)=>{s.items.push({score:1,id:t})}))
|
73 |
+
const r=n._getSortFunction(s)
|
74 |
+
return r&&s.items.sort(r),s.total=s.items.length,"number"==typeof t.limit&&(s.items=s.items.slice(0,t.limit)),s}}const w=e=>{if(e.jquery)return e[0]
|
75 |
+
if(e instanceof HTMLElement)return e
|
76 |
+
if(e.indexOf("<")>-1){let t=document.createElement("div")
|
77 |
+
return t.innerHTML=e.trim(),t.firstChild}return document.querySelector(e)},_=(e,t)=>{var i=document.createEvent("HTMLEvents")
|
78 |
+
i.initEvent(t,!0,!1),e.dispatchEvent(i)},I=(e,t)=>{Object.assign(e.style,t)},C=(e,...t)=>{var i=A(t);(e=x(e)).map((e=>{i.map((t=>{e.classList.add(t)}))}))},S=(e,...t)=>{var i=A(t);(e=x(e)).map((e=>{i.map((t=>{e.classList.remove(t)}))}))},A=e=>{var t=[]
|
79 |
+
return y(e,(e=>{"string"==typeof e&&(e=e.trim().split(/[\11\12\14\15\40]/)),Array.isArray(e)&&(t=t.concat(e))})),t.filter(Boolean)},x=e=>(Array.isArray(e)||(e=[e]),e),k=(e,t,i)=>{if(!i||i.contains(e))for(;e&&e.matches;){if(e.matches(t))return e
|
80 |
+
e=e.parentNode}},F=(e,t=0)=>t>0?e[e.length-1]:e[0],L=(e,t)=>{if(!e)return-1
|
81 |
+
t=t||e.nodeName
|
82 |
+
for(var i=0;e=e.previousElementSibling;)e.matches(t)&&i++
|
83 |
+
return i},P=(e,t)=>{y(t,((t,i)=>{null==t?e.removeAttribute(i):e.setAttribute(i,""+t)}))},E=(e,t)=>{e.parentNode&&e.parentNode.replaceChild(t,e)},T=(e,t)=>{if(null===t)return
|
84 |
+
if("string"==typeof t){if(!t.length)return
|
85 |
+
t=new RegExp(t,"i")}const i=e=>3===e.nodeType?(e=>{var i=e.data.match(t)
|
86 |
+
if(i&&e.data.length>0){var s=document.createElement("span")
|
87 |
+
s.className="highlight"
|
88 |
+
var n=e.splitText(i.index)
|
89 |
+
n.splitText(i[0].length)
|
90 |
+
var o=n.cloneNode(!0)
|
91 |
+
return s.appendChild(o),E(n,s),1}return 0})(e):((e=>{if(1===e.nodeType&&e.childNodes&&!/(script|style)/i.test(e.tagName)&&("highlight"!==e.className||"SPAN"!==e.tagName))for(var t=0;t<e.childNodes.length;++t)t+=i(e.childNodes[t])})(e),0)
|
92 |
+
i(e)},V="undefined"!=typeof navigator&&/Mac/.test(navigator.userAgent)?"metaKey":"ctrlKey"
|
93 |
+
var j={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:!0,diacritics:!0,create:null,createOnBlur:!1,createFilter:null,highlight:!0,openOnFocus:!0,shouldOpen:null,maxOptions:50,maxItems:null,hideSelected:null,duplicates:!1,addPrecedence:!1,selectOnTab:!1,preload:null,allowEmptyOption:!1,loadThrottle:300,loadingClass:"loading",dataAttr:null,optgroupField:"optgroup",valueField:"value",labelField:"text",disabledField:"disabled",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:!1,sortField:"$order",searchField:["text"],searchConjunction:"and",mode:null,wrapperClass:"ts-wrapper",controlClass:"ts-control",dropdownClass:"ts-dropdown",dropdownContentClass:"ts-dropdown-content",itemClass:"item",optionClass:"option",dropdownParent:null,copyClassesToDropdown:!1,placeholder:null,hidePlaceholder:null,shouldLoad:function(e){return e.length>0},render:{}}
|
94 |
+
const q=e=>null==e?null:D(e),D=e=>"boolean"==typeof e?e?"1":"0":e+"",N=e=>(e+"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),z=(e,t)=>{var i
|
95 |
+
return function(s,n){var o=this
|
96 |
+
i&&(o.loading=Math.max(o.loading-1,0),clearTimeout(i)),i=setTimeout((function(){i=null,o.loadedSearches[s]=!0,e.call(o,s,n)}),t)}},R=(e,t,i)=>{var s,n=e.trigger,o={}
|
97 |
+
for(s in e.trigger=function(){var i=arguments[0]
|
98 |
+
if(-1===t.indexOf(i))return n.apply(e,arguments)
|
99 |
+
o[i]=arguments},i.apply(e,[]),e.trigger=n,o)n.apply(e,o[s])},H=(e,t=!1)=>{e&&(e.preventDefault(),t&&e.stopPropagation())},B=(e,t,i,s)=>{e.addEventListener(t,i,s)},K=(e,t)=>!!t&&(!!t[e]&&1===(t.altKey?1:0)+(t.ctrlKey?1:0)+(t.shiftKey?1:0)+(t.metaKey?1:0)),M=(e,t)=>{const i=e.getAttribute("id")
|
100 |
+
return i||(e.setAttribute("id",t),t)},Q=e=>e.replace(/[\\"']/g,"\\$&"),G=(e,t)=>{t&&e.append(t)}
|
101 |
+
function U(e,t){var i=Object.assign({},j,t),s=i.dataAttr,n=i.labelField,o=i.valueField,r=i.disabledField,l=i.optgroupField,a=i.optgroupLabelField,c=i.optgroupValueField,d=e.tagName.toLowerCase(),p=e.getAttribute("placeholder")||e.getAttribute("data-placeholder")
|
102 |
+
if(!p&&!i.allowEmptyOption){let t=e.querySelector('option[value=""]')
|
103 |
+
t&&(p=t.textContent)}var u,h,g,f,v,m,O={placeholder:p,options:[],optgroups:[],items:[],maxItems:null}
|
104 |
+
return"select"===d?(h=O.options,g={},f=1,v=e=>{var t=Object.assign({},e.dataset),i=s&&t[s]
|
105 |
+
return"string"==typeof i&&i.length&&(t=Object.assign(t,JSON.parse(i))),t},m=(e,t)=>{var s=q(e.value)
|
106 |
+
if(null!=s&&(s||i.allowEmptyOption)){if(g.hasOwnProperty(s)){if(t){var a=g[s][l]
|
107 |
+
a?Array.isArray(a)?a.push(t):g[s][l]=[a,t]:g[s][l]=t}}else{var c=v(e)
|
108 |
+
c[n]=c[n]||e.textContent,c[o]=c[o]||s,c[r]=c[r]||e.disabled,c[l]=c[l]||t,c.$option=e,g[s]=c,h.push(c)}e.selected&&O.items.push(s)}},O.maxItems=e.hasAttribute("multiple")?null:1,y(e.children,(e=>{var t,i,s
|
109 |
+
"optgroup"===(u=e.tagName.toLowerCase())?((s=v(t=e))[a]=s[a]||t.getAttribute("label")||"",s[c]=s[c]||f++,s[r]=s[r]||t.disabled,O.optgroups.push(s),i=s[c],y(t.children,(e=>{m(e,i)}))):"option"===u&&m(e)}))):(()=>{const t=e.getAttribute(s)
|
110 |
+
if(t)O.options=JSON.parse(t),y(O.options,(e=>{O.items.push(e[o])}))
|
111 |
+
else{var r=e.value.trim()||""
|
112 |
+
if(!i.allowEmptyOption&&!r.length)return
|
113 |
+
const t=r.split(i.delimiter)
|
114 |
+
y(t,(e=>{const t={}
|
115 |
+
t[n]=e,t[o]=e,O.options.push(t)})),O.items=t}})(),Object.assign({},j,O,t)}var W=0
|
116 |
+
class J extends(function(e){return e.plugins={},class extends e{constructor(...e){super(...e),this.plugins={names:[],settings:{},requested:{},loaded:{}}}static define(t,i){e.plugins[t]={name:t,fn:i}}initializePlugins(e){var t,i
|
117 |
+
const s=this,n=[]
|
118 |
+
if(Array.isArray(e))e.forEach((e=>{"string"==typeof e?n.push(e):(s.plugins.settings[e.name]=e.options,n.push(e.name))}))
|
119 |
+
else if(e)for(t in e)e.hasOwnProperty(t)&&(s.plugins.settings[t]=e[t],n.push(t))
|
120 |
+
for(;i=n.shift();)s.require(i)}loadPlugin(t){var i=this,s=i.plugins,n=e.plugins[t]
|
121 |
+
if(!e.plugins.hasOwnProperty(t))throw new Error('Unable to find "'+t+'" plugin')
|
122 |
+
s.requested[t]=!0,s.loaded[t]=n.fn.apply(i,[i.plugins.settings[t]||{}]),s.names.push(t)}require(e){var t=this,i=t.plugins
|
123 |
+
if(!t.plugins.loaded.hasOwnProperty(e)){if(i.requested[e])throw new Error('Plugin has circular dependency ("'+e+'")')
|
124 |
+
t.loadPlugin(e)}return i.loaded[e]}}}(t)){constructor(e,t){var i
|
125 |
+
super(),this.order=0,this.isOpen=!1,this.isDisabled=!1,this.isInvalid=!1,this.isValid=!0,this.isLocked=!1,this.isFocused=!1,this.isInputHidden=!1,this.isSetup=!1,this.ignoreFocus=!1,this.hasOptions=!1,this.lastValue="",this.caretPos=0,this.loading=0,this.loadedSearches={},this.activeOption=null,this.activeItems=[],this.optgroups={},this.options={},this.userOptions={},this.items=[],W++
|
126 |
+
var s=w(e)
|
127 |
+
if(s.tomselect)throw new Error("Tom Select already initialized on this element")
|
128 |
+
s.tomselect=this,i=(window.getComputedStyle&&window.getComputedStyle(s,null)).getPropertyValue("direction")
|
129 |
+
const n=U(s,t)
|
130 |
+
this.settings=n,this.input=s,this.tabIndex=s.tabIndex||0,this.is_select_tag="select"===s.tagName.toLowerCase(),this.rtl=/rtl/i.test(i),this.inputId=M(s,"tomselect-"+W),this.isRequired=s.required,this.sifter=new b(this.options,{diacritics:n.diacritics}),n.mode=n.mode||(1===n.maxItems?"single":"multi"),"boolean"!=typeof n.hideSelected&&(n.hideSelected="multi"===n.mode),"boolean"!=typeof n.hidePlaceholder&&(n.hidePlaceholder="multi"!==n.mode)
|
131 |
+
var o=n.createFilter
|
132 |
+
"function"!=typeof o&&("string"==typeof o&&(o=new RegExp(o)),o instanceof RegExp?n.createFilter=e=>o.test(e):n.createFilter=()=>!0),this.initializePlugins(n.plugins),this.setupCallbacks(),this.setupTemplates()
|
133 |
+
const r=w("<div>"),l=w("<div>"),a=this._render("dropdown"),c=w('<div role="listbox" tabindex="-1">'),d=this.input.getAttribute("class")||"",p=n.mode
|
134 |
+
var u
|
135 |
+
if(C(r,n.wrapperClass,d,p),C(l,n.controlClass),G(r,l),C(a,n.dropdownClass,p),n.copyClassesToDropdown&&C(a,d),C(c,n.dropdownContentClass),G(a,c),w(n.dropdownParent||r).appendChild(a),n.hasOwnProperty("controlInput"))n.controlInput?(u=w(n.controlInput),this.focus_node=u):(u=w("<input/>"),this.focus_node=l)
|
136 |
+
else{u=w('<input type="text" autocomplete="off" size="1" />')
|
137 |
+
y(["autocorrect","autocapitalize","autocomplete"],(e=>{s.getAttribute(e)&&P(u,{[e]:s.getAttribute(e)})})),u.tabIndex=-1,l.appendChild(u),this.focus_node=u}this.wrapper=r,this.dropdown=a,this.dropdown_content=c,this.control=l,this.control_input=u,this.setup()}setup(){const e=this,t=e.settings,i=e.control_input,s=e.dropdown,n=e.dropdown_content,o=e.wrapper,r=e.control,l=e.input,a=e.focus_node,c={passive:!0},d=e.inputId+"-ts-dropdown"
|
138 |
+
P(n,{id:d}),P(a,{role:"combobox","aria-haspopup":"listbox","aria-expanded":"false","aria-controls":d})
|
139 |
+
const p=M(a,e.inputId+"-ts-control"),u="label[for='"+(e=>e.replace(/['"\\]/g,"\\$&"))(e.inputId)+"']",h=document.querySelector(u),g=e.focus.bind(e)
|
140 |
+
if(h){B(h,"click",g),P(h,{for:p})
|
141 |
+
const t=M(h,e.inputId+"-ts-label")
|
142 |
+
P(a,{"aria-labelledby":t}),P(n,{"aria-labelledby":t})}if(o.style.width=l.style.width,e.plugins.names.length){const t="plugin-"+e.plugins.names.join(" plugin-")
|
143 |
+
C([o,s],t)}(null===t.maxItems||t.maxItems>1)&&e.is_select_tag&&P(l,{multiple:"multiple"}),e.settings.placeholder&&P(i,{placeholder:t.placeholder}),!e.settings.splitOn&&e.settings.delimiter&&(e.settings.splitOn=new RegExp("\\s*"+v(e.settings.delimiter)+"+\\s*")),t.load&&t.loadThrottle&&(t.load=z(t.load,t.loadThrottle)),e.control_input.type=l.type,B(s,"click",(t=>{const i=k(t.target,"[data-selectable]")
|
144 |
+
i&&(e.onOptionSelect(t,i),H(t,!0))})),B(r,"click",(t=>{var s=k(t.target,"[data-ts-item]",r)
|
145 |
+
s&&e.onItemSelect(t,s)?H(t,!0):""==i.value&&(e.onClick(),H(t,!0))})),B(i,"mousedown",(e=>{""!==i.value&&e.stopPropagation()})),B(a,"keydown",(t=>e.onKeyDown(t))),B(i,"keypress",(t=>e.onKeyPress(t))),B(i,"input",(t=>e.onInput(t))),B(a,"resize",(()=>e.positionDropdown()),c),B(a,"blur",(t=>e.onBlur(t))),B(a,"focus",(t=>e.onFocus(t))),B(a,"paste",(t=>e.onPaste(t)))
|
146 |
+
const f=t=>{const i=t.composedPath()[0]
|
147 |
+
if(!o.contains(i)&&!s.contains(i))return e.isFocused&&e.blur(),void e.inputState()
|
148 |
+
H(t,!0)}
|
149 |
+
var m=()=>{e.isOpen&&e.positionDropdown()}
|
150 |
+
B(document,"mousedown",f),B(window,"scroll",m,c),B(window,"resize",m,c),this._destroy=()=>{document.removeEventListener("mousedown",f),window.removeEventListener("sroll",m),window.removeEventListener("resize",m),h&&h.removeEventListener("click",g)},this.revertSettings={innerHTML:l.innerHTML,tabIndex:l.tabIndex},l.tabIndex=-1,l.insertAdjacentElement("afterend",e.wrapper),e.sync(!1),t.items=[],delete t.optgroups,delete t.options,B(l,"invalid",(t=>{e.isValid&&(e.isValid=!1,e.isInvalid=!0,e.refreshState())})),e.updateOriginalInput(),e.refreshItems(),e.close(!1),e.inputState(),e.isSetup=!0,l.disabled?e.disable():e.enable(),e.on("change",this.onChange),C(l,"tomselected","ts-hidden-accessible"),e.trigger("initialize"),!0===t.preload&&e.preload()}setupOptions(e=[],t=[]){this.addOptions(e),y(t,(e=>{this.registerOptionGroup(e)}))}setupTemplates(){var e=this,t=e.settings.labelField,i=e.settings.optgroupLabelField,s={optgroup:e=>{let t=document.createElement("div")
|
151 |
+
return t.className="optgroup",t.appendChild(e.options),t},optgroup_header:(e,t)=>'<div class="optgroup-header">'+t(e[i])+"</div>",option:(e,i)=>"<div>"+i(e[t])+"</div>",item:(e,i)=>"<div>"+i(e[t])+"</div>",option_create:(e,t)=>'<div class="create">Add <strong>'+t(e.input)+"</strong>…</div>",no_results:()=>'<div class="no-results">No results found</div>',loading:()=>'<div class="spinner"></div>',not_loading:()=>{},dropdown:()=>"<div></div>"}
|
152 |
+
e.settings.render=Object.assign({},s,e.settings.render)}setupCallbacks(){var e,t,i={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",item_select:"onItemSelect",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur"}
|
153 |
+
for(e in i)(t=this.settings[i[e]])&&this.on(e,t)}sync(e=!0){const t=this,i=e?U(t.input,{delimiter:t.settings.delimiter}):t.settings
|
154 |
+
t.setupOptions(i.options,i.optgroups),t.setValue(i.items,!0),t.lastQuery=null}onClick(){var e=this
|
155 |
+
if(e.activeItems.length>0)return e.clearActiveItems(),void e.focus()
|
156 |
+
e.isFocused&&e.isOpen?e.blur():e.focus()}onMouseDown(){}onChange(){_(this.input,"input"),_(this.input,"change")}onPaste(e){var t=this
|
157 |
+
t.isFull()||t.isInputHidden||t.isLocked?H(e):t.settings.splitOn&&setTimeout((()=>{var e=t.inputValue()
|
158 |
+
if(e.match(t.settings.splitOn)){var i=e.trim().split(t.settings.splitOn)
|
159 |
+
y(i,(e=>{t.createItem(e)}))}}),0)}onKeyPress(e){var t=this
|
160 |
+
if(!t.isLocked){var i=String.fromCharCode(e.keyCode||e.which)
|
161 |
+
return t.settings.create&&"multi"===t.settings.mode&&i===t.settings.delimiter?(t.createItem(),void H(e)):void 0}H(e)}onKeyDown(e){var t=this
|
162 |
+
if(t.isLocked)9!==e.keyCode&&H(e)
|
163 |
+
else{switch(e.keyCode){case 65:if(K(V,e))return H(e),void t.selectAll()
|
164 |
+
break
|
165 |
+
case 27:return t.isOpen&&(H(e,!0),t.close()),void t.clearActiveItems()
|
166 |
+
case 40:if(!t.isOpen&&t.hasOptions)t.open()
|
167 |
+
else if(t.activeOption){let e=t.getAdjacent(t.activeOption,1)
|
168 |
+
e&&t.setActiveOption(e)}return void H(e)
|
169 |
+
case 38:if(t.activeOption){let e=t.getAdjacent(t.activeOption,-1)
|
170 |
+
e&&t.setActiveOption(e)}return void H(e)
|
171 |
+
case 13:return void(t.isOpen&&t.activeOption?(t.onOptionSelect(e,t.activeOption),H(e)):t.settings.create&&t.createItem()&&H(e))
|
172 |
+
case 37:return void t.advanceSelection(-1,e)
|
173 |
+
case 39:return void t.advanceSelection(1,e)
|
174 |
+
case 9:return void(t.settings.selectOnTab&&(t.isOpen&&t.activeOption&&(t.onOptionSelect(e,t.activeOption),H(e)),t.settings.create&&t.createItem()&&H(e)))
|
175 |
+
case 8:case 46:return void t.deleteSelection(e)}t.isInputHidden&&!K(V,e)&&H(e)}}onInput(e){var t=this
|
176 |
+
if(!t.isLocked){var i=t.inputValue()
|
177 |
+
t.lastValue!==i&&(t.lastValue=i,t.settings.shouldLoad.call(t,i)&&t.load(i),t.refreshOptions(),t.trigger("type",i))}}onFocus(e){var t=this,i=t.isFocused
|
178 |
+
if(t.isDisabled)return t.blur(),void H(e)
|
179 |
+
t.ignoreFocus||(t.isFocused=!0,"focus"===t.settings.preload&&t.preload(),i||t.trigger("focus"),t.activeItems.length||(t.showInput(),t.refreshOptions(!!t.settings.openOnFocus)),t.refreshState())}onBlur(e){if(!1!==document.hasFocus()){var t=this
|
180 |
+
if(t.isFocused){t.isFocused=!1,t.ignoreFocus=!1
|
181 |
+
var i=()=>{t.close(),t.setActiveItem(),t.setCaret(t.items.length),t.trigger("blur")}
|
182 |
+
t.settings.create&&t.settings.createOnBlur?t.createItem(null,!1,i):i()}}}onOptionSelect(e,t){var i,s=this
|
183 |
+
t&&(t.parentElement&&t.parentElement.matches("[data-disabled]")||(t.classList.contains("create")?s.createItem(null,!0,(()=>{s.settings.closeAfterSelect&&s.close()})):void 0!==(i=t.dataset.value)&&(s.lastQuery=null,s.addItem(i),s.settings.closeAfterSelect&&s.close(),!s.settings.hideSelected&&e.type&&/click/.test(e.type)&&s.setActiveOption(t))))}onItemSelect(e,t){var i=this
|
184 |
+
return!i.isLocked&&"multi"===i.settings.mode&&(H(e),i.setActiveItem(t,e),!0)}canLoad(e){return!!this.settings.load&&!this.loadedSearches.hasOwnProperty(e)}load(e){const t=this
|
185 |
+
if(!t.canLoad(e))return
|
186 |
+
C(t.wrapper,t.settings.loadingClass),t.loading++
|
187 |
+
const i=t.loadCallback.bind(t)
|
188 |
+
t.settings.load.call(t,e,i)}loadCallback(e,t){const i=this
|
189 |
+
i.loading=Math.max(i.loading-1,0),i.lastQuery=null,i.clearActiveOption(),i.setupOptions(e,t),i.refreshOptions(i.isFocused&&!i.isInputHidden),i.loading||S(i.wrapper,i.settings.loadingClass),i.trigger("load",e,t)}preload(){var e=this.wrapper.classList
|
190 |
+
e.contains("preloaded")||(e.add("preloaded"),this.load(""))}setTextboxValue(e=""){var t=this.control_input
|
191 |
+
t.value!==e&&(t.value=e,_(t,"update"),this.lastValue=e)}getValue(){return this.is_select_tag&&this.input.hasAttribute("multiple")?this.items:this.items.join(this.settings.delimiter)}setValue(e,t){R(this,t?[]:["change"],(()=>{this.clear(t),this.addItems(e,t)}))}setMaxItems(e){0===e&&(e=null),this.settings.maxItems=e,this.refreshState()}setActiveItem(e,t){var i,s,n,o,r,l,a=this
|
192 |
+
if("single"!==a.settings.mode){if(!e)return a.clearActiveItems(),void(a.isFocused&&a.showInput())
|
193 |
+
if("click"===(i=t&&t.type.toLowerCase())&&K("shiftKey",t)&&a.activeItems.length){for(l=a.getLastActive(),(n=Array.prototype.indexOf.call(a.control.children,l))>(o=Array.prototype.indexOf.call(a.control.children,e))&&(r=n,n=o,o=r),s=n;s<=o;s++)e=a.control.children[s],-1===a.activeItems.indexOf(e)&&a.setActiveItemClass(e)
|
194 |
+
H(t)}else"click"===i&&K(V,t)||"keydown"===i&&K("shiftKey",t)?e.classList.contains("active")?a.removeActiveItem(e):a.setActiveItemClass(e):(a.clearActiveItems(),a.setActiveItemClass(e))
|
195 |
+
a.hideInput(),a.isFocused||a.focus()}}setActiveItemClass(e){const t=this,i=t.control.querySelector(".last-active")
|
196 |
+
i&&S(i,"last-active"),C(e,"active last-active"),t.trigger("item_select",e),-1==t.activeItems.indexOf(e)&&t.activeItems.push(e)}removeActiveItem(e){var t=this.activeItems.indexOf(e)
|
197 |
+
this.activeItems.splice(t,1),S(e,"active")}clearActiveItems(){S(this.activeItems,"active"),this.activeItems=[]}setActiveOption(e){e!==this.activeOption&&(this.clearActiveOption(),e&&(this.activeOption=e,P(this.focus_node,{"aria-activedescendant":e.getAttribute("id")}),P(e,{"aria-selected":"true"}),C(e,"active"),this.scrollToOption(e)))}scrollToOption(e,t){if(!e)return
|
198 |
+
const i=this.dropdown_content,s=i.clientHeight,n=i.scrollTop||0,o=e.offsetHeight,r=e.getBoundingClientRect().top-i.getBoundingClientRect().top+n
|
199 |
+
r+o>s+n?this.scroll(r-s+o,t):r<n&&this.scroll(r,t)}scroll(e,t){const i=this.dropdown_content
|
200 |
+
t&&(i.style.scrollBehavior=t),i.scrollTop=e,i.style.scrollBehavior=""}clearActiveOption(){this.activeOption&&(S(this.activeOption,"active"),P(this.activeOption,{"aria-selected":null})),this.activeOption=null,P(this.focus_node,{"aria-activedescendant":null})}selectAll(){if("single"===this.settings.mode)return
|
201 |
+
const e=this.controlChildren()
|
202 |
+
e.length&&(this.hideInput(),this.close(),this.activeItems=e,C(e,"active"))}inputState(){var e=this
|
203 |
+
e.control.contains(e.control_input)&&(P(e.control_input,{placeholder:e.settings.placeholder}),e.activeItems.length>0||!e.isFocused&&e.settings.hidePlaceholder&&e.items.length>0?(e.setTextboxValue(),e.isInputHidden=!0):(e.settings.hidePlaceholder&&e.items.length>0&&P(e.control_input,{placeholder:""}),e.isInputHidden=!1),e.wrapper.classList.toggle("input-hidden",e.isInputHidden))}hideInput(){this.inputState()}showInput(){this.inputState()}inputValue(){return this.control_input.value.trim()}focus(){var e=this
|
204 |
+
e.isDisabled||(e.ignoreFocus=!0,e.control_input.offsetWidth?e.control_input.focus():e.focus_node.focus(),setTimeout((()=>{e.ignoreFocus=!1,e.onFocus()}),0))}blur(){this.focus_node.blur(),this.onBlur()}getScoreFunction(e){return this.sifter.getScoreFunction(e,this.getSearchOptions())}getSearchOptions(){var e=this.settings,t=e.sortField
|
205 |
+
return"string"==typeof e.sortField&&(t=[{field:e.sortField}]),{fields:e.searchField,conjunction:e.searchConjunction,sort:t,nesting:e.nesting}}search(e){var t,i,s,n=this,o=this.getSearchOptions()
|
206 |
+
if(n.settings.score&&"function"!=typeof(s=n.settings.score.call(n,e)))throw new Error('Tom Select "score" setting must be a function that returns a function')
|
207 |
+
if(e!==n.lastQuery?(n.lastQuery=e,i=n.sifter.search(e,Object.assign(o,{score:s})),n.currentResults=i):i=Object.assign({},n.currentResults),n.settings.hideSelected)for(t=i.items.length-1;t>=0;t--){let e=q(i.items[t].id)
|
208 |
+
e&&-1!==n.items.indexOf(e)&&i.items.splice(t,1)}return i}refreshOptions(e=!0){var t,i,s,n,o,r,l,a,c,d,p
|
209 |
+
const u={},h=[]
|
210 |
+
var g,f=this,v=f.inputValue(),m=f.search(v),O=f.activeOption,b=f.settings.shouldOpen||!1,w=f.dropdown_content
|
211 |
+
for(O&&(c=O.dataset.value,d=O.closest("[data-group]")),n=m.items.length,"number"==typeof f.settings.maxOptions&&(n=Math.min(n,f.settings.maxOptions)),n>0&&(b=!0),t=0;t<n;t++){let e=m.items[t].id,n=f.options[e],l=f.getOption(e,!0)
|
212 |
+
for(f.settings.hideSelected||l.classList.toggle("selected",f.items.includes(e)),o=n[f.settings.optgroupField]||"",i=0,s=(r=Array.isArray(o)?o:[o])&&r.length;i<s;i++)o=r[i],f.optgroups.hasOwnProperty(o)||(o=""),u.hasOwnProperty(o)||(u[o]=document.createDocumentFragment(),h.push(o)),i>0&&(l=l.cloneNode(!0),P(l,{id:n.$id+"-clone-"+i,"aria-selected":null}),l.classList.add("ts-cloned"),S(l,"active")),c==e&&d&&d.dataset.group===o&&(O=l),u[o].appendChild(l)}this.settings.lockOptgroupOrder&&h.sort(((e,t)=>(f.optgroups[e]&&f.optgroups[e].$order||0)-(f.optgroups[t]&&f.optgroups[t].$order||0))),l=document.createDocumentFragment(),y(h,(e=>{if(f.optgroups.hasOwnProperty(e)&&u[e].children.length){let t=document.createDocumentFragment(),i=f.render("optgroup_header",f.optgroups[e])
|
213 |
+
G(t,i),G(t,u[e])
|
214 |
+
let s=f.render("optgroup",{group:f.optgroups[e],options:t})
|
215 |
+
G(l,s)}else G(l,u[e])})),w.innerHTML="",G(w,l),f.settings.highlight&&(g=w.querySelectorAll("span.highlight"),Array.prototype.forEach.call(g,(function(e){var t=e.parentNode
|
216 |
+
t.replaceChild(e.firstChild,e),t.normalize()})),m.query.length&&m.tokens.length&&y(m.tokens,(e=>{T(w,e.regex)})))
|
217 |
+
var _=e=>{let t=f.render(e,{input:v})
|
218 |
+
return t&&(b=!0,w.insertBefore(t,w.firstChild)),t}
|
219 |
+
if(f.loading?_("loading"):f.settings.shouldLoad.call(f,v)?0===m.items.length&&_("no_results"):_("not_loading"),(a=f.canCreate(v))&&(p=_("option_create")),f.hasOptions=m.items.length>0||a,b){if(m.items.length>0){if(!w.contains(O)&&"single"===f.settings.mode&&f.items.length&&(O=f.getOption(f.items[0])),!w.contains(O)){let e=0
|
220 |
+
p&&!f.settings.addPrecedence&&(e=1),O=f.selectable()[e]}}else p&&(O=p)
|
221 |
+
e&&!f.isOpen&&(f.open(),f.scrollToOption(O,"auto")),f.setActiveOption(O)}else f.clearActiveOption(),e&&f.isOpen&&f.close(!1)}selectable(){return this.dropdown_content.querySelectorAll("[data-selectable]")}addOption(e,t=!1){const i=this
|
222 |
+
if(Array.isArray(e))return i.addOptions(e,t),!1
|
223 |
+
const s=q(e[i.settings.valueField])
|
224 |
+
return null!==s&&!i.options.hasOwnProperty(s)&&(e.$order=e.$order||++i.order,e.$id=i.inputId+"-opt-"+e.$order,i.options[s]=e,i.lastQuery=null,t&&(i.userOptions[s]=t,i.trigger("option_add",s,e)),s)}addOptions(e,t=!1){y(e,(e=>{this.addOption(e,t)}))}registerOption(e){return this.addOption(e)}registerOptionGroup(e){var t=q(e[this.settings.optgroupValueField])
|
225 |
+
return null!==t&&(e.$order=e.$order||++this.order,this.optgroups[t]=e,t)}addOptionGroup(e,t){var i
|
226 |
+
t[this.settings.optgroupValueField]=e,(i=this.registerOptionGroup(t))&&this.trigger("optgroup_add",i,t)}removeOptionGroup(e){this.optgroups.hasOwnProperty(e)&&(delete this.optgroups[e],this.clearCache(),this.trigger("optgroup_remove",e))}clearOptionGroups(){this.optgroups={},this.clearCache(),this.trigger("optgroup_clear")}updateOption(e,t){const i=this
|
227 |
+
var s,n
|
228 |
+
const o=q(e),r=q(t[i.settings.valueField])
|
229 |
+
if(null===o)return
|
230 |
+
if(!i.options.hasOwnProperty(o))return
|
231 |
+
if("string"!=typeof r)throw new Error("Value must be set in option data")
|
232 |
+
const l=i.getOption(o),a=i.getItem(o)
|
233 |
+
if(t.$order=t.$order||i.options[o].$order,delete i.options[o],i.uncacheValue(r),i.options[r]=t,l){if(i.dropdown_content.contains(l)){const e=i._render("option",t)
|
234 |
+
E(l,e),i.activeOption===l&&i.setActiveOption(e)}l.remove()}a&&(-1!==(n=i.items.indexOf(o))&&i.items.splice(n,1,r),s=i._render("item",t),a.classList.contains("active")&&C(s,"active"),E(a,s)),i.lastQuery=null}removeOption(e,t){const i=this
|
235 |
+
e=D(e),i.uncacheValue(e),delete i.userOptions[e],delete i.options[e],i.lastQuery=null,i.trigger("option_remove",e),i.removeItem(e,t)}clearOptions(){this.loadedSearches={},this.userOptions={},this.clearCache()
|
236 |
+
var e={}
|
237 |
+
y(this.options,((t,i)=>{this.items.indexOf(i)>=0&&(e[i]=this.options[i])})),this.options=this.sifter.items=e,this.lastQuery=null,this.trigger("option_clear")}getOption(e,t=!1){const i=q(e)
|
238 |
+
if(null!==i&&this.options.hasOwnProperty(i)){const e=this.options[i]
|
239 |
+
if(e.$div)return e.$div
|
240 |
+
if(t)return this._render("option",e)}return null}getAdjacent(e,t,i="option"){var s
|
241 |
+
if(!e)return null
|
242 |
+
s="item"==i?this.controlChildren():this.dropdown_content.querySelectorAll("[data-selectable]")
|
243 |
+
for(let i=0;i<s.length;i++)if(s[i]==e)return t>0?s[i+1]:s[i-1]
|
244 |
+
return null}getItem(e){if("object"==typeof e)return e
|
245 |
+
var t=q(e)
|
246 |
+
return null!==t?this.control.querySelector(`[data-value="${Q(t)}"]`):null}addItems(e,t){var i=this,s=Array.isArray(e)?e:[e]
|
247 |
+
for(let e=0,n=(s=s.filter((e=>-1===i.items.indexOf(e)))).length;e<n;e++)i.isPending=e<n-1,i.addItem(s[e],t)}addItem(e,t){R(this,t?[]:["change"],(()=>{var i,s
|
248 |
+
const n=this,o=n.settings.mode,r=q(e)
|
249 |
+
if((!r||-1===n.items.indexOf(r)||("single"===o&&n.close(),"single"!==o&&n.settings.duplicates))&&null!==r&&n.options.hasOwnProperty(r)&&("single"===o&&n.clear(t),"multi"!==o||!n.isFull())){if(i=n._render("item",n.options[r]),n.control.contains(i)&&(i=i.cloneNode(!0)),s=n.isFull(),n.items.splice(n.caretPos,0,r),n.insertAtCaret(i),n.isSetup){if(!n.isPending&&n.settings.hideSelected){let e=n.getOption(r),t=n.getAdjacent(e,1)
|
250 |
+
t&&n.setActiveOption(t)}n.isPending||n.refreshOptions(n.isFocused&&"single"!==o),0!=n.settings.closeAfterSelect&&n.isFull()?n.close():n.isPending||n.positionDropdown(),n.trigger("item_add",r,i),n.isPending||n.updateOriginalInput({silent:t})}(!n.isPending||!s&&n.isFull())&&(n.inputState(),n.refreshState())}}))}removeItem(e=null,t){const i=this
|
251 |
+
if(!(e=i.getItem(e)))return
|
252 |
+
var s,n
|
253 |
+
const o=e.dataset.value
|
254 |
+
s=L(e),e.remove(),e.classList.contains("active")&&(n=i.activeItems.indexOf(e),i.activeItems.splice(n,1),S(e,"active")),i.items.splice(s,1),i.lastQuery=null,!i.settings.persist&&i.userOptions.hasOwnProperty(o)&&i.removeOption(o,t),s<i.caretPos&&i.setCaret(i.caretPos-1),i.updateOriginalInput({silent:t}),i.refreshState(),i.positionDropdown(),i.trigger("item_remove",o,e)}createItem(e=null,t=!0,i=(()=>{})){var s,n=this,o=n.caretPos
|
255 |
+
if(e=e||n.inputValue(),!n.canCreate(e))return i(),!1
|
256 |
+
n.lock()
|
257 |
+
var r=!1,l=e=>{if(n.unlock(),!e||"object"!=typeof e)return i()
|
258 |
+
var s=q(e[n.settings.valueField])
|
259 |
+
if("string"!=typeof s)return i()
|
260 |
+
n.setTextboxValue(),n.addOption(e,!0),n.setCaret(o),n.addItem(s),n.refreshOptions(t&&"single"!==n.settings.mode),i(e),r=!0}
|
261 |
+
return s="function"==typeof n.settings.create?n.settings.create.call(this,e,l):{[n.settings.labelField]:e,[n.settings.valueField]:e},r||l(s),!0}refreshItems(){var e=this
|
262 |
+
e.lastQuery=null,e.isSetup&&e.addItems(e.items),e.updateOriginalInput(),e.refreshState()}refreshState(){const e=this
|
263 |
+
e.refreshValidityState()
|
264 |
+
const t=e.isFull(),i=e.isLocked
|
265 |
+
e.wrapper.classList.toggle("rtl",e.rtl)
|
266 |
+
const s=e.wrapper.classList
|
267 |
+
var n
|
268 |
+
s.toggle("focus",e.isFocused),s.toggle("disabled",e.isDisabled),s.toggle("required",e.isRequired),s.toggle("invalid",!e.isValid),s.toggle("locked",i),s.toggle("full",t),s.toggle("input-active",e.isFocused&&!e.isInputHidden),s.toggle("dropdown-active",e.isOpen),s.toggle("has-options",(n=e.options,0===Object.keys(n).length)),s.toggle("has-items",e.items.length>0)}refreshValidityState(){var e=this
|
269 |
+
e.input.checkValidity&&(e.isValid=e.input.checkValidity(),e.isInvalid=!e.isValid)}isFull(){return null!==this.settings.maxItems&&this.items.length>=this.settings.maxItems}updateOriginalInput(e={}){const t=this
|
270 |
+
var i,s
|
271 |
+
const n=t.input.querySelector('option[value=""]')
|
272 |
+
if(t.is_select_tag){const e=[]
|
273 |
+
function o(i,s,o){return i||(i=w('<option value="'+N(s)+'">'+N(o)+"</option>")),i!=n&&t.input.append(i),e.push(i),i.selected=!0,i}t.input.querySelectorAll("option:checked").forEach((e=>{e.selected=!1})),0==t.items.length&&"single"==t.settings.mode?o(n,"",""):t.items.forEach((n=>{if(i=t.options[n],s=i[t.settings.labelField]||"",e.includes(i.$option)){o(t.input.querySelector(`option[value="${Q(n)}"]:not(:checked)`),n,s)}else i.$option=o(i.$option,n,s)}))}else t.input.value=t.getValue()
|
274 |
+
t.isSetup&&(e.silent||t.trigger("change",t.getValue()))}open(){var e=this
|
275 |
+
e.isLocked||e.isOpen||"multi"===e.settings.mode&&e.isFull()||(e.isOpen=!0,P(e.focus_node,{"aria-expanded":"true"}),e.refreshState(),I(e.dropdown,{visibility:"hidden",display:"block"}),e.positionDropdown(),I(e.dropdown,{visibility:"visible",display:"block"}),e.focus(),e.trigger("dropdown_open",e.dropdown))}close(e=!0){var t=this,i=t.isOpen
|
276 |
+
e&&(t.setTextboxValue(),"single"===t.settings.mode&&t.items.length&&t.hideInput()),t.isOpen=!1,P(t.focus_node,{"aria-expanded":"false"}),I(t.dropdown,{display:"none"}),t.settings.hideSelected&&t.clearActiveOption(),t.refreshState(),i&&t.trigger("dropdown_close",t.dropdown)}positionDropdown(){if("body"===this.settings.dropdownParent){var e=this.control,t=e.getBoundingClientRect(),i=e.offsetHeight+t.top+window.scrollY,s=t.left+window.scrollX
|
277 |
+
I(this.dropdown,{width:t.width+"px",top:i+"px",left:s+"px"})}}clear(e){var t=this
|
278 |
+
if(t.items.length){var i=t.controlChildren()
|
279 |
+
y(i,(e=>{t.removeItem(e,!0)})),t.showInput(),e||t.updateOriginalInput(),t.trigger("clear")}}insertAtCaret(e){const t=this,i=t.caretPos,s=t.control
|
280 |
+
s.insertBefore(e,s.children[i]),t.setCaret(i+1)}deleteSelection(e){var t,i,s,n,o,r=this
|
281 |
+
t=e&&8===e.keyCode?-1:1,i={start:(o=r.control_input).selectionStart||0,length:(o.selectionEnd||0)-(o.selectionStart||0)}
|
282 |
+
const l=[]
|
283 |
+
if(r.activeItems.length)n=F(r.activeItems,t),s=L(n),t>0&&s++,y(r.activeItems,(e=>l.push(e)))
|
284 |
+
else if((r.isFocused||"single"===r.settings.mode)&&r.items.length){const e=r.controlChildren()
|
285 |
+
t<0&&0===i.start&&0===i.length?l.push(e[r.caretPos-1]):t>0&&i.start===r.inputValue().length&&l.push(e[r.caretPos])}const a=l.map((e=>e.dataset.value))
|
286 |
+
if(!a.length||"function"==typeof r.settings.onDelete&&!1===r.settings.onDelete.call(r,a,e))return!1
|
287 |
+
for(H(e,!0),void 0!==s&&r.setCaret(s);l.length;)r.removeItem(l.pop())
|
288 |
+
return r.showInput(),r.positionDropdown(),r.refreshOptions(!1),!0}advanceSelection(e,t){var i,s,n=this
|
289 |
+
n.rtl&&(e*=-1),n.inputValue().length||(K(V,t)||K("shiftKey",t)?(s=(i=n.getLastActive(e))?i.classList.contains("active")?n.getAdjacent(i,e,"item"):i:e>0?n.control_input.nextElementSibling:n.control_input.previousElementSibling)&&(s.classList.contains("active")&&n.removeActiveItem(i),n.setActiveItemClass(s)):n.moveCaret(e))}moveCaret(e){}getLastActive(e){let t=this.control.querySelector(".last-active")
|
290 |
+
if(t)return t
|
291 |
+
var i=this.control.querySelectorAll(".active")
|
292 |
+
return i?F(i,e):void 0}setCaret(e){this.caretPos=this.items.length}controlChildren(){return Array.from(this.control.querySelectorAll("[data-ts-item]"))}lock(){this.close(),this.isLocked=!0,this.refreshState()}unlock(){this.isLocked=!1,this.refreshState()}disable(){var e=this
|
293 |
+
e.input.disabled=!0,e.control_input.disabled=!0,e.focus_node.tabIndex=-1,e.isDisabled=!0,e.lock()}enable(){var e=this
|
294 |
+
e.input.disabled=!1,e.control_input.disabled=!1,e.focus_node.tabIndex=e.tabIndex,e.isDisabled=!1,e.unlock()}destroy(){var e=this,t=e.revertSettings
|
295 |
+
e.trigger("destroy"),e.off(),e.wrapper.remove(),e.dropdown.remove(),e.input.innerHTML=t.innerHTML,e.input.tabIndex=t.tabIndex,S(e.input,"tomselected","ts-hidden-accessible"),e._destroy(),delete e.input.tomselect}render(e,t){return"function"!=typeof this.settings.render[e]?null:this._render(e,t)}_render(e,t){var i,s,n=""
|
296 |
+
const o=this
|
297 |
+
return"option"!==e&&"item"!=e||(n=D(t[o.settings.valueField])),null==(s=o.settings.render[e].call(this,t,N))||(s=w(s),"option"===e||"option_create"===e?t[o.settings.disabledField]?P(s,{"aria-disabled":"true"}):P(s,{"data-selectable":""}):"optgroup"===e&&(i=t.group[o.settings.optgroupValueField],P(s,{"data-group":i}),t.group[o.settings.disabledField]&&P(s,{"data-disabled":""})),"option"!==e&&"item"!==e||(P(s,{"data-value":n}),"item"===e?(C(s,o.settings.itemClass),P(s,{"data-ts-item":""})):(C(s,o.settings.optionClass),P(s,{role:"option",id:t.$id}),o.options[n].$div=s))),s}clearCache(){y(this.options,((e,t)=>{e.$div&&(e.$div.remove(),delete e.$div)}))}uncacheValue(e){const t=this.getOption(e)
|
298 |
+
t&&t.remove()}canCreate(e){return this.settings.create&&e.length>0&&this.settings.createFilter.call(this,e)}hook(e,t,i){var s=this,n=s[t]
|
299 |
+
s[t]=function(){var t,o
|
300 |
+
return"after"===e&&(t=n.apply(s,arguments)),o=i.apply(s,arguments),"instead"===e?o:("before"===e&&(t=n.apply(s,arguments)),t)}}}return J.define("change_listener",(function(){B(this.input,"change",(()=>{this.sync()}))})),J.define("checkbox_options",(function(){var e=this,t=e.onOptionSelect
|
301 |
+
e.settings.hideSelected=!1
|
302 |
+
var i=function(e){setTimeout((()=>{var t=e.querySelector("input")
|
303 |
+
e.classList.contains("selected")?t.checked=!0:t.checked=!1}),1)}
|
304 |
+
e.hook("after","setupTemplates",(()=>{var t=e.settings.render.option
|
305 |
+
e.settings.render.option=(i,s)=>{var n=w(t.call(e,i,s)),o=document.createElement("input")
|
306 |
+
o.addEventListener("click",(function(e){H(e)})),o.type="checkbox"
|
307 |
+
const r=q(i[e.settings.valueField])
|
308 |
+
return r&&e.items.indexOf(r)>-1&&(o.checked=!0),n.prepend(o),n}})),e.on("item_remove",(t=>{var s=e.getOption(t)
|
309 |
+
s&&(s.classList.remove("selected"),i(s))})),e.hook("instead","onOptionSelect",((s,n)=>{if(n.classList.contains("selected"))return n.classList.remove("selected"),e.removeItem(n.dataset.value),e.refreshOptions(),void H(s,!0)
|
310 |
+
t.call(e,s,n),i(n)}))})),J.define("clear_button",(function(e){const t=this,i=Object.assign({className:"clear-button",title:"Clear All",html:e=>`<div class="${e.className}" title="${e.title}">×</div>`},e)
|
311 |
+
t.on("initialize",(()=>{var e=w(i.html(i))
|
312 |
+
e.addEventListener("click",(e=>{t.clear(),"single"===t.settings.mode&&t.settings.allowEmptyOption&&t.addItem(""),e.preventDefault(),e.stopPropagation()})),t.control.appendChild(e)}))})),J.define("drag_drop",(function(){var e=this
|
313 |
+
if(!$.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".')
|
314 |
+
if("multi"===e.settings.mode){var t=e.lock,i=e.unlock
|
315 |
+
e.hook("instead","lock",(()=>{var i=$(e.control).data("sortable")
|
316 |
+
return i&&i.disable(),t.call(e)})),e.hook("instead","unlock",(()=>{var t=$(e.control).data("sortable")
|
317 |
+
return t&&t.enable(),i.call(e)})),e.on("initialize",(()=>{var t=$(e.control).sortable({items:"[data-value]",forcePlaceholderSize:!0,disabled:e.isLocked,start:(e,i)=>{i.placeholder.css("width",i.helper.css("width")),t.css({overflow:"visible"})},stop:()=>{t.css({overflow:"hidden"})
|
318 |
+
var i=[]
|
319 |
+
t.children("[data-value]").each((function(){this.dataset.value&&i.push(this.dataset.value)})),e.setValue(i)}})}))}})),J.define("dropdown_header",(function(e){const t=this,i=Object.assign({title:"Untitled",headerClass:"dropdown-header",titleRowClass:"dropdown-header-title",labelClass:"dropdown-header-label",closeClass:"dropdown-header-close",html:e=>'<div class="'+e.headerClass+'"><div class="'+e.titleRowClass+'"><span class="'+e.labelClass+'">'+e.title+'</span><a class="'+e.closeClass+'">×</a></div></div>'},e)
|
320 |
+
t.on("initialize",(()=>{var e=w(i.html(i)),s=e.querySelector("."+i.closeClass)
|
321 |
+
s&&s.addEventListener("click",(e=>{H(e,!0),t.close()})),t.dropdown.insertBefore(e,t.dropdown.firstChild)}))})),J.define("caret_position",(function(){var e=this
|
322 |
+
e.hook("instead","setCaret",(t=>{"single"!==e.settings.mode&&e.control.contains(e.control_input)?(t=Math.max(0,Math.min(e.items.length,t)))==e.caretPos||e.isPending||e.controlChildren().forEach(((i,s)=>{s<t?e.control_input.insertAdjacentElement("beforebegin",i):e.control.appendChild(i)})):t=e.items.length,e.caretPos=t})),e.hook("instead","moveCaret",(t=>{if(!e.isFocused)return
|
323 |
+
const i=e.getLastActive(t)
|
324 |
+
if(i){const s=L(i)
|
325 |
+
e.setCaret(t>0?s+1:s),e.setActiveItem()}else e.setCaret(e.caretPos+t)}))})),J.define("dropdown_input",(function(){var e=this
|
326 |
+
e.settings.shouldOpen=!0,e.hook("before","setup",(()=>{e.focus_node=e.control,C(e.control_input,"dropdown-input")
|
327 |
+
const t=w('<div class="dropdown-input-wrap">')
|
328 |
+
t.append(e.control_input),e.dropdown.insertBefore(t,e.dropdown.firstChild)})),e.on("initialize",(()=>{e.control_input.addEventListener("keydown",(t=>{switch(t.keyCode){case 27:return e.isOpen&&(H(t,!0),e.close()),void e.clearActiveItems()
|
329 |
+
case 9:e.focus_node.tabIndex=-1}return e.onKeyDown.call(e,t)})),e.on("blur",(()=>{e.focus_node.tabIndex=e.isDisabled?-1:e.tabIndex})),e.on("dropdown_open",(()=>{e.control_input.focus()}))
|
330 |
+
const t=e.onBlur
|
331 |
+
e.hook("instead","onBlur",(i=>{if(!i||i.relatedTarget!=e.control_input)return t.call(e)})),B(e.control_input,"blur",(()=>e.onBlur())),e.hook("before","close",(()=>{e.isOpen&&e.focus_node.focus()}))}))})),J.define("input_autogrow",(function(){var e=this
|
332 |
+
e.on("initialize",(()=>{var t=document.createElement("span"),i=e.control_input
|
333 |
+
t.style.cssText="position:absolute; top:-99999px; left:-99999px; width:auto; padding:0; white-space:pre; ",e.wrapper.appendChild(t)
|
334 |
+
for(const e of["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"])t.style[e]=i.style[e]
|
335 |
+
var s=()=>{e.items.length>0?(t.textContent=i.value,i.style.width=t.clientWidth+"px"):i.style.width=""}
|
336 |
+
s(),e.on("update item_add item_remove",s),B(i,"input",s),B(i,"keyup",s),B(i,"blur",s),B(i,"update",s)}))})),J.define("no_backspace_delete",(function(){var e=this,t=e.deleteSelection
|
337 |
+
this.hook("instead","deleteSelection",(i=>!!e.activeItems.length&&t.call(e,i)))})),J.define("no_active_items",(function(){this.hook("instead","setActiveItem",(()=>{})),this.hook("instead","selectAll",(()=>{}))})),J.define("optgroup_columns",(function(){var e=this,t=e.onKeyDown
|
338 |
+
e.hook("instead","onKeyDown",(i=>{var s,n,o,r
|
339 |
+
if(!e.isOpen||37!==i.keyCode&&39!==i.keyCode)return t.call(e,i)
|
340 |
+
r=k(e.activeOption,"[data-group]"),s=L(e.activeOption,"[data-selectable]"),r&&(r=37===i.keyCode?r.previousSibling:r.nextSibling)&&(n=(o=r.querySelectorAll("[data-selectable]"))[Math.min(o.length-1,s)])&&e.setActiveOption(n)}))})),J.define("remove_button",(function(e){const t=Object.assign({label:"×",title:"Remove",className:"remove",append:!0},e)
|
341 |
+
var i=this
|
342 |
+
if(t.append){var s='<a href="javascript:void(0)" class="'+t.className+'" tabindex="-1" title="'+N(t.title)+'">'+t.label+"</a>"
|
343 |
+
i.hook("after","setupTemplates",(()=>{var e=i.settings.render.item
|
344 |
+
i.settings.render.item=(t,n)=>{var o=w(e.call(i,t,n)),r=w(s)
|
345 |
+
return o.appendChild(r),B(r,"mousedown",(e=>{H(e,!0)})),B(r,"click",(e=>{if(H(e,!0),!i.isLocked){var t=o.dataset.value
|
346 |
+
i.removeItem(t),i.refreshOptions(!1)}})),o}}))}})),J.define("restore_on_backspace",(function(e){const t=this,i=Object.assign({text:e=>e[t.settings.labelField]},e)
|
347 |
+
t.on("item_remove",(function(e){if(""===t.control_input.value.trim()){var s=t.options[e]
|
348 |
+
s&&t.setTextboxValue(i.text.call(t,s))}}))})),J.define("virtual_scroll",(function(){const e=this,t=e.canLoad,i=e.clearActiveOption,s=e.loadCallback
|
349 |
+
var n,o={},r=!1
|
350 |
+
if(!e.settings.firstUrl)throw"virtual_scroll plugin requires a firstUrl() method"
|
351 |
+
function l(t){return!("number"==typeof e.settings.maxOptions&&n.children.length>=e.settings.maxOptions)&&!(!(t in o)||!o[t])}e.settings.sortField=[{field:"$order"},{field:"$score"}],e.setNextUrl=function(e,t){o[e]=t},e.getUrl=function(t){if(t in o){const e=o[t]
|
352 |
+
return o[t]=!1,e}return o={},e.settings.firstUrl(t)},e.hook("instead","clearActiveOption",(()=>{if(!r)return i.call(e)})),e.hook("instead","canLoad",(i=>i in o?l(i):t.call(e,i))),e.hook("instead","loadCallback",((t,i)=>{r||e.clearOptions(),s.call(e,t,i),r=!1})),e.hook("after","refreshOptions",(()=>{const t=e.lastValue
|
353 |
+
var i
|
354 |
+
l(t)?(i=e.render("loading_more",{query:t}))&&i.setAttribute("data-selectable",""):t in o&&!n.querySelector(".no-results")&&(i=e.render("no_more_results",{query:t})),i&&(C(i,e.settings.optionClass),n.append(i))})),e.on("initialize",(()=>{n=e.dropdown_content,e.settings.render=Object.assign({},{loading_more:function(){return'<div class="loading-more-results">Loading more results ... </div>'},no_more_results:function(){return'<div class="no-more-results">No more results</div>'}},e.settings.render),n.addEventListener("scroll",(function(){n.clientHeight/(n.scrollHeight-n.scrollTop)<.95||l(e.lastValue)&&(r||(r=!0,e.load.call(e,e.lastValue)))}))}))})),J}))
|
355 |
+
var tomSelect=function(e,t){return new TomSelect(e,t)}
|
356 |
+
//# sourceMappingURL=tom-select.complete.min.js.map
|
lib/tom-select/tom-select.css
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* tom-select.css (v2.0.0-rc.4)
|
3 |
+
* Copyright (c) contributors
|
4 |
+
*
|
5 |
+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
|
6 |
+
* file except in compliance with the License. You may obtain a copy of the License at:
|
7 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
*
|
9 |
+
* Unless required by applicable law or agreed to in writing, software distributed under
|
10 |
+
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
|
11 |
+
* ANY KIND, either express or implied. See the License for the specific language
|
12 |
+
* governing permissions and limitations under the License.
|
13 |
+
*
|
14 |
+
*/
|
15 |
+
.ts-wrapper.plugin-drag_drop.multi > .ts-control > div.ui-sortable-placeholder {
|
16 |
+
visibility: visible !important;
|
17 |
+
background: #f2f2f2 !important;
|
18 |
+
background: rgba(0, 0, 0, 0.06) !important;
|
19 |
+
border: 0 none !important;
|
20 |
+
box-shadow: inset 0 0 12px 4px #fff; }
|
21 |
+
|
22 |
+
.ts-wrapper.plugin-drag_drop .ui-sortable-placeholder::after {
|
23 |
+
content: '!';
|
24 |
+
visibility: hidden; }
|
25 |
+
|
26 |
+
.ts-wrapper.plugin-drag_drop .ui-sortable-helper {
|
27 |
+
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); }
|
28 |
+
|
29 |
+
.plugin-checkbox_options .option input {
|
30 |
+
margin-right: 0.5rem; }
|
31 |
+
|
32 |
+
.plugin-clear_button .ts-control {
|
33 |
+
padding-right: calc( 1em + (3 * 6px)) !important; }
|
34 |
+
|
35 |
+
.plugin-clear_button .clear-button {
|
36 |
+
opacity: 0;
|
37 |
+
position: absolute;
|
38 |
+
top: 8px;
|
39 |
+
right: calc(8px - 6px);
|
40 |
+
margin-right: 0 !important;
|
41 |
+
background: transparent !important;
|
42 |
+
transition: opacity 0.5s;
|
43 |
+
cursor: pointer; }
|
44 |
+
|
45 |
+
.plugin-clear_button.single .clear-button {
|
46 |
+
right: calc(8px - 6px + 2rem); }
|
47 |
+
|
48 |
+
.plugin-clear_button.focus.has-items .clear-button,
|
49 |
+
.plugin-clear_button:hover.has-items .clear-button {
|
50 |
+
opacity: 1; }
|
51 |
+
|
52 |
+
.ts-wrapper .dropdown-header {
|
53 |
+
position: relative;
|
54 |
+
padding: 10px 8px;
|
55 |
+
border-bottom: 1px solid #d0d0d0;
|
56 |
+
background: #f8f8f8;
|
57 |
+
border-radius: 3px 3px 0 0; }
|
58 |
+
|
59 |
+
.ts-wrapper .dropdown-header-close {
|
60 |
+
position: absolute;
|
61 |
+
right: 8px;
|
62 |
+
top: 50%;
|
63 |
+
color: #303030;
|
64 |
+
opacity: 0.4;
|
65 |
+
margin-top: -12px;
|
66 |
+
line-height: 20px;
|
67 |
+
font-size: 20px !important; }
|
68 |
+
|
69 |
+
.ts-wrapper .dropdown-header-close:hover {
|
70 |
+
color: black; }
|
71 |
+
|
72 |
+
.plugin-dropdown_input.focus.dropdown-active .ts-control {
|
73 |
+
box-shadow: none;
|
74 |
+
border: 1px solid #d0d0d0; }
|
75 |
+
|
76 |
+
.plugin-dropdown_input .dropdown-input {
|
77 |
+
border: 1px solid #d0d0d0;
|
78 |
+
border-width: 0 0 1px 0;
|
79 |
+
display: block;
|
80 |
+
padding: 8px 8px;
|
81 |
+
box-shadow: none;
|
82 |
+
width: 100%;
|
83 |
+
background: transparent; }
|
84 |
+
|
85 |
+
.ts-wrapper.plugin-input_autogrow.has-items .ts-control > input {
|
86 |
+
min-width: 0; }
|
87 |
+
|
88 |
+
.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input {
|
89 |
+
flex: none;
|
90 |
+
min-width: 4px; }
|
91 |
+
.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::-webkit-input-placeholder {
|
92 |
+
color: transparent; }
|
93 |
+
.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::-ms-input-placeholder {
|
94 |
+
color: transparent; }
|
95 |
+
.ts-wrapper.plugin-input_autogrow.has-items.focus .ts-control > input::placeholder {
|
96 |
+
color: transparent; }
|
97 |
+
|
98 |
+
.ts-dropdown.plugin-optgroup_columns .ts-dropdown-content {
|
99 |
+
display: flex; }
|
100 |
+
|
101 |
+
.ts-dropdown.plugin-optgroup_columns .optgroup {
|
102 |
+
border-right: 1px solid #f2f2f2;
|
103 |
+
border-top: 0 none;
|
104 |
+
flex-grow: 1;
|
105 |
+
flex-basis: 0;
|
106 |
+
min-width: 0; }
|
107 |
+
|
108 |
+
.ts-dropdown.plugin-optgroup_columns .optgroup:last-child {
|
109 |
+
border-right: 0 none; }
|
110 |
+
|
111 |
+
.ts-dropdown.plugin-optgroup_columns .optgroup:before {
|
112 |
+
display: none; }
|
113 |
+
|
114 |
+
.ts-dropdown.plugin-optgroup_columns .optgroup-header {
|
115 |
+
border-top: 0 none; }
|
116 |
+
|
117 |
+
.ts-wrapper.plugin-remove_button .item {
|
118 |
+
display: inline-flex;
|
119 |
+
align-items: center;
|
120 |
+
padding-right: 0 !important; }
|
121 |
+
|
122 |
+
.ts-wrapper.plugin-remove_button .item .remove {
|
123 |
+
color: inherit;
|
124 |
+
text-decoration: none;
|
125 |
+
vertical-align: middle;
|
126 |
+
display: inline-block;
|
127 |
+
padding: 2px 6px;
|
128 |
+
border-left: 1px solid #d0d0d0;
|
129 |
+
border-radius: 0 2px 2px 0;
|
130 |
+
box-sizing: border-box;
|
131 |
+
margin-left: 6px; }
|
132 |
+
|
133 |
+
.ts-wrapper.plugin-remove_button .item .remove:hover {
|
134 |
+
background: rgba(0, 0, 0, 0.05); }
|
135 |
+
|
136 |
+
.ts-wrapper.plugin-remove_button .item.active .remove {
|
137 |
+
border-left-color: #cacaca; }
|
138 |
+
|
139 |
+
.ts-wrapper.plugin-remove_button.disabled .item .remove:hover {
|
140 |
+
background: none; }
|
141 |
+
|
142 |
+
.ts-wrapper.plugin-remove_button.disabled .item .remove {
|
143 |
+
border-left-color: white; }
|
144 |
+
|
145 |
+
.ts-wrapper.plugin-remove_button .remove-single {
|
146 |
+
position: absolute;
|
147 |
+
right: 0;
|
148 |
+
top: 0;
|
149 |
+
font-size: 23px; }
|
150 |
+
|
151 |
+
.ts-wrapper {
|
152 |
+
position: relative; }
|
153 |
+
|
154 |
+
.ts-dropdown,
|
155 |
+
.ts-control,
|
156 |
+
.ts-control input {
|
157 |
+
color: #303030;
|
158 |
+
font-family: inherit;
|
159 |
+
font-size: 13px;
|
160 |
+
line-height: 18px;
|
161 |
+
font-smoothing: inherit; }
|
162 |
+
|
163 |
+
.ts-control,
|
164 |
+
.ts-wrapper.single.input-active .ts-control {
|
165 |
+
background: #fff;
|
166 |
+
cursor: text; }
|
167 |
+
|
168 |
+
.ts-control {
|
169 |
+
border: 1px solid #d0d0d0;
|
170 |
+
padding: 8px 8px;
|
171 |
+
width: 100%;
|
172 |
+
overflow: hidden;
|
173 |
+
position: relative;
|
174 |
+
z-index: 1;
|
175 |
+
box-sizing: border-box;
|
176 |
+
box-shadow: none;
|
177 |
+
border-radius: 3px;
|
178 |
+
display: flex;
|
179 |
+
flex-wrap: wrap; }
|
180 |
+
.ts-wrapper.multi.has-items .ts-control {
|
181 |
+
padding: calc( 8px - 2px - 0) 8px calc( 8px - 2px - 3px - 0); }
|
182 |
+
.full .ts-control {
|
183 |
+
background-color: #fff; }
|
184 |
+
.disabled .ts-control,
|
185 |
+
.disabled .ts-control * {
|
186 |
+
cursor: default !important; }
|
187 |
+
.focus .ts-control {
|
188 |
+
box-shadow: none; }
|
189 |
+
.ts-control > * {
|
190 |
+
vertical-align: baseline;
|
191 |
+
display: inline-block; }
|
192 |
+
.ts-wrapper.multi .ts-control > div {
|
193 |
+
cursor: pointer;
|
194 |
+
margin: 0 3px 3px 0;
|
195 |
+
padding: 2px 6px;
|
196 |
+
background: #f2f2f2;
|
197 |
+
color: #303030;
|
198 |
+
border: 0 solid #d0d0d0; }
|
199 |
+
.ts-wrapper.multi .ts-control > div.active {
|
200 |
+
background: #e8e8e8;
|
201 |
+
color: #303030;
|
202 |
+
border: 0 solid #cacaca; }
|
203 |
+
.ts-wrapper.multi.disabled .ts-control > div, .ts-wrapper.multi.disabled .ts-control > div.active {
|
204 |
+
color: #7d7c7c;
|
205 |
+
background: white;
|
206 |
+
border: 0 solid white; }
|
207 |
+
.ts-control > input {
|
208 |
+
flex: 1 1 auto;
|
209 |
+
min-width: 7rem;
|
210 |
+
display: inline-block !important;
|
211 |
+
padding: 0 !important;
|
212 |
+
min-height: 0 !important;
|
213 |
+
max-height: none !important;
|
214 |
+
max-width: 100% !important;
|
215 |
+
margin: 0 !important;
|
216 |
+
text-indent: 0 !important;
|
217 |
+
border: 0 none !important;
|
218 |
+
background: none !important;
|
219 |
+
line-height: inherit !important;
|
220 |
+
-webkit-user-select: auto !important;
|
221 |
+
-moz-user-select: auto !important;
|
222 |
+
-ms-user-select: auto !important;
|
223 |
+
user-select: auto !important;
|
224 |
+
box-shadow: none !important; }
|
225 |
+
.ts-control > input::-ms-clear {
|
226 |
+
display: none; }
|
227 |
+
.ts-control > input:focus {
|
228 |
+
outline: none !important; }
|
229 |
+
.has-items .ts-control > input {
|
230 |
+
margin: 0 4px !important; }
|
231 |
+
.ts-control.rtl {
|
232 |
+
text-align: right; }
|
233 |
+
.ts-control.rtl.single .ts-control:after {
|
234 |
+
left: 15px;
|
235 |
+
right: auto; }
|
236 |
+
.ts-control.rtl .ts-control > input {
|
237 |
+
margin: 0 4px 0 -2px !important; }
|
238 |
+
.disabled .ts-control {
|
239 |
+
opacity: 0.5;
|
240 |
+
background-color: #fafafa; }
|
241 |
+
.input-hidden .ts-control > input {
|
242 |
+
opacity: 0;
|
243 |
+
position: absolute;
|
244 |
+
left: -10000px; }
|
245 |
+
|
246 |
+
.ts-dropdown {
|
247 |
+
position: absolute;
|
248 |
+
top: 100%;
|
249 |
+
left: 0;
|
250 |
+
width: 100%;
|
251 |
+
z-index: 10;
|
252 |
+
border: 1px solid #d0d0d0;
|
253 |
+
background: #fff;
|
254 |
+
margin: 0.25rem 0 0 0;
|
255 |
+
border-top: 0 none;
|
256 |
+
box-sizing: border-box;
|
257 |
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
258 |
+
border-radius: 0 0 3px 3px; }
|
259 |
+
.ts-dropdown [data-selectable] {
|
260 |
+
cursor: pointer;
|
261 |
+
overflow: hidden; }
|
262 |
+
.ts-dropdown [data-selectable] .highlight {
|
263 |
+
background: rgba(125, 168, 208, 0.2);
|
264 |
+
border-radius: 1px; }
|
265 |
+
.ts-dropdown .option,
|
266 |
+
.ts-dropdown .optgroup-header,
|
267 |
+
.ts-dropdown .no-results,
|
268 |
+
.ts-dropdown .create {
|
269 |
+
padding: 5px 8px; }
|
270 |
+
.ts-dropdown .option, .ts-dropdown [data-disabled], .ts-dropdown [data-disabled] [data-selectable].option {
|
271 |
+
cursor: inherit;
|
272 |
+
opacity: 0.5; }
|
273 |
+
.ts-dropdown [data-selectable].option {
|
274 |
+
opacity: 1;
|
275 |
+
cursor: pointer; }
|
276 |
+
.ts-dropdown .optgroup:first-child .optgroup-header {
|
277 |
+
border-top: 0 none; }
|
278 |
+
.ts-dropdown .optgroup-header {
|
279 |
+
color: #303030;
|
280 |
+
background: #fff;
|
281 |
+
cursor: default; }
|
282 |
+
.ts-dropdown .create:hover,
|
283 |
+
.ts-dropdown .option:hover,
|
284 |
+
.ts-dropdown .active {
|
285 |
+
background-color: #f5fafd;
|
286 |
+
color: #495c68; }
|
287 |
+
.ts-dropdown .create:hover.create,
|
288 |
+
.ts-dropdown .option:hover.create,
|
289 |
+
.ts-dropdown .active.create {
|
290 |
+
color: #495c68; }
|
291 |
+
.ts-dropdown .create {
|
292 |
+
color: rgba(48, 48, 48, 0.5); }
|
293 |
+
.ts-dropdown .spinner {
|
294 |
+
display: inline-block;
|
295 |
+
width: 30px;
|
296 |
+
height: 30px;
|
297 |
+
margin: 5px 8px; }
|
298 |
+
.ts-dropdown .spinner:after {
|
299 |
+
content: " ";
|
300 |
+
display: block;
|
301 |
+
width: 24px;
|
302 |
+
height: 24px;
|
303 |
+
margin: 3px;
|
304 |
+
border-radius: 50%;
|
305 |
+
border: 5px solid #d0d0d0;
|
306 |
+
border-color: #d0d0d0 transparent #d0d0d0 transparent;
|
307 |
+
animation: lds-dual-ring 1.2s linear infinite; }
|
308 |
+
|
309 |
+
@keyframes lds-dual-ring {
|
310 |
+
0% {
|
311 |
+
transform: rotate(0deg); }
|
312 |
+
100% {
|
313 |
+
transform: rotate(360deg); } }
|
314 |
+
|
315 |
+
.ts-dropdown-content {
|
316 |
+
overflow-y: auto;
|
317 |
+
overflow-x: hidden;
|
318 |
+
max-height: 200px;
|
319 |
+
overflow-scrolling: touch;
|
320 |
+
scroll-behavior: smooth; }
|
321 |
+
|
322 |
+
.ts-hidden-accessible {
|
323 |
+
border: 0 !important;
|
324 |
+
clip: rect(0 0 0 0) !important;
|
325 |
+
-webkit-clip-path: inset(50%) !important;
|
326 |
+
clip-path: inset(50%) !important;
|
327 |
+
height: 1px !important;
|
328 |
+
overflow: hidden !important;
|
329 |
+
padding: 0 !important;
|
330 |
+
position: absolute !important;
|
331 |
+
width: 1px !important;
|
332 |
+
white-space: nowrap !important; }
|
333 |
+
|
334 |
+
/*# sourceMappingURL=tom-select.css.map */
|
lib/vis-9.0.4/vis-network.css
ADDED
The diff for this file is too large to render.
See raw diff
|
|
lib/vis-9.0.4/vis-network.min.js
ADDED
The diff for this file is too large to render.
See raw diff
|
|
lib/vis-9.1.2/vis-network.css
ADDED
The diff for this file is too large to render.
See raw diff
|
|
lib/vis-9.1.2/vis-network.min.js
ADDED
The diff for this file is too large to render.
See raw diff
|
|
networks/network.html
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<html>
|
2 |
+
<head>
|
3 |
+
<meta charset="utf-8">
|
4 |
+
|
5 |
+
<script src="lib/bindings/utils.js"></script>
|
6 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/dist/vis-network.min.css" integrity="sha512-WgxfT5LWjfszlPHXRmBWHkV2eceiWTOBvrKCNbdgDYTHrT2AeLCGbF4sZlZw3UMN3WtL0tGUoIAKsu8mllg/XA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
|
7 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.2/dist/vis-network.min.js" integrity="sha512-LnvoEWDFrqGHlHmDD2101OrLcbsfkrzoSpvtSQtxK3RMnRV0eOkhhBN2dXHKRrUU8p2DGRTk35n4O8nWSVe1mQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
|
8 |
+
|
9 |
+
|
10 |
+
<center>
|
11 |
+
<h1></h1>
|
12 |
+
</center>
|
13 |
+
|
14 |
+
<!-- <link rel="stylesheet" href="../node_modules/vis/dist/vis.min.css" type="text/css" />
|
15 |
+
<script type="text/javascript" src="../node_modules/vis/dist/vis.js"> </script>-->
|
16 |
+
<link
|
17 |
+
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
|
18 |
+
rel="stylesheet"
|
19 |
+
integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
|
20 |
+
crossorigin="anonymous"
|
21 |
+
/>
|
22 |
+
<script
|
23 |
+
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
|
24 |
+
integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
|
25 |
+
crossorigin="anonymous"
|
26 |
+
></script>
|
27 |
+
|
28 |
+
|
29 |
+
<center>
|
30 |
+
<h1></h1>
|
31 |
+
</center>
|
32 |
+
<style type="text/css">
|
33 |
+
|
34 |
+
#mynetwork {
|
35 |
+
width: 700px;
|
36 |
+
height: 700px;
|
37 |
+
background-color: #ffffff;
|
38 |
+
border: 1px solid lightgray;
|
39 |
+
position: relative;
|
40 |
+
float: left;
|
41 |
+
}
|
42 |
+
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
#config {
|
47 |
+
float: left;
|
48 |
+
width: 400px;
|
49 |
+
height: 600px;
|
50 |
+
}
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
</style>
|
55 |
+
</head>
|
56 |
+
|
57 |
+
|
58 |
+
<body>
|
59 |
+
<div class="card" style="width: 100%">
|
60 |
+
|
61 |
+
|
62 |
+
<div id="mynetwork" class="card-body"></div>
|
63 |
+
</div>
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
<div id="config"></div>
|
68 |
+
|
69 |
+
|
70 |
+
<script type="text/javascript">
|
71 |
+
|
72 |
+
// initialize global variables.
|
73 |
+
var edges;
|
74 |
+
var nodes;
|
75 |
+
var allNodes;
|
76 |
+
var allEdges;
|
77 |
+
var nodeColors;
|
78 |
+
var originalNodes;
|
79 |
+
var network;
|
80 |
+
var container;
|
81 |
+
var options, data;
|
82 |
+
var filter = {
|
83 |
+
item : '',
|
84 |
+
property : '',
|
85 |
+
value : []
|
86 |
+
};
|
87 |
+
|
88 |
+
|
89 |
+
|
90 |
+
|
91 |
+
|
92 |
+
// This method is responsible for drawing the graph, returns the drawn network
|
93 |
+
function drawGraph() {
|
94 |
+
var container = document.getElementById('mynetwork');
|
95 |
+
|
96 |
+
|
97 |
+
|
98 |
+
// parsing and collecting nodes and edges from the python
|
99 |
+
nodes = new vis.DataSet([{"color": "#00FF00", "id": "Google", "label": "Google", "shape": "circle"}, {"color": "#00FF00", "id": "Alphabet", "label": "Alphabet", "shape": "circle"}, {"color": "#00FF00", "id": "Larry Page", "label": "Larry Page", "shape": "circle"}, {"color": "#00FF00", "id": "Stanford University", "label": "Stanford University", "shape": "circle"}, {"color": "#00FF00", "id": "Sergey Brin", "label": "Sergey Brin", "shape": "circle"}, {"color": "#00FF00", "id": "Sundar Pichai", "label": "Sundar Pichai", "shape": "circle"}, {"color": "#00FF00", "id": "Alphabet Inc.", "label": "Alphabet Inc.", "shape": "circle"}, {"color": "#00FF00", "id": "Google Search", "label": "Google Search", "shape": "circle"}, {"color": "#00FF00", "id": "Gmail", "label": "Gmail", "shape": "circle"}, {"color": "#00FF00", "id": "YouTube", "label": "YouTube", "shape": "circle"}, {"color": "#00FF00", "id": "Nest", "label": "Nest", "shape": "circle"}, {"color": "#00FF00", "id": "Pixel", "label": "Pixel", "shape": "circle"}, {"color": "#00FF00", "id": "Google Assistant", "label": "Google Assistant", "shape": "circle"}, {"color": "#00FF00", "id": "Artificial intelligence", "label": "Artificial intelligence", "shape": "circle"}, {"color": "#00FF00", "id": "Machine learning", "label": "Machine learning", "shape": "circle"}, {"color": "#00FF00", "id": "TensorFlow", "label": "TensorFlow", "shape": "circle"}, {"color": "#00FF00", "id": "Pixel Watch", "label": "Pixel Watch", "shape": "circle"}, {"color": "#00FF00", "id": "Fitbit", "label": "Fitbit", "shape": "circle"}, {"color": "#00FF00", "id": "Google Brain", "label": "Google Brain", "shape": "circle"}]);
|
100 |
+
edges = new vis.DataSet([{"arrows": "to", "from": "Google", "label": "parent organization", "title": "parent organization", "to": "Alphabet"}, {"arrows": "to", "from": "Google", "label": "founded by", "title": "founded by", "to": "Larry Page"}, {"arrows": "to", "from": "Alphabet", "label": "subsidiary", "title": "subsidiary", "to": "Google"}, {"arrows": "to", "from": "Alphabet", "label": "founded by", "title": "founded by", "to": "Larry Page"}, {"arrows": "to", "from": "Larry Page", "label": "educated at", "title": "educated at", "to": "Stanford University"}, {"arrows": "to", "from": "Sergey Brin", "label": "educated at", "title": "educated at", "to": "Stanford University"}, {"arrows": "to", "from": "Sundar Pichai", "label": "employer", "title": "employer", "to": "Google"}, {"arrows": "to", "from": "Google", "label": "parent organization", "title": "parent organization", "to": "Alphabet Inc."}, {"arrows": "to", "from": "Alphabet Inc.", "label": "subsidiary", "title": "subsidiary", "to": "Google"}, {"arrows": "to", "from": "Google Search", "label": "owned by", "title": "owned by", "to": "Alphabet"}, {"arrows": "to", "from": "Gmail", "label": "owned by", "title": "owned by", "to": "Alphabet"}, {"arrows": "to", "from": "YouTube", "label": "owned by", "title": "owned by", "to": "Alphabet"}, {"arrows": "to", "from": "Nest", "label": "developer", "title": "developer", "to": "Alphabet"}, {"arrows": "to", "from": "Pixel", "label": "manufacturer", "title": "manufacturer", "to": "Alphabet"}, {"arrows": "to", "from": "Nest", "label": "owned by", "title": "owned by", "to": "Alphabet"}, {"arrows": "to", "from": "Google Assistant", "label": "use", "title": "use", "to": "Artificial intelligence"}, {"arrows": "to", "from": "Machine learning", "label": "part of", "title": "part of", "to": "Artificial intelligence"}, {"arrows": "to", "from": "TensorFlow", "label": "use", "title": "use", "to": "Artificial intelligence"}, {"arrows": "to", "from": "Pixel Watch", "label": "connects with", "title": "connects with", "to": "Fitbit"}, {"arrows": "to", "from": "Fitbit", "label": "connects with", "title": "connects with", "to": "Pixel Watch"}, {"arrows": "to", "from": "Google", "label": "subsidiary", "title": "subsidiary", "to": "YouTube"}, {"arrows": "to", "from": "YouTube", "label": "parent organization", "title": "parent organization", "to": "Google"}, {"arrows": "to", "from": "YouTube", "label": "owned by", "title": "owned by", "to": "Google"}, {"arrows": "to", "from": "Google Brain", "label": "owned by", "title": "owned by", "to": "Google"}, {"arrows": "to", "from": "Google", "label": "owner of", "title": "owner of", "to": "Google Brain"}]);
|
101 |
+
|
102 |
+
nodeColors = {};
|
103 |
+
allNodes = nodes.get({ returnType: "Object" });
|
104 |
+
for (nodeId in allNodes) {
|
105 |
+
nodeColors[nodeId] = allNodes[nodeId].color;
|
106 |
+
}
|
107 |
+
allEdges = edges.get({ returnType: "Object" });
|
108 |
+
// adding nodes and edges to the graph
|
109 |
+
data = {nodes: nodes, edges: edges};
|
110 |
+
|
111 |
+
var options = {
|
112 |
+
"configure": {
|
113 |
+
"enabled": true,
|
114 |
+
"filter": [
|
115 |
+
"physics"
|
116 |
+
]
|
117 |
+
},
|
118 |
+
"edges": {
|
119 |
+
"color": {
|
120 |
+
"inherit": true
|
121 |
+
},
|
122 |
+
"smooth": {
|
123 |
+
"enabled": true,
|
124 |
+
"type": "dynamic"
|
125 |
+
}
|
126 |
+
},
|
127 |
+
"interaction": {
|
128 |
+
"dragNodes": true,
|
129 |
+
"hideEdgesOnDrag": false,
|
130 |
+
"hideNodesOnDrag": false
|
131 |
+
},
|
132 |
+
"physics": {
|
133 |
+
"enabled": true,
|
134 |
+
"repulsion": {
|
135 |
+
"centralGravity": 0.2,
|
136 |
+
"damping": 0.09,
|
137 |
+
"nodeDistance": 200,
|
138 |
+
"springConstant": 0.05,
|
139 |
+
"springLength": 200
|
140 |
+
},
|
141 |
+
"solver": "repulsion",
|
142 |
+
"stabilization": {
|
143 |
+
"enabled": true,
|
144 |
+
"fit": true,
|
145 |
+
"iterations": 1000,
|
146 |
+
"onlyDynamicEdges": false,
|
147 |
+
"updateInterval": 50
|
148 |
+
}
|
149 |
+
}
|
150 |
+
};
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
|
156 |
+
// if this network requires displaying the configure window,
|
157 |
+
// put it in its div
|
158 |
+
options.configure["container"] = document.getElementById("config");
|
159 |
+
|
160 |
+
|
161 |
+
network = new vis.Network(container, data, options);
|
162 |
+
|
163 |
+
|
164 |
+
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
|
171 |
+
|
172 |
+
return network;
|
173 |
+
|
174 |
+
}
|
175 |
+
drawGraph();
|
176 |
+
</script>
|
177 |
+
</body>
|
178 |
+
</html>
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
transformers
|
3 |
+
pyvis
|
4 |
+
GoogleNews
|
5 |
+
newspaper3k
|
6 |
+
wikipedia
|
utils.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import pickle
|
3 |
+
import re
|
4 |
+
|
5 |
+
import bs4
|
6 |
+
import torch
|
7 |
+
from GoogleNews import GoogleNews
|
8 |
+
from tqdm import tqdm
|
9 |
+
from kb import KB
|
10 |
+
from newspaper import Article, ArticleException
|
11 |
+
from pyvis.network import Network
|
12 |
+
|
13 |
+
|
14 |
+
def extract_relations_from_model_output(text):
|
15 |
+
relations = []
|
16 |
+
relation, subject, relation, object_ = '', '', '', ''
|
17 |
+
text = text.strip()
|
18 |
+
current = 'x'
|
19 |
+
text_replaced = text.replace("<s>", "").replace("<pad>", "").replace("</s>", "")
|
20 |
+
for token in text_replaced.split():
|
21 |
+
if token == "<obj>":
|
22 |
+
current = 'o'
|
23 |
+
relation = ''
|
24 |
+
elif token == "<subj>":
|
25 |
+
current = 's'
|
26 |
+
if relation != '':
|
27 |
+
relations.append({
|
28 |
+
'head': subject.strip(),
|
29 |
+
'type': relation.strip(),
|
30 |
+
'tail': object_.strip()
|
31 |
+
})
|
32 |
+
object_ = ''
|
33 |
+
elif token == "<triplet>":
|
34 |
+
current = 't'
|
35 |
+
if relation != '':
|
36 |
+
relations.append({
|
37 |
+
'head': subject.strip(),
|
38 |
+
'type': relation.strip(),
|
39 |
+
'tail': object_.strip()
|
40 |
+
})
|
41 |
+
relation = ''
|
42 |
+
subject = ''
|
43 |
+
elif current == 'o':
|
44 |
+
relation += f' {token}'
|
45 |
+
elif current == 's':
|
46 |
+
object_ += f' {token}'
|
47 |
+
elif current == 't':
|
48 |
+
subject += f' {token}'
|
49 |
+
if subject != '' and relation != '' and object_ != '':
|
50 |
+
relations.append({
|
51 |
+
'head': subject.strip(),
|
52 |
+
'type': relation.strip(),
|
53 |
+
'tail': object_.strip()
|
54 |
+
})
|
55 |
+
|
56 |
+
return relations
|
57 |
+
|
58 |
+
def from_text_to_kb(text, model, tokenizer, article_url, span_length=128, article_title=None,
|
59 |
+
article_publish_date=None, verbose=False):
|
60 |
+
# tokenize whole text
|
61 |
+
print('Start tokenizing')
|
62 |
+
inputs = tokenizer([text], return_tensors="pt")
|
63 |
+
print('End tokenizing')
|
64 |
+
|
65 |
+
# compute span boundaries
|
66 |
+
num_tokens = len(inputs["input_ids"][0])
|
67 |
+
if verbose:
|
68 |
+
print(f"Input has {num_tokens} tokens")
|
69 |
+
num_spans = math.ceil(num_tokens / span_length)
|
70 |
+
if verbose:
|
71 |
+
print(f"Input has {num_spans} spans")
|
72 |
+
overlap = math.ceil((num_spans * span_length - num_tokens) /
|
73 |
+
max(num_spans - 1, 1))
|
74 |
+
spans_boundaries = []
|
75 |
+
start = 0
|
76 |
+
for i in tqdm(range(num_spans)):
|
77 |
+
spans_boundaries.append([start + span_length * i,
|
78 |
+
start + span_length * (i + 1)])
|
79 |
+
start -= overlap
|
80 |
+
if verbose:
|
81 |
+
print(f"Span boundaries are {spans_boundaries}")
|
82 |
+
|
83 |
+
# transform input with spans
|
84 |
+
tensor_ids = [inputs["input_ids"][0][boundary[0]:boundary[1]]
|
85 |
+
for boundary in spans_boundaries]
|
86 |
+
tensor_masks = [inputs["attention_mask"][0][boundary[0]:boundary[1]]
|
87 |
+
for boundary in spans_boundaries]
|
88 |
+
inputs = {
|
89 |
+
"input_ids": torch.stack(tensor_ids),
|
90 |
+
"attention_mask": torch.stack(tensor_masks)
|
91 |
+
}
|
92 |
+
|
93 |
+
# generate relations
|
94 |
+
num_return_sequences = 3
|
95 |
+
gen_kwargs = {
|
96 |
+
"max_length": 256,
|
97 |
+
"length_penalty": 0,
|
98 |
+
"num_beams": 3,
|
99 |
+
"num_return_sequences": num_return_sequences
|
100 |
+
}
|
101 |
+
generated_tokens = model.generate(
|
102 |
+
**inputs,
|
103 |
+
**gen_kwargs,
|
104 |
+
)
|
105 |
+
|
106 |
+
# decode relations
|
107 |
+
decoded_preds = tokenizer.batch_decode(generated_tokens,
|
108 |
+
skip_special_tokens=False)
|
109 |
+
|
110 |
+
# create kb
|
111 |
+
kb = KB()
|
112 |
+
for i, sentence_pred in enumerate(decoded_preds):
|
113 |
+
current_span_index = i // num_return_sequences
|
114 |
+
relations = extract_relations_from_model_output(sentence_pred)
|
115 |
+
for relation in relations:
|
116 |
+
relation["meta"] = {
|
117 |
+
article_url: {
|
118 |
+
"spans": [spans_boundaries[current_span_index]]
|
119 |
+
}
|
120 |
+
}
|
121 |
+
kb.add_relation(relation, article_title, article_publish_date)
|
122 |
+
return kb
|
123 |
+
|
124 |
+
def get_article(url):
|
125 |
+
article = Article(url)
|
126 |
+
article.download()
|
127 |
+
article.parse()
|
128 |
+
return article
|
129 |
+
|
130 |
+
def from_url_to_kb(url, model, tokenizer):
|
131 |
+
article = get_article(url)
|
132 |
+
config = {
|
133 |
+
"article_title": article.title,
|
134 |
+
"article_publish_date": article.publish_date
|
135 |
+
}
|
136 |
+
return from_text_to_kb(article.text, model, tokenizer, article.url, **config)
|
137 |
+
|
138 |
+
def get_news_links(query, lang="en", region="US", pages=1):
|
139 |
+
googlenews = GoogleNews(lang=lang, region=region)
|
140 |
+
googlenews.search(query)
|
141 |
+
all_urls = []
|
142 |
+
for page in range(pages):
|
143 |
+
googlenews.get_page(page)
|
144 |
+
all_urls += googlenews.get_links()
|
145 |
+
return list(set(all_urls))
|
146 |
+
|
147 |
+
def from_urls_to_kb(urls, model, tokenizer, verbose=False):
|
148 |
+
kb = KB()
|
149 |
+
if verbose:
|
150 |
+
print(f"{len(urls)} links to visit")
|
151 |
+
for url in urls:
|
152 |
+
if verbose:
|
153 |
+
print(f"Visiting {url}...")
|
154 |
+
try:
|
155 |
+
kb_url = from_url_to_kb(url, model, tokenizer)
|
156 |
+
kb.merge_with_kb(kb_url)
|
157 |
+
except ArticleException:
|
158 |
+
if verbose:
|
159 |
+
print(f" Couldn't download article at url {url}")
|
160 |
+
return kb
|
161 |
+
|
162 |
+
def save_network_html(kb, filename="network.html"):
|
163 |
+
# create network
|
164 |
+
net = Network(directed=True, width="700px", height="700px")
|
165 |
+
|
166 |
+
# nodes
|
167 |
+
color_entity = "#00FF00"
|
168 |
+
for e in kb.entities:
|
169 |
+
net.add_node(e, shape="circle", color=color_entity)
|
170 |
+
|
171 |
+
# edges
|
172 |
+
for r in kb.relations:
|
173 |
+
net.add_edge(r["head"], r["tail"],
|
174 |
+
title=r["type"], label=r["type"])
|
175 |
+
|
176 |
+
# save network
|
177 |
+
net.repulsion(
|
178 |
+
node_distance=200,
|
179 |
+
central_gravity=0.2,
|
180 |
+
spring_length=200,
|
181 |
+
spring_strength=0.05,
|
182 |
+
damping=0.09
|
183 |
+
)
|
184 |
+
net.set_edge_smooth('dynamic')
|
185 |
+
net.show_buttons(filter_=['physics'])
|
186 |
+
net.show(filename)
|
187 |
+
|
188 |
+
def save_kb(kb, filename):
|
189 |
+
with open(filename, "wb") as f:
|
190 |
+
pickle.dump(kb, f)
|
191 |
+
|
192 |
+
class CustomUnpickler(pickle.Unpickler):
|
193 |
+
def find_class(self, module, name):
|
194 |
+
return KB if name == 'KB' else super().find_class(module, name)
|
195 |
+
|
196 |
+
def load_kb(filename):
|
197 |
+
res = None
|
198 |
+
with open(filename, "rb") as f:
|
199 |
+
res = CustomUnpickler(f).load()
|
200 |
+
return res
|
201 |
+
|
202 |
+
|
203 |
+
def process_transcript(src, dist):
|
204 |
+
with open(src, 'r') as src:
|
205 |
+
html = bs4.BeautifulSoup(src.read())
|
206 |
+
transcript = html.findChildren('div', {'class': 'transcript-line'})
|
207 |
+
with open(dist, 'w') as dist:
|
208 |
+
transcript_texts = map(lambda x: x.find('span', {'class': 'transcript-text'}).text, transcript)
|
209 |
+
transcript_texts = map(lambda text: re.sub(r'\s(?=\s)','',re.sub(r'\s',' ', text)) , transcript_texts)
|
210 |
+
text = ' '.join(transcript_texts)
|
211 |
+
dist.write(text)
|