<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[jobpal has been acquired by SmartRecruiters! - Medium]]></title>
        <description><![CDATA[This is a match made in heaven for unparalleled hiring efficiency. The industry’s most advanced conversational AI now embedded onto the world’s leading talent acquisition suite. To learn more about what this means for the jobpal community, please visit www.smartrecruiters.com - Medium]]></description>
        <link>https://medium.com/jobpal-dev?source=rss----2cca75d51128---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>jobpal has been acquired by SmartRecruiters! - Medium</title>
            <link>https://medium.com/jobpal-dev?source=rss----2cca75d51128---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:27:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/jobpal-dev" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Measure and Improve Automatic FAQ Answers]]></title>
            <link>https://medium.com/jobpal-dev/how-to-measure-and-improve-automatic-faq-answers-90f97cbdcc3?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/90f97cbdcc3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Kit Kuksenok]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 14:20:23 GMT</pubDate>
            <atom:updated>2020-09-22T09:14:10.562Z</atom:updated>
            <content:encoded><![CDATA[<p>When we start with a new recruitment chatbot project that includes the FAQ automation feature, we use a Starter Set of questions, which are then enriched with FAQS relevant for the client before go-live. After go-live, the system is put to the test with real usage, and <a href="https://medium.com/jobpal-dev/how-we-help-your-chatbot-learn-over-time-2f0ac72d0d6c">improves over time with training</a>.</p><p>When I say “Starter Set,” I mean something like sourdough starter: it may not look like the end goal, but it is essential for success. In a good automated FAQ system, robust algorithms are crucial; however, the dataset, especially the dataset that is often (in the world of chatbots) developed before go-live and with limited exposure to real data, can have a big influence. What the chatbot knows and doesn’t know on Day 1 already shapes how candidates interact with it, and influences its learning over time. Fortunately, we have experience with many multi-year live projects, which allows us to find <a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">consistent trends in FAQ topics relevant to candidates</a>. These trends have guided the development of the Starter Set v1.0 in 2018, and its revision this summer.</p><blockquote>How can the chatbot know more from Day 1?</blockquote><p>How were we able to substantially improve our Starter Set? We used a combination of automation and manual review, to grow our initial v1.0 set into from ~1K questions over 47 to ~3–4K questions (in German and English, respectively) over 68 categories. The new, v2.0 set reflects patterns in <strong>130,000 questions asked by real candidates</strong> in multiple live projects over a year, and has been thoroughly anonymized. In this post, I’ll answer:</p><ol><li>What is the difference between accuracy and automation, and why does it matter?</li><li>How do these measures help guide the iterative process of creating a good, clean starting dataset for an FAQ chatbot?</li><li>When we went from 47 categories to 68, we both added and removed categories; how did we decide what to change, and what was the role of automation and manual review in this process?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVtvmm0IHezbx9ilkvlGAg.png" /><figcaption>Figure 1: Summary of improvement in Starter Set v2.0, compared to v1.0. Automation and Accuracy axes have been truncated for readability; all performance numbers are based on multiple trials, and on test data not used during set development. Details of the accuracy measurement method are <a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">described in a previous publication</a>.</figcaption></figure><p>Crucial to this human-machine collaborative data development process is how FAQ answer performance is <strong>measured</strong>.<strong> </strong>We use two measures: <strong>automation</strong> and <strong>accuracy</strong>, which are related, but distinct. When it comes to an FAQ chatbot in recruitment, not every incoming question is a frequently-asked question; to the key insight is to recognise that not everything should be automated, and to measure not only the capacity to automate as much as possible as well as possible, but also the capacity to correctly decline to answer something that is outside of the FAQ dataset. We developed a measure of accuracy, nex-cv (or: <strong>c</strong>ross-<strong>v</strong>alidation with <strong>ne</strong>gative <strong>ex</strong>amples) that is especially useful, and is <a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">described in a previous publication</a>.</p><p>However, when it comes to the Starter Set, it is not the only important measure for the Starter Set. It is an internal estimate of accuracy, and v1.0 already had a relative high accuracy, compared to typical, live FAQ sets — in part because more categories makes high data quality difficult to maintain. Therefore, we also use automated response as the main measure of success: the goal was to improve the coverage of the Starter Set. In other words, how can the chatbot know more from Day 1?</p><p><strong>What is the difference between accuracy and automation, and why does it matter?</strong> In the example performance in Figure 2 below, automation would refer to the part of each pie that isn’t “No Response” / “Not FAQ.” Meanwhile, accuracy is something independent from the pie chart: it is a comparison to the ground truth, and <em>includes</em> the case where the ground truth label might indicate that no automated response is the best response. In the case of the Starter Set, a high accuracy is a vital, difficult pre-requisite; but increasing<strong> </strong>automation will help us expand the chatbot’s knowledge prior to go-live.</p><blockquote><strong>Ground truth:</strong> given a question, the recruiters’ judgment of what the right answer category is — as opposed to an automated guess.</blockquote><p>With Starter Set v2.0, we see that the top 20 topics in each language cover nearly three quarters of the questions in the test data (Fig 2). At a high level, these topics are similar to <a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">the main topics in v1.0</a>: details of the application process, and questions about qualifications and benefits. The differences are subtle, but important.</p><blockquote><strong>During development, we aimed to </strong>improve coherence: split categories which contain questions that often end up in different categories in practice.</blockquote><p>For example, between v1.0 and v2.0, one category that used to be about the <strong>company language</strong> (e.g, English or German) was split into two: (1) about the company language, and (2) about the language acceptable in the application. This split allows each individual category to perform better; and because <em>both</em> of the language categories are part of the top 20, it has a surprisingly big impact on the capacity of the dataset as a whole to handle the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaTmTaxkh7N8fb0z6ctIFA.png" /><figcaption>Summary of responses to the test data, using the v2.0 set. In this case, the “No Response” section means no response was found; “Not FAQ” was excluded because it <a href="https://medium.com/jobpal-dev/how-we-help-your-chatbot-learn-over-time-2f0ac72d0d6c">fell into a different feature, like small talk</a>. The rest cover topics that, at a high level, stay very similar to <a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">the main topics in v1.0</a>. Although the Top 20 topics cover a large portion of the data, the overall high performance would not be possible without the other 48 topics that cover the “long tail” — shown here in the “All Others” section.</figcaption></figure><p>So, <strong>how do these measures help guide the iterative process of creating a good, clean starting dataset for an FAQ chatbot?</strong></p><p>We had a total of 130K questions, over 2 languages, and in the very beginning we split these into a <em>test</em> set and a <em>development</em> set. The test set for EN was 14K, and for DE 30K; this test set<strong> </strong><em>was not used at all</em><strong> </strong>until the end. In any data-driven project where you are experimenting with the structure of data or the algorithm, it is essential to leave out a test set. All the numbers reported (in Figures 1 and 2) reflect the results on v2.0 sets after they were completed. This allowed testing with <em>unseen</em> data.</p><p>The <em>development</em> set, on the other hand, was used extensively and repeatedly for deciding which categories stay in the Starter Set, and which do not. For<strong> </strong>v1.0, this process was based on automated unsupervised clustering and manual review, but in 2.0 it was significantly more data-driven, and started with v1.0. Each language had 8–10 distinct iterations, at every round adding and removing categories.</p><p><strong>How did we decide what to change, and what was the role of automation and manual review in this process? </strong>Each iteration went like this:</p><ol><li><strong>Grow</strong> the dataset, but automatically accepting very confident guesses</li><li><strong>Automatically suggest changes </strong>in categories to (1) improve coherence: split categories which contain questions that often end up in different categories in practice and (2) reduce unrealistic overestimation: remove or reduce categories that appear more in the training data than in real, incoming questions.</li><li>Manually <strong>review</strong> newly-added questions, including <strong>anonymizing</strong> them, and the suggested changes. Especially in the first iterations, the suggestion list is very long, so these are prioritized by performance at the level of each category (F1 score, a common measure)</li><li>Check <strong>measures of success</strong>: <a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">accuracy (nex-cv)</a> and auto-response — still using a test set from <em>within</em> the development set, and only use the held-out test sample at the end.</li></ol><p>This process was repeated until it was no longer possible to grow: for example, at one point, the EN v2.0 dataset had nearly 10K questions, but through anonymization and review, this was reduced to about 3K, with the same high accuracy and automation. The role of the automation is to greatly speed up the manual review; however, <strong>manual review is crucial</strong> because:</p><ol><li>All data must be fully anonymous, if the Starter Set is to be used for new projects. This means that individual questions cannot contain any non-anonymous data, but also that topics that are highly specific to particular live projects should be excluded.</li><li>The categories and topics must make sense, and match between the different languages: although this process takes place over each language individually at first, it is important that there is coherence between localized version of the dataset.</li></ol><p>Over the last several years, we have considered many aspects of the human element of <a href="https://medium.com/jobpal-dev/how-we-help-your-chatbot-learn-over-time-2f0ac72d0d6c">chatbot learning</a> and <a href="https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc">data quality maintenance</a>, and the development of the Starter Set v2.0 was no exception: although guided by optimising accuracy and automation, it was ultimately a collaboration between the development and implementation team. This collaboration enabled the data from real needs of job-seekers and candidates to be contextualized and understood throughout the process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90f97cbdcc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/how-to-measure-and-improve-automatic-faq-answers-90f97cbdcc3">How to Measure and Improve Automatic FAQ Answers</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how browsers work by creating one]]></title>
            <link>https://medium.com/jobpal-dev/understanding-how-browsers-work-by-creating-one-9aa63a32851e?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/9aa63a32851e</guid>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[tutotial]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yujie Wang]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 08:21:57 GMT</pubDate>
            <atom:updated>2020-08-28T08:23:12.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT0pTtO-BLCqwSay1DwjVw.png" /></figure><p>In this article, I will demonstrate how browsers work by creating a simple mini-browser. This toy example can show the basic rendering principles. After all, learning by doing is always effective, so let’s start the journey by building from scratch a browser that supports HTTP requests, HTML/CSS parsing, and flexbox layout. If you want to view the complete code, please refer to this <a href="https://github.com/BeijiYang/mini-browser">repository</a>.</p><h3>A browser’s basic work process</h3><p>To display a page, the browser takes the following steps:</p><ol><li>Requesting the page from the server using HTTP or HTTPS protocol</li><li>Parsing the HTML to build a DOM tree</li><li>Parsing the CSS to build a CSSOM tree</li><li>Combine the DOM and CSSOM into a render tree</li><li>Rendering the elements according to the CSS properties to get the bitmaps in memory</li><li>Compositing bitmap for better performance (optional)</li><li>Painting to display the content on the screen</li></ol><p>The contents can be displayed on the screen as soon as they are individually ready, because the rendering engine will not wait until all HTML is parsed before starting to build and layout the DOM tree. In this way, the contents can be displayed on the screen gradually as soon as possible.</p><p>In our mini-browser project, we follow the steps below to implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ja34YXnWUZF40kwNx5adA.png" /></figure><pre>.<br>├── client<br>│   ├── index.js  (step one)<br>│   ├── parser.js (step two and three)<br>│   ├── layout.js (step four)<br>│   ├── render.js (step five)<br>│   ├── package-lock.json<br>│   ├── package.json<br>│   └── viewport.jpg (the final result)<br>└── server<br>    ├── package-lock.json<br>    ├── package.json<br>    └── server.js</pre><h3>Step one: network request</h3><p>Let’s start with this basic directory structure:</p><pre>.<br>├── client<br>│ └── index.js<br>└── server<br> └── server.js</pre><h4>Set up a server</h4><p>First of all, let’s start a simple HTTP server which can send back a simple sentence “ Hello World\n”.</p><p>./server/server.js</p><pre>const http = require(&quot;http&quot;);</pre><pre>http.createServer((request, response) =&gt; {<br>  let body = [];</pre><pre>  request.on(&#39;error&#39;, error =&gt; {<br>    console.log(error);<br>  })<br>    .on(&#39;data&#39;, chunk =&gt; {<br>      body.push(chunk.toString());<br>      console.log(body)<br>    })<br>    .on(&#39;end&#39;, () =&gt; {<br>      body = body.join(&#39;&#39;);<br>      response.writeHead(200, { &#39;Content-Type&#39;: &#39;text/html&#39; });<br>      response.end(&#39; Hello World\n&#39;);<br>    });<br>}).listen(8080);</pre><pre>console.log(&#39;The server is running!&#39;);</pre><p>After installing the ‘http’ library and run the index.js file, the server is running.</p><pre>npm install http<br>node server.js</pre><p>I would recommend using the <a href="https://www.npmjs.com/package/nodemon">node monitor</a>, so you don’t have to restart the server by hand every time you change something.</p><p>nodemon server.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*56sBdbwXEAUGHCH6MG8bAA.png" /></figure><h4>Construct and send an HTTP request</h4><p>To send an HTTP request, we need to</p><ul><li>specify the host for IP</li><li>specify the port for TCP</li><li>specify the method, path, headers and body for HTTP</li></ul><p>We put them in an IIFE (Immediately Invoked Function Expression) like this:</p><p>./client/index.js</p><pre>void async function () {<br>  const request = new Request({<br>    host: &#39;127.0.0.1&#39;,<br>    port: 8080,<br>    method: &#39;POST&#39;,<br>    path: &#39;/&#39;,<br>    headers: {<br>      [&#39;X-Jobpal&#39;]: &#39;chatbots&#39;,<br>    },<br>    body: {<br>      name: &#39;Jobpal&#39;,<br>    }<br>  });</pre><pre>  const response = await request.send();<br>  console.log(response);<br>}()</pre><p>According to these requirements, we can implement the request class as follows.</p><p>./client/index.js</p><pre>const net = require(&#39;net&#39;);</pre><pre>class Request {<br>  constructor({<br>    method,<br>    host,<br>    port,<br>    path,<br>    headers,<br>    body<br>  }) {<br>    this.host = host;<br>    this.port = port || 80;<br>    this.method = method || &#39;GET&#39;;<br>    this.path = path || &#39;/&#39;;<br>    this.headers = headers || {};<br>    this.body = body || {};</pre><pre>    if (!this.headers[&#39;Content-Type&#39;]) {<br>      this.headers[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;;<br>    }<br>    // encode the http body.<br>    if (this.headers[&#39;Content-Type&#39;] === &#39;application/json&#39;) {<br>      this.bodyText = JSON.stringify(this.body);<br>    } else if (this.headers[&#39;Content-Type&#39;] === &#39;application/x-www-form-urlencoded&#39;) {<br>      this.bodyText = Object.keys(this.body).map(<br>        key =&gt; `${key}=${encodeURIComponent(this.body[key])}`<br>      ).join(&#39;&amp;&#39;);<br>    }</pre><pre>    this.headers[&quot;Content-Length&quot;] = this.bodyText.length;<br>  }<br></pre><pre>  // The parameter is a TCP connection.<br>  send(connection) {<br>    return new Promise((resolve, reject) =&gt; {<br>      if (connection) {<br>        connection.write(this.toString());<br>      } else {<br>        // create a TCP connection<br>        connection = net.createConnection(<br>          { host: this.host, port: this.port },<br>          () =&gt; connection.write(this.toString())<br>        );<br>      }</pre><pre>      connection.on(&#39;data&#39;, data =&gt; {<br>        console.log(data.toString());<br>        console.log(JSON.stringify(data.toString()));<br>      });</pre><pre>      connection.on(&#39;error&#39;, error =&gt; {<br>        console.log(error);<br>        reject(error);<br>        connection.end();<br>      })<br>    })<br>  }</pre><pre>  toString() {<br>    // the HTTP request<br>    return `${this.method} ${this.path} HTTP/1.1\r<br>${Object.keys(this.headers).map(key =&gt; `${key}: ${this.headers[key]}`).join(&#39;\r\n&#39;)}\r<br>\r<br>${this.bodyText}`;<br>  }<br>}</pre><p>In the construction function, we save the parameters and set the default values. When dealing with headers, pay attention to content-type. It is required; otherwise, the body can not be parsed correctly, because different formats require different parsing methods.</p><p>These are the four most used format:</p><ul><li>application/json</li><li>application/x-www-form-urlencoded (when submitting form)</li><li>multipart/form-data (when uploading files)</li><li>text/xml</li></ul><p>In the project, we set the default value as application/x-www-form-urlencoded. In this format, the submitted data will be encoded like key1=value1&amp;key2=value2.</p><p>In toString() method, the HTTP request is build. It is composed of a request line, request head, and request body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*TswijNAbg8_Y50jwxVJ6pg.png" /></figure><p>Then, in the send() method, we send this request and print the response data when success.</p><p>Don’t forget to install the ‘net’ library, we need it to create a TCP connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*8s5fFeo_jMUt5BKSzxeMLg.png" /></figure><p>As we can see, the structure of response data conforms to the above figure.</p><p>Maybe you have noticed that the response body is different from what we sent on the server-side.</p><ul><li>what we sent: ‘ Hello World\n’</li><li>what we get: ‘d\r\n Hello World\n\r\n0\r\n\r\n’</li></ul><p>The reason is the Transfer-Encoding: chunked in the response headers.</p><p>As described <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding">here</a>:</p><blockquote><em>chunked</em></blockquote><blockquote><em>Data is sent in a series of chunks. The Content-Length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by </em>\r\n<em> and then the chunk itself, followed by another </em>\r\n<em>. The terminating chunk is a regular chunk, with the exception that its length is zero. It is followed by the trailer, which consists of a (possibly empty) sequence of entity header fields.</em></blockquote><p>So in the first chunk, d is a hexadecimal number, indicating that there are 13 characters, which are ‘HelloWorld’, two spaces, and a \n. The second chunk, the empty one, means the body part is over.</p><p>We have successfully got the response data. Next, let’s parse it.</p><h4>Parse HTTP response</h4><p><strong>Parse response line and response head</strong></p><p>As you can see, the response is such a string:</p><ul><li>the request line and the request header are separated by \r\n</li><li>there are two \r\n between the last request header and the request body</li></ul><p>HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nDate: Sun, 02 Aug 2020 17:05:31 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\nd\r\n Hello World\n\r\n0\r\n\r\n</p><p>We can use a state machine to parse this string. The states can be designed according to the format of the response, like the code below.</p><p>In the index.js, we add the ResponseParser class.</p><p>./client/index.js</p><pre>class ResponseParser {<br>  constructor() {<br>    this.WAITING_STATUS_LINE = 0;<br>    this.WAITING_STATUS_LINE_END = 1;</pre><pre>    this.WAITING_HEADER_NAME = 2;<br>    this.WAITING_HEADER_SPACE = 3;<br>    this.WAITING_HEADER_VALUE = 4;<br>    this.WAITING_HEADER_LINE_END = 5;<br>    this.WAITING_HEADER_BLOCK_END = 6;</pre><pre>    this.WAITING_BODY = 7;</pre><pre>    // initial state<br>    this.current = this.WAITING_STATUS_LINE;</pre><pre>    this.statusLine = &#39;&#39;;<br>    this.headers = {};<br>    this.headerName = &#39;&#39;;<br>    this.headerValue = &#39;&#39;;<br>    this.bodyParser = null;<br>  }<br>  get isFinished() { }</pre><pre>  get response() { }</pre><pre>  receive(string) {<br>    for (const char of string) {<br>      this.receiveChar(char);<br>    }<br>    console.log(this.statusLine, &#39;\n&#39;, this.headers)<br>  }<br>  <br>  // a state machine<br>  receiveChar(char) {<br>    switch (this.current) {<br>      case this.WAITING_STATUS_LINE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_STATUS_LINE_END;<br>        } else {<br>          this.statusLine += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_STATUS_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_HEADER_NAME;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_NAME:<br>        if (char === &#39;:&#39;) {<br>          this.current = this.WAITING_HEADER_SPACE;<br>        } else if (char === &#39;\r&#39;) {<br>          // no key-value pairs at all or the end of k-v paris (no more)<br>          this.current = this.WAITING_HEADER_BLOCK_END;<br>        } else {<br>          this.headerName += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_SPACE:<br>        if (char === &#39; &#39;) {<br>          this.current = this.WAITING_HEADER_VALUE;<br>        }<br>        break;<br>      case this.WAITING_HEADER_VALUE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_HEADER_LINE_END;<br>        } else {<br>          this.headerValue += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_HEADER_NAME;<br>          this.headers = {<br>            ...this.headers,<br>            [this.headerName]: this.headerValue<br>          }<br>          this.headerName = &#39;&#39;;<br>          this.headerValue = &#39;&#39;;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_BLOCK_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_BODY;<br>        }<br>        break;</pre><pre>      case this.WAITING_BODY:<br>        console.log(JSON.stringify(char));<br>        break;</pre><pre>      default:<br>        break;<br>    }<br>  }<br>}</pre><p>Then, in the send() method of the Request class, we pass the data to the parser.</p><pre>send(connection) {<br>    return new Promise((resolve, reject) =&gt; {<br>      const parser = new ResponseParser;</pre><pre>      if (connection) {<br>        connection.write(this.toString());<br>      } else {<br>        // create a TCP connection<br>        connection = net.createConnection(<br>          { host: this.host, port: this.port },<br>          () =&gt; connection.write(this.toString())<br>        );<br>      }</pre><pre>      connection.on(&#39;data&#39;, data =&gt; {<br>        console.log(data.toString());<br>        console.log(JSON.stringify(data.toString()));</pre><pre>        // receive the data and pass it to the parser<br>        parser.receive(data.toString());<br>        if (parser.isFinished) {<br>          resolve(parser.response);<br>          connection.end();<br>        }<br>      });</pre><pre>      connection.on(&#39;error&#39;, error =&gt; {<br>        console.log(error);<br>        reject(error);<br>        connection.end();<br>      })<br>    })<br>  }</pre><p>Executing the file, we can see that the response line and response headers have been parsed successfully, and the content of the response body has been printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Vp3RpNv7cSLtDkaY2E8JPA.png" /></figure><p>Different types of response bodies require different parsing methods. Next, we only take chunked as an example.</p><p><strong>Parse response body</strong></p><p>In the newly added ChunkedBodyParser class, we also use a state machine to parse the response body.</p><p>The hexadecimal number and the content are separated by \r\n, so we design the states like this.</p><p>./client/index.js</p><pre>class ChunkedBodyParser {<br>  constructor() {<br>    this.WAITING_LENGTH = 0;<br>    this.WAITING_LENGTH_LINE_END = 1;</pre><pre>    this.READING_CHUNK = 2;<br>    this.WAITING_BLANK_LINE = 3;<br>    this.WAITING_BLANK_LINE_END = 4;</pre><pre>    this.current = this.WAITING_LENGTH;</pre><pre>    this.content = [];<br>    this.length = 0;<br>    this.isFinished = false;<br>  }</pre><pre>receiveChar(char) {<br>    switch (this.current) {<br>      case this.WAITING_LENGTH:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_LENGTH_LINE_END;<br>          if (this.length === 0) {<br>            this.isFinished = true;<br>          }<br>        } else {<br>          // operation of hexadecimal numbers, for example, 2AF5, 2 =&gt; A =&gt; F =&gt; 5<br>          this.length *= 16;<br>          this.length += parseInt(char, 16);<br>        }<br>        break;</pre><pre>      case this.WAITING_LENGTH_LINE_END:<br>        if (char === &#39;\n&#39; &amp;&amp; !this.isFinished) {<br>          this.current = this.READING_CHUNK;<br>        }<br>        break;</pre><pre>      case this.READING_CHUNK:<br>        this.content.push(char);<br>        this.length -= 1;<br>        if (this.length === 0) {<br>          this.current = this.WAITING_BLANK_LINE;<br>        }<br>        break;</pre><pre>      case this.WAITING_BLANK_LINE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_BLANK_LINE_END;<br>        }<br>        break;</pre><pre>      case this.WAITING_BLANK_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_LENGTH;<br>        }<br>        break;</pre><pre>      default:<br>        break;<br>    }<br>  }<br>}</pre><p>Then, we use the parser in the receiveChar() method of the ResponseParser class.</p><pre>receiveChar(char) {<br>  ...<br>  case this.WAITING_HEADER_NAME:<br>        if (char === &#39;:&#39;) {<br>          this.current = this.WAITING_HEADER_SPACE;<br>        } else if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_HEADER_BLOCK_END;<br>          if (this.headers[&#39;Transfer-Encoding&#39;] === &#39;chunked&#39;) {<br>            this.bodyParser = new ChunkedBodyParser();<br>          }<br>        } else {<br>          this.headerName += char;<br>        }<br>        break;<br>  ...<br>  case this.WAITING_BODY:<br>        this.bodyParser.receiveChar(char);<br>        break;<br>  ...<br>}</pre><p>At this point, the response line, response header, and response body are all parsed, we can complete the isFinished() and response() methods in ResponseParser class.</p><pre>get isFinished() {<br>  return this.bodyParser &amp;&amp; this.bodyParser.isFinished;<br>}<br></pre><pre>get response() {<br>  this.statusLine.match(/HTTP\/1.1 ([0-9]+) ([\s\S]+)/);<br>  return {<br>    statusCode: RegExp.$1,<br>    statusText: RegExp.$2,<br>    headers: this.headers,<br>    body: this.bodyParser.content.join(&#39;&#39;)<br>  }<br>}</pre><p>This is the printed result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*hdvMe3IYQFeCzkcBdLDS0A.png" /></figure><p>Let’s send HTML from the server. After saving the changes, the node monitor should automatically restart the server. Requesting again from the client-side, the response is printed out.</p><p>./server/server.js</p><pre>const http = require(&quot;http&quot;);</pre><pre>http.createServer((request, response) =&gt; {<br>  let body = [];</pre><pre>  request.on(&#39;error&#39;, error =&gt; {<br>    console.log(error);<br>  })<br>    .on(&#39;data&#39;, chunk =&gt; {<br>      body.push(chunk.toString());<br>      console.log(body)<br>    })<br>    .on(&#39;end&#39;, () =&gt; {<br>      body = body.join(&#39;&#39;);<br>      response.writeHead(200, { &#39;Content-Type&#39;: &#39;text/html&#39; });<br>      response.end(<br>        `&lt;html maaa=a &gt;<br>    &lt;head&gt;<br>          &lt;style&gt;<br>    body div #myid{<br>      width:100px;<br>      background-color: #ff5000;<br>    }<br>    body div img{<br>      width:30px;<br>      background-color: #ff1111;<br>    }<br>      &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>      &lt;div&gt;<br>          &lt;img id=&quot;myid&quot;/&gt;<br>          &lt;img /&gt;<br>      &lt;/div&gt;<br>    &lt;/body&gt;<br>    &lt;/html&gt;`);<br>    });<br>}).listen(8080);</pre><pre>console.log(&#39;The server is running!&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*_AOzYDJnXjEE0FxGZMy9hQ.png" /></figure><p>So far, we have successfully received the HTML from the network request.</p><p>Now, we can try to parse HTML to get a DOM tree.</p><h3>Step two: HTML parsing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*aY3u_N43jh2D2ZII7eNvZQ.png" /></figure><h4>Tokenization (lexical analysis)</h4><p>A token represents the smallest meaningful unit in the compilation principle. In terms of HTML, 90% of the token that we need for daily development is only about startTag, attributes, endTag, comments, and CDATA nodes.</p><p>Take &lt;p class=&quot;a&quot;&gt;text&lt;/p&gt; as an example, split it to the smallest meaningful units, we can get:</p><ul><li>&lt;p the start of an opening tag</li><li>class=&quot;a&quot; attribute</li><li>&gt; the end of an opening tag</li><li>text</li><li>closing tag</li></ul><p>Similar to the previous, we also use a state machine for parsing. Fortunately, the state machine has been well designed in the <a href="https://html.spec.whatwg.org/multipage/parsing.html#tokenization">HTML standard</a>, what we need to do is just translate it to JavaScript.</p><p>There are more than 80 states specified, but we don’t need so many states to parse our simple HTML. So in our sample code, some simplifications are made.</p><h4>Setup an empty state machine</h4><p>We design the state as a function so that the state transition part is very simple.</p><pre>let state = data; // the initial state is called &#39;data&#39; in the HTML standard</pre><pre>for (const char of html) {<br>  state = state(char);<br>}</pre><p>Add a new file “parser.js”.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;); // end of file token</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    console.log(JSON.stringify(char), state.name)<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>}</pre><pre>// There are three kinds of HTML tags: opening tag &lt;div&gt;, closing tag &lt;/div&gt;, self-closing tag &lt;div/&gt;</pre><pre>// the initial state is called &#39;data&#39; in the HTML standard<br>function data(char) {<br>  if (char === &#39;&lt;&#39;) {<br>    return tagOpen;<br>  } else if (char === EOF) {<br>    return;<br>  } else {<br>    // text node<br>    return data;<br>  }<br>}</pre><pre>// when the state is tagOpen, we don&#39;t know what kind of tag it is yet. like &#39;&lt;&#39;<br>function tagOpen(char) {<br>  if (char === &#39;/&#39;) {<br>    // &#39;&lt;/&#39; ,e.g. &#39;&lt;/div&gt;&#39;<br>    return endTagOpen;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    // the char is a letter, the tag could be a opening tag or a self-closing tag. e.g. &#39;&lt;d&#39;  =&gt; &#39;&lt;div&gt;&#39; or &#39;&lt;/div&gt;&#39;<br>    return tagName(char); // reconsume the char<br>  } else {<br>    // Parse error<br>    return;<br>  }<br>}<br><br>function endTagOpen(char) {<br>  if (char.match(/^[a-zA-Z]$/)) {<br>    return tagName(char);<br>  } else if (char === &#39;&gt;&#39;) {<br>    // error  /&gt;  It&#39;s html, not JSX<br>    // Parse error<br>  } else if (char === EOF) {<br>    // Parse error<br>  } else {<br>    // Parse error<br>  }<br>}</pre><pre>function tagName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    // tagname start from a &#39;&lt;&#39;, end with a &#39; &#39; e.g. &#39;&lt;div prop&#39;<br>    return beforeAttributeName;<br>  } else if (char === &#39;/&#39;) {<br>    return selfClosingStartTag;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    return tagName;<br>  } else if (char === &#39;&gt;&#39;) {<br>    // the current tag is over, go back to the initial state to parse the next tag<br>    return data;<br>  } else {<br>    return tagName;<br>  }<br>}</pre><pre>// Only &#39;&gt;&#39; is valid after &#39;&lt;div/&#39;<br>function selfClosingStartTag(char) {<br>  if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {</pre><pre>  }<br>}</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // Parse error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) { // end of a pair of attribute, e.g. &quot;&lt;div class=&#39;abc&#39; &quot;<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) { // e.g. &#39;class=&#39;<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}<br></pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue; // e.g. &lt;html attribute=&quot;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue; // e.g. &lt;html attribute=&#39;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char); // e.g. &lt;html attribute=<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) { // the second double quotes<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>// when the attribute part is over, save attribute name and value to the current token<br>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) { // end of unquoted Attribute value<br>    return beforeAttributeName; // to parse a new pair of attribute<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><p>Then, use the new parser in the index.js.</p><p>./client/index.js</p><pre>const parser = require(&#39;./parser&#39;);<br>...</pre><pre>void async function () {<br>  const request = new Request({<br>   ...<br>  });</pre><pre>  const response = await request.send();<br>  const dom = parser.parseHTML(response.body);<br>  console.log(JSON.stringify(dom, null, 2));<br>}()</pre><p>Run the index.js, now the state machine is running! You can see the correspondence between characters and states at each step in the printed log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*evb6L1qRJ7tBgKoioFkIKw.png" /></figure><p>The dom is undefined because now this state machine is empty, it does nothing. In the next step, let&#39;s add the corresponding logic code in these states to build the DOM tree.</p><h4>Emit tokens</h4><p>The tag types are nothing more than the starting-tag, the closing tag, and the self-closing tag. In the state machine, we emit the tag token when we encounter the end of a tag.</p><p>The emit() function takes the token generated from the state machine. In this step, it does nothing but prints the received token.</p><p>So the parser.js looks like this.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;</pre><pre>function emit(token) {<br>  console.log(token);<br>}</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>}</pre><pre>function data(char) {<br>  if (char === &#39;&lt;&#39;) {<br>    return tagOpen;<br>  } else if (char === EOF) {<br>    emit({ type: &#39;EOF&#39; });<br>    return;<br>  } else {<br>    // emit the text nodes one by one, we can join them later<br>    emit({<br>      type: &#39;text&#39;,<br>      content: char,<br>    });<br>    return data;<br>  }<br>}</pre><pre>function tagOpen(char) {<br>  if (char === &#39;/&#39;) {<br>    return endTagOpen;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken = {<br>      type: &#39;startTag&#39;,<br>      tagName: &#39;&#39;,<br>    }<br>    return tagName(char); // reconsume<br>  } else {<br>    // Parse error<br>    return;<br>  }<br>}<br><br>function endTagOpen(char) {<br>  if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken = {<br>      type: &#39;endTag&#39;,<br>      tagName: &#39;&#39;<br>    }<br>    return tagName(char);<br>  } else if (char === &#39;&gt;&#39;) {<br>    // Parse error<br>  } else if (char === EOF) {<br>    // Parse error<br>  } else {<br>    // Parse error<br>  }<br>}</pre><pre>function tagName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &#39;/&#39;) {<br>    return selfClosingStartTag;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken.tagName += char;<br>    return tagName;<br>  } else if (char === &#39;&gt;&#39;) {<br>    // the current tag is over, go back to the initial state to parse the next tag<br>    emit(currentToken);<br>    return data;<br>  } else {<br>    return tagName;<br>  }<br>}</pre><pre>function selfClosingStartTag(char) {<br>  if (char === &quot;&gt;&quot;) {<br>    currentToken.isSelfClosing = true;<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {</pre><pre>  }<br>}</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // parser error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}</pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char);<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*xFfrgeg5pZCxTXCxA8zeCw.png" /></figure><p>Now, we get these tokens. You might have noticed that the attributes are missing. For example, the token of the img tag with id &quot;myid&quot; is { type: &#39;startTag&#39;, tagName: &#39;img&#39;, isSelfClosing: true }. The id is not included.</p><p>The way of adding attributes is similar to the previous step. Add the currentAttribute variable and complete the logic in the state machine like below.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;<br>let currentAttribute = null;</pre><pre>...</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // parse error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) { </pre><pre>  } else {<br>    return attributeName;<br>  }<br>}<br></pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}</pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char);<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><p>Run the index again, you can find out that now the attributes come back!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*C4fIm3t8uABUNNlp8qH_hw.png" /></figure><p>At this point, we have split the character stream into tokens, and then let’s use these tokens to build a DOM tree.</p><h4>DOM tree construction (syntactic analysis)</h4><p>In real browsers, the HTML nodes inheritance from different subclasses of Node. To simplify our code, we only divide Node into Element and Text.</p><p>For elements, we construct the DOM tree by using a stack to match the tags.</p><p>Specifically, when the emit function receives the token, it starts to build the DOM tree. When it encounters a startTag, it pushes the element into the stack, and when it encounters the matching endTag, it pops the top element out of the stack. Self-closing tags do not need to be pushed into the stack.</p><p>It is worth mentioning that when a tag mismatch occurs, the real browser will do fault-tolerant processing, while we just throw an error here.</p><p>When all tokens are received, the top element (the document element) of the stack is the root node of the DOM tree.</p><p>For Text nodes, we need to merge them when they are adjacent. When it is pushed into the stack, check whether the top node of the stack is a Text node. If so, merge the Text nodes and then add the text nodes to the DOM tree.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;<br>let currentAttribute = null;<br>let currentTextNode = null;</pre><pre>// a stack containing the root node<br>const stack = [{ type: &#39;document&#39;, children: [] }];</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>  // return the DOM tree<br>  return stack[0];<br>}</pre><pre>...</pre><pre>function emit(token) {<br>  let top = stack[stack.length - 1];</pre><pre>  if (token.type === &#39;startTag&#39;) {<br>    // create the element<br>    let element = {<br>      type: &#39;element&#39;,<br>      children: [],<br>      attributes: [],<br>      tagName: token.tagName<br>    }</pre><pre>for (const prop in token) {<br>      if (prop !== &quot;type&quot; &amp;&amp; prop !== &quot;tagName&quot;) {<br>        element.attributes.push({<br>          name: prop,<br>          value: token[prop],<br>        })<br>      }<br>    }<br><br>    top.children.push(element);<br>    // comment out this line to avoid the circular structure error when print the DOM tree<br>    // element.parent = top;</pre><pre>    if (!token.isSelfClosing) {<br>      stack.push(element);<br>    }</pre><pre>    currentTextNode = null;<br>  } else if (token.type === &#39;endTag&#39;) {<br>    if (top.tagName !== token.tagName) {<br>      throw new Error(&#39;Tag does not match&#39;);<br>    } else {<br>      stack.pop();<br>    }<br>    currentTextNode = null;<br>  } else if (token.type === &#39;text&#39;) {<br>    if (currentTextNode === null) {<br>      currentTextNode = {<br>        type: &quot;text&quot;,<br>        content: &quot;&quot;,<br>      }<br>      top.children.push(currentTextNode);<br>    }<br>    currentTextNode.content += token.content;<br>  }<br>}</pre><p>Run the index again, instead of undefined, now we can see a DOM tree here! Under the document node is the html node, below it is the head node and the body node.</p><pre>{<br>  &quot;type&quot;: &quot;document&quot;,<br>  &quot;children&quot;: [<br>    {<br>      &quot;type&quot;: &quot;element&quot;,<br>      &quot;children&quot;: [<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;element&quot;,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n            &quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;element&quot;,<br>              &quot;children&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n      body div #myid{\n        width:100px;\n        background-color: #ff5000;\n      }\n      body div img{\n        width:30px;\n        background-color: #ff1111;\n      }\n        &quot;<br>                }<br>              ],<br>              &quot;attributes&quot;: [],<br>              &quot;tagName&quot;: &quot;style&quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n      &quot;<br>            }<br>          ],<br>          &quot;attributes&quot;: [],<br>          &quot;tagName&quot;: &quot;head&quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;element&quot;,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n        &quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;element&quot;,<br>              &quot;children&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n            &quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;element&quot;,<br>                  &quot;children&quot;: [],<br>                  &quot;attributes&quot;: [<br>                    {<br>                      &quot;name&quot;: &quot;id&quot;,<br>                      &quot;value&quot;: &quot;myid&quot;<br>                    },<br>                    {<br>                      &quot;name&quot;: &quot;isSelfClosing&quot;,<br>                      &quot;value&quot;: true<br>                    }<br>                  ],<br>                  &quot;tagName&quot;: &quot;img&quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n            &quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;element&quot;,<br>                  &quot;children&quot;: [],<br>                  &quot;attributes&quot;: [<br>                    {<br>                      &quot;name&quot;: &quot;isSelfClosing&quot;,<br>                      &quot;value&quot;: true<br>                    }<br>                  ],<br>                  &quot;tagName&quot;: &quot;img&quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n        &quot;<br>                }<br>              ],<br>              &quot;attributes&quot;: [],<br>              &quot;tagName&quot;: &quot;div&quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n      &quot;<br>            }<br>          ],<br>          &quot;attributes&quot;: [],<br>          &quot;tagName&quot;: &quot;body&quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        }<br>      ],<br>      &quot;attributes&quot;: [<br>        {<br>          &quot;name&quot;: &quot;maaa&quot;,<br>          &quot;value&quot;: &quot;a&quot;<br>        }<br>      ],<br>      &quot;tagName&quot;: &quot;html&quot;<br>    }<br>  ]<br>}</pre><p>Look at the DOM tree we have here. The structure is correct, but it is bare, without any decoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsEVaNB9wM-nIJIioWD6uA.jpeg" /></figure><h3>Step three: CSS computing</h3><p>Let’s make it a beautiful Christmas tree with CSS in this step!</p><p>During the CSS computation step, parsed CSS rules are added to the matched DOM elements. Note that CSS computing also occurs during the construction of the DOM tree.</p><p>We need to install the css library which can parse the CSS code into a CSS AST (abstract syntax tree). To simplify, we use the AST to replace the role of CSSOM in our sample project.</p><p>npm install css</p><h4>Gather the CSS rules</h4><p>First, we need to gather all CSS rules together from the CSS AST.</p><p>./client/parser.js</p><pre>const css = require(&quot;css&quot;);<br>...</pre><pre>// to save the CSS rules<br>const rules = []; </pre><pre>// gather all the CSS rules<br>function addCSSRules(text) {<br>  const ast = css.parse(text);<br>  rules.push(...ast.stylesheet.rules);<br>}</pre><p>Then, execute it at the end of the style tag (ignore CSS in other locations).</p><p>So, in the emit() method:</p><pre>...<br>else if (token.type === &#39;endTag&#39;) {<br>  if (top.tagName !== token.tagName) {<br>    throw new Error(&#39;Tag does not match&#39;);<br>  } else {<br>    if (top.tagName === &#39;style&#39;) {<br>      addCSSRules(top.children[0].content); // The children of the top element in the stack are the current element<br>    }<br>    stack.pop();<br>  }<br>  currentTextNode = null;<br>}<br>...</pre><p>If you print the rules, you’ll find that the CSS rules have been collected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ci3djq_UvIwyw1EdyCMYIQ.png" /></figure><h4>Match CSS rules and elements</h4><p>When to do it? Generally speaking, we will try to ensure that all selectors can be judged when startTag is entered. With the later addition of advanced selectors, this rule has been loosened. Due to the limited length of the article, we only use simple selectors in our sample code. So when there is a startTag, it is already possible to determine which CSS rules the element matches.</p><p>In real browsers, there may be style tags in the body that require recalculation of CSS. We ignore this kind of situation.</p><p>Call the computeCSS in the emit function.</p><p>./client/parser.js</p><pre>function emit(token) {<br>  let top = stack[stack.length - 1];</pre><pre>  if (token.type === &#39;startTag&#39;) {<br>    let element = {...}</pre><pre>    for (const prop in token) {<br>      ...<br>    }<br>    // CSS computing happens during the DOM tree construction <br>    computeCSS(element);<br>    <br>    top.children.push(element);<br>    ...</pre><p>In the computeCSS function, in order to match the selector with the corresponding element, we need to get the ancestor element sequence of the current element.</p><p>const elements = stack.slice().reverse();</p><p>All ancestor elements of the current element are stored in the stack. Because the stack is changing, the slice() method is used to save a copy of the current state.</p><p>When we try to determine whether an element matches the selector, we start with the current element, then its parent element, and step by step outward. Take “div #myid” as an example, the div can be any ancestor element, but #myid must be the current element.</p><p>In addition, we need a way to calculate whether the selector matches the element. Also for simplicity, we only deal with the case of descendant selectors composed of simple selectors and spaces, like ‘div #myid’.</p><p>./client/parser.js</p><pre>...</pre><pre>// assuming selector is a simple selector (.class #id tagname)<br>function match(element, selector) {<br>  if (!selector || !element.attributes) return false;</pre><pre>  if (selector.charAt(0) === &#39;#&#39;) { // id selector<br>    const attr = element.attributes.filter(<br>      ({ name }) =&gt; (name === &#39;id&#39;)<br>    )[0];<br>    if (attr &amp;&amp; attr.value === selector.replace(&#39;#&#39;, &#39;&#39;)) {<br>      return true;<br>    }<br>  } else if (selector.charAt(0) === &#39;.&#39;) { // class selector<br>    const attr = element.attributes.filter(<br>      ({ name }) =&gt; (name === &#39;class&#39;)<br>    )[0];<br>    if (attr &amp;&amp; attr.value === selector.replace(&quot;.&quot;, &quot;&quot;)) {<br>      return true;<br>    }<br>  } else { // type selector<br>    if (element.tagName === selector) return true;<br>  }<br>}<br></pre><pre>function computeCSS(element) {<br>  const elements = stack.slice().reverse();</pre><pre>for (const rule of rules) {<br>    const selectors = rule.selectors[0].split(&#39; &#39;).reverse(); //  the structure of the ast and don&#39;t forget to do the reversing<br>    // selectors are like &#39;[ &#39;#myid&#39;, &#39;div&#39;, &#39;body&#39; ]&#39;</pre><pre>    if (!match(element, selectors[0])) continue;</pre><pre>    let matched = false;</pre><pre>let selectorIndex = 1; // elements is parent element or ancestor element, so here we start from 1<br>    for (let elementIndex = 0; elementIndex &lt; elements.length; elementIndex++) {<br>      if (match(elements[elementIndex], selectors[selectorIndex])) {<br>        selectorIndex++;<br>      }<br>    }<br>    if (selectorIndex &gt;= selectors.length) {<br>      // all selectors are matched<br>      matched = true;<br>    }<br>    if (matched) {<br>      console.log(`Selector &quot;${rule.selectors[0]}&quot; has matched element ${JSON.stringify(element)}`)<br>    }<br>  }<br>}</pre><pre>...</pre><p>From the printed result, we can see that the element and the selector have been correctly matched.</p><p>Selector &quot;body div #myid&quot; has matched element {&quot;type&quot;:&quot;element&quot;,&quot;children&quot;:[],&quot;attributes&quot;:[{&quot;name&quot;:&quot;id&quot;,&quot;value&quot;:&quot;myid&quot;},{&quot;name&quot;:&quot;isSelfClosing&quot;,&quot;value&quot;:true}],&quot;tagName&quot;:&quot;img&quot;}</p><p>After the successful match, we should add CSS rules to the corresponding elements.</p><p>This step is very simple. In the computeCSS function, we add a computedStyle property to the element and save the CSS rules into it when matching.</p><pre>function computeCSS(element) {<br>  if (!element.computedStyle) {<br>    element.computedStyle = {};<br>  }</pre><pre>  const elements = stack.slice().reverse();</pre><pre>  for (const rule of rules) {<br>    ...<br>    <br>    if (matched) {<br>      const { computedStyle } = element;<br>      for (const declaration of rule.declarations) {<br>        const { property, value } = declaration;<br>        if (!computedStyle[property]) {<br>          computedStyle[property] = {};<br>        }<br>        computedStyle[property] = value;<br>      }<br>    }<br>  }<br>  console.log(element.computedStyle)<br>}</pre><p>Now the elements have their CSS rules, but it’s not enough yet. Go check these two img elements, you’ll find that they have the same computedstyle property, which is wrong.</p><p>{ width: &#39;30px&#39;, &#39;background-color&#39;: &#39;#ff1111&#39; }</p><p>Why? The reason is the CSS specificity. The rules with higher specificity should always have higher priority. The currently wrong result is because the later low-specificity rules overwrite the previous high-specificity rules.</p><p>To calculate the CSS specificity, we need a quaternion: [inline, id, class/attribute, tagName]（Inline styles have the highest priority, and the rest is number of each type of selectors）.</p><p>For example, for the case[a, b, c, d], the calculation formula is:</p><p>specificity = a * N³ + b * N² + c * N + d</p><p>N is a big number. In the old version of IE, in order to save memory, the value of N is 255, which is not large enough, resulting in a funny bug that 256 classes are equivalent to one id. Of course, any sane developer would not write 256 selectors. Nowadays, most browsers set N as 65536.</p><p>Based on this, we can implement functions for calculating and comparing CSS specificity. Again, this is also a simplified version.</p><pre>function getSpecificity(selector) {<br>  const specificity = [0, 0, 0, 0];<br>  //Similarly, assuming that selector is composed of simple selectors.<br>  const selectors = selector.split(&#39; &#39;);</pre><pre>  for (const item of selectors) {<br>    if (item.charAt(0) === &#39;#&#39;) {<br>      specificity[1] += 1;<br>    } else if (item.charAt(0) === &#39;.&#39;) {<br>      specificity[2] += 1;<br>    } else {<br>      specificity[3] += 1;<br>    }<br>  }<br>  return specificity;<br>}</pre><pre>function compareSpecificity(sp1, sp2) {<br>  if (sp1[0] - sp2[0]) {<br>    return sp1[0] - sp2[0];<br>  }<br>  if (sp1[1] - sp2[1]) {<br>    return sp1[1] - sp2[1];<br>  }<br>  if (sp1[2] - sp2[2]) {<br>    return sp1[2] - sp2[2];<br>  }<br>  return sp1[3] - sp2[3];<br>}</pre><p>In the computeCSS function, when an element matches a selector, instead of simply apply the CSS rules, we need to compare the CSS specificity and use the rules with higher specificity.</p><pre>if (matched) {<br>      const { computedStyle } = element;<br>      const specificity = getSpecificity(rule.selectors[0]);</pre><pre>      for (const declaration of rule.declarations) {<br>        const { property, value } = declaration;<br>        if (!computedStyle[property]) {<br>          computedStyle[property] = {};<br>        }<br>        // computedStyle[property] = value;<br>        // CSS specificity<br>        if (!computedStyle[property].specificity) {<br>          computedStyle[property] = {<br>            value,<br>            specificity,<br>            ...computedStyle[property],<br>          }<br>        } else if (compareSpecificity(computedStyle[property].specificity, specificity) &lt; 0) {<br>          // current CSS selector have higher specificity than the previous, cover the previous rules<br>          computedStyle[property] = {<br>            value,<br>            specificity,<br>            ...computedStyle[property],<br>          }<br>        }<br>      }<br>    }</pre><p>Run it again, as it printed, the img element with ID is correctly displayed as &#39;#ff5000&#39;.</p><p>Now, if you print the DOM tree again, you will see a beautiful Christmas tree with all the CSS decoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBDd0KlFX7qBTURHSSUP-Q.jpeg" /></figure><p>Next, our job is to calculate the position of each element so we can get a DOM tree with position information.</p><h3>Step four: layout</h3><p>In CSS, there are three generations of layout technology:</p><ul><li>normal flow</li><li>flexbox</li><li>grid</li></ul><p>We are going to implement the most popular one: flexbox. If you are not familiar with this technique, please check this <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">link</a>.</p><h4>Main axis and cross axis</h4><p>Before we start, we must first understand the concepts of the main axis and the cross axis. By default, the main axis is horizontal (from left to right) and the cross axis is vertical (from top to bottom). It can also change with our settings. For example, when the value of ‘flex-direction’ is ‘row’, the main axis is horizontal, when the value is ‘column’, the main axis is vertical. Using these concepts can help us reduce a lot of unnecessary if-else code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2H_FOT-eUrGecEIsQc0GQ.png" /></figure><h4>When to do the layout</h4><p>Suppose we already have the layout() function, when should we call it? To calculate the flexbox layout, we need to know all the children elements of the current element. So we should call the layout() function in the ‘endTag’ branch.</p><p>./client/parser.js</p><pre>const css = require(&quot;css&quot;);<br>const layout = require(&quot;./layout.js&quot;);</pre><pre>...</pre><pre>function emit(token) {<br>  ...<br>   else if (token.type === &#39;endTag&#39;) {<br>    if (top.tagName !== token.tagName) {<br>      throw new Error(&#39;Tag does not match&#39;);<br>    } else {<br>      if (top.tagName === &#39;style&#39;) {<br>        addCSSRules(top.children[0].content);<br>      }<br>      // right here!<br>      layout(top);<br>      stack.pop();<br>    }<br>    currentTextNode = null;<br>  }<br>  ...<br>}</pre><h4>Pre-processing</h4><p>In the newly created layout.js file, let&#39;s add a getStyle() function to do some pre-processing work like filtering out unwanted elements and type conversion(string to number).</p><p>./client/layout.js</p><pre>function getStyle(element) {<br>  if (!element.style) element.style = {};</pre><pre>  const { computedStyle, style } = element;</pre><pre>  for (const prop in computedStyle) {<br>    if (style[prop]) continue;<br>    <br>    element.style[prop] = computedStyle[prop].value;</pre><pre>    if (element.style[prop].toString().match(/px$/)) {<br>      element.style[prop] = parseInt(element.style[prop]);<br>    }<br><br>    if (element.style[prop].toString().match(/^[0-9\.]+$/)) {<br>      element.style[prop] = parseInt(element.style[prop]);<br>    }<br>  }<br>  return element.style;<br>}</pre><h4>Set default values</h4><p>Set default values in the layout function.</p><p>./client/layout.js</p><pre>function layout(element) {<br>  if (!element.computedStyle) return;</pre><pre>  const elementStyle = getStyle(element);<br><br>  if (elementStyle.display !== &#39;flex&#39;) return;</pre><pre>  // filter out text nodes<br>  const elementItems = element.children.filter(<br>    el =&gt; el.type === &#39;element&#39;<br>  );</pre><pre>  // to support the order property<br>  elementItems.sort((a, b) =&gt; (a.order || 0) - (b.order || 0));</pre><pre>  const style = elementStyle;</pre><pre>  [&#39;width&#39;, &#39;height&#39;].forEach(size =&gt; {<br>    if (style[size] === &#39;auto&#39; || style[size] === &#39;&#39;) {<br>      style[size] = null;<br>    }<br>  })</pre><pre>  // set default values<br>  if (!style[&#39;flex-direction&#39;] || style[&#39;flex-direction&#39;] === &#39;auto&#39;) {<br>    style[&#39;flex-direction&#39;] = &#39;row&#39;;<br>  }<br>  if (!style[&#39;align-items&#39;] || style[&#39;align-items&#39;] === &#39;auto&#39;) {<br>    style[&#39;align-items&#39;] = &#39;stretch&#39;;<br>  }<br>  if (!style[&#39;justify-content&#39;] || style[&#39;justify-content&#39;] === &#39;auto&#39;) {<br>    style[&#39;justify-content&#39;] = &#39;flex-start&#39;;<br>  }<br>  if (!style[&#39;flex-wrap&#39;] || style[&#39;flex-wrap&#39;] === &#39;auto&#39;) {<br>    style[&#39;flex-wrap&#39;] = &#39;nowrap&#39;;<br>  }<br>  if (!style[&#39;align-content&#39;] || style[&#39;align-content&#39;] === &#39;auto&#39;) {<br>    style[&#39;align-content&#39;] = &#39;stretch&#39;;<br>  }</pre><pre>  let mainSize,<br>    mainStart,<br>    mainEnd,<br>    mainSign,<br>    mainBase,<br>    crossSize,<br>    crossStart,<br>    crossEnd,<br>    crossSign,<br>    crossBase;</pre><pre>  if (style[&#39;flex-direction&#39;] === &#39;row&#39;) {<br>    mainSize = &#39;width&#39;;<br>    mainStart = &#39;left&#39;;<br>    mainEnd = &#39;right&#39;;<br>    mainSign = +1;<br>    mainBase = 0;</pre><pre>    crossSize = &#39;height&#39;;<br>    crossStart = &#39;top&#39;;<br>    crossEnd = &#39;bottom&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;row-reverse&#39;) {<br>    mainSize = &#39;width&#39;;<br>    mainStart = &#39;right&#39;;<br>    mainEnd = &#39;left&#39;;<br>    mainSign = -1;<br>    mainBase = style.width;</pre><pre>    crossSize = &#39;height&#39;;<br>    crossStart = &#39;top&#39;;<br>    crossEnd = &#39;bottom&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;column&#39;) {<br>    mainSize = &#39;height&#39;;<br>    mainStart = &#39;top&#39;;<br>    mainEnd = &#39;bottom&#39;;<br>    mainSign = +1;<br>    mainBase = 0;</pre><pre>    crossSize = &#39;width&#39;;<br>    crossStart = &#39;left&#39;;<br>    crossEnd = &#39;right&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;column-reverse&#39;) {<br>    mainSize = &#39;height&#39;;<br>    mainStart = &#39;bottom&#39;;<br>    mainEnd = &#39;top&#39;;<br>    mainSign = -1;<br>    mainBase = style.height;</pre><pre>    crossSize = &#39;width&#39;;<br>    crossStart = &#39;left&#39;;<br>    crossEnd = &#39;right&#39;;<br>  }</pre><pre>  if (style[&#39;flex-wrap&#39;] === &#39;wrap-reverse&#39;) {<br>    const [crossEnd, crossStart] = [crossStart, crossEnd];<br>    crossSign = -1;<br>  } else {<br>    crossBase = 0;<br>    crossSign = +1;<br>  }</pre><pre>}</pre><h4>Collect elements into flex line</h4><p>Put the elements in one line if there is enough room or no-wrap, otherwise, start a new line.</p><p>There might be a special case: If the parent element does not have a main axis size (like width), the parent element is stretched by the child element. This mode is called the “auto main size”. In this case, the elements are gathered in one line.</p><p>./client/layout.js (continue with the previous code block)</p><pre>  // the special case<br>  let isAutoMainSize = false;<br>  if (!style[mainSize]) {<br>    // auto sizing<br>    elementStyle[mainSize] = 0;<br>    for (let i = 0; i &lt; elementItems.length; i++) {<br>      const itemStyle = getStyle(elementItems[i]);<br>      if (itemStyle[mainSize] !== null || itemStyle[mainSize] !== (void 0)) {<br>        elementStyle[mainSize] = elementStyle[mainSize] + itemStyle[mainSize];<br>      }<br>    }<br>    isAutoMainSize = true;<br>  }<br></pre><pre>  // normal case<br>  let flexLine = [];<br>  const flexLines = [flexLine];</pre><pre>  // mainSpace is the current remaining space, set it to the mainsize of the parent element<br>  let mainSpace = elementStyle[mainSize];<br>  let crossSpace = 0;</pre><pre>  // loop all the flex items<br>  for (let i = 0; i &lt; elementItems.length; i++) {<br>    const item = elementItems[i];<br>    const itemStyle = getStyle(item);<br><br>    if (itemStyle[mainSize] === null) {<br>      itemStyle[mainSize] = 0;<br>    }<br><br>    if (itemStyle.flex) { // one line<br>      flexLine.push(item);<br>    } else if (style[&#39;flex-wrap&#39;] === &#39;nowrap&#39; &amp;&amp; isAutoMainSize) {<br>      mainSpace -= itemStyle[mainSize];<br>      if (itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) {<br>        crossSpace = Math.max(crossSpace, itemStyle[crossSize]);<br>      }<br>      // because of &#39;nowrap&#39;<br>      flexLine.push(item);<br>    } else { // multiple lines<br>      // if the mainsize of the element is larger than it&#39;s parent element, it will be compressed to the same size as the parent element.<br>      if (itemStyle[mainSize] &gt; style[mainSize]) {<br>        itemStyle[mainSize] = style[mainSize];<br>      }<br>      // start a new line<br>      if (mainSpace &lt; itemStyle[mainSize]) {<br>        flexLine.mainSpace = mainSpace;<br>        flexLine.crossSpace = crossSpace;<br> <br>        // create the new line<br>        flexLine = [item];<br>        flexLines.push(flexLine);<br>        // reset these two props<br>        mainSpace = style[mainSize];<br>        crossSpace = 0;<br>      } else {<br>        flexLine.push(item);<br>      }<br><br>      if (itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) {<br>        crossSpace = Math.max(crossSpace, itemStyle[crossSize]);<br>      }<br>      mainSpace -= itemStyle[mainSize];<br>    }<br>  }<br>  flexLine.mainSpace = mainSpace;</pre><h4>Calculate the main axis</h4><p>Find all flex items and assign the remaining space mainspace in the main axis direction to these flex items proportionally. Special case: if the remaining space is a negative number (like in the “no-wrap” mode), set the size of the main axis of all flex items elements to 0, and compress the remaining elements proportionally.</p><p>If there are no flex items, calculate the position of each element according to the value of justify-content.</p><p>./client/layout.js (continue with the previous code block)</p><pre>if (style[&#39;flex-wrap&#39;] === &quot;nowrap&quot; || isAutoMainSize) {<br>    flexLine.crossSpace = (style[crossSize] !== undefined)<br>      ? style[crossSize]<br>      : crossSpace;<br>  } else {<br>    flexLine.crossSpace = crossSpace;<br>  }</pre><pre>if (mainSpace &lt; 0) {<br>    // overflow (happens only if container is single line), scale every item <br>    // the special case, proportional compression<br>    let scale = style[mainSize] / (style[mainSize] - mainSpace);<br>    let currentMain = mainBase;</pre><pre>for (let i = 0; i &lt; elementItems.length; i++) {<br>      const itemStyle = getStyle(elementItems[i]);<br>      if (itemStyle.flex) {<br>        // flex elements do not participate in proportional compression<br>        itemStyle[mainSize] = 0;<br>      }</pre><pre>      itemStyle[mainSize] = itemStyle[mainSize] * scale;</pre><pre>      // if the flex direction is row，this part is to calculate left and right after compression<br>      itemStyle[mainStart] = currentMain;<br>      itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>      currentMain = itemStyle[mainEnd];<br>    }<br>  } else {<br>    // multiple lines<br>    // process each flex line<br>    flexLines.forEach(flexLine =&gt; {<br>      const mainSpace = flexLine.mainSpace;<br>      let itemStyle;<br>      let flexTotal = 0;<br>      for (let i = 0; i &lt; flexLine.length; i++) {<br>        itemStyle = getStyle(flexLine[i]);<br>        // find the flex items to get the value of flexTotal<br>        if ((itemStyle.flex !== null) &amp;&amp; (itemStyle.flex !== (void 0))) {<br>          flexTotal += itemStyle.flex;<br>          continue;<br>        }<br>      }</pre><pre>      // if flex elements exist, distribute mianSpace evenly to each flex element<br>      if (flexTotal &gt; 0) {<br>        let currentMain = mainBase;<br>        for (let i = 0; i &lt; flexLine.length; i++) {<br>          itemStyle = getStyle(flexLine[i]);<br>  <br>          if (itemStyle.flex) {<br>            itemStyle[mainSize] = (mainSpace / flexTotal) * itemStyle.flex;<br>          }          itemStyle[mainStart] = currentMain;<br>          itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>          currentMain = itemStyle[mainEnd];<br>        }<br>      } else {<br>        // if there is no flex element, the remaining space in the main axis direction is allocated according to the rules of justifyContent<br>        let currentMain, gap;<br>        if (style[&#39;justify-content&#39;] === &#39;flex-start&#39;) {<br>          currentMain = mainBase;<br>          gap = 0; // there is no space between each element<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;flex-end&#39;) {<br>          currentMain = mainBase + mainSpace * mainSign;<br>          gap = 0;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;center&#39;) {<br>          currentMain = mainBase + mainSpace / 2 * mainSign;<br>          gap = 0;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-between&#39;) {<br>          currentMain = mainBase;<br>          gap = mainSpace / (elementItems.length - 1) * mainSign;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-around&#39;) {<br>          currentMain = gap / 2 + mainBase;<br>          gap = mainSpace / elementItems.length * mainSign;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-evenly&#39;) {<br>          gap = mainSpace / (elementItems.length + 1) * mainSign<br>          currentMain = gap + mainBase<br>        }<br>        // calculate mainend based on mainstart and mainsize<br>        for (let i = 0; i &lt; flexLine.length; i++) {<br>          itemStyle[mainStart] = currentMain;<br>          itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>          currentMain = itemStyle[mainEnd] + gap;<br>        }<br>      }<br>    })<br>  }</pre><p>If the flex-direction is “row”, at this point we have the value of width, left, and right. The next step is to calculate the cross axis to get the value of height, top, and bottom. When these are determined, the position of the element is also determined.</p><h4>Calculate the cross axis</h4><ul><li>the height of the line based on the height of the largest element</li><li>the specific position of elements can be calculated according to the value of flex-align and item-align</li></ul><p>./client/layout.js (continue with the previous code block)</p><pre>  if (!style[crossSize]) {<br>    // if the parent element has no crossSize, crossSpace will always be zero<br>    crossSpace = 0;<br>    elementStyle[crossSize] = 0;<br>    // add the height of the expansion<br>    for (let i = 0; i &lt; flexLines.length; i++) {<br>      elementStyle[crossSize] = elementStyle[crossSize] + flexLines[i].crossSpace;<br>    }<br>  } else {<br>    crossSpace = style[crossSize];<br>    for (let i = 0; i &lt; flexLines.length; i++) {<br>      crossSpace -= flexLines[i].crossSpace;<br>    }<br>  }</pre><pre>  // wrap-reverse    this affects crossBase<br>  if (style[&#39;flex-wrap&#39;] === &#39;wrap-reverse&#39;) {<br>    crossBase = style[crossSize];<br>  } else {<br>    crossBase = 0;<br>  }</pre><pre>  let lineSize = style[crossSize] / flexLines.length;<br>  let gap;<br><br>  if (style[&#39;align-content&#39;] === &#39;flex-start&#39;) {<br>    crossBase += 0;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;flex-end&#39;) {<br>    crossBase += crossSpace * crossSign;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;center&#39;) {<br>    crossBase += crossSpace * crossSign / 2;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;space-between&#39;) {<br>    crossBase += 0;<br>    gap = crossSpace / (flexLines.length - 1);<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;space-around&#39;) {<br>    crossBase += crossSign * gap / 2;<br>    gap = crossSpace / (flexLines.length);<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;stretch&#39;) {<br>    crossBase += 0;<br>    gap = 0;<br>  }</pre><pre>  flexLines.forEach(flexLine =&gt; {<br>    let lineCrossSize = style[&#39;align-content&#39;] === &#39;stretch&#39;<br>      ? flexLine.crossSpace + crossSpace / flexLines.length<br>      : flexLine.crossSpace;<br><br>    for (let i = 0; i &lt; flexLine.length; i++) {<br>      let itemStyle = getStyle(flexLine[i]);<br>      let align = itemStyle[&#39;align-self&#39;] || style[&#39;align-items&#39;];</pre><pre>      if (itemStyle[crossSize] === null) {<br>        itemStyle[crossSize] = align === &#39;stretch&#39;<br>          ? lineCrossSize<br>          : 0;<br>      }</pre><pre>      if (align === &#39;flex-start&#39;) {<br>        itemStyle[crossStart] = crossBase;<br>        itemStyle[crossEnd] = itemStyle[crossStart] + crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;flex-end&#39;) {<br>        itemStyle[crossStart] = crossBase + crossSign * lineCrossSize;<br>        itemStyle[crossEnd] = itemStyle[crossEnd] - crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;center&#39;) {<br>        itemStyle[crossStart] = crossBase + crossSign * lineCrossSize[crossSize] / 2;<br>        itemStyle[crossEnd] = itemStyle[crossStart] + crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;stretch&#39;) {<br>        itemStyle[crossStart] = crossBase;<br>        itemStyle[crossEnd] = crossBase + crossSign * ((itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) ? itemStyle[crossSize] : lineCrossSize);<br>        itemStyle[crossSize] = crossSign * (itemStyle[crossEnd] - itemStyle[crossStart]);<br>      }<br>    }<br>    crossBase += crossSign * (lineCrossSize + gap);<br>  })</pre><p>Now, we have a DOM tree with the position data!</p><h4>Send an HTML with flexbox layout from the server</h4><p>./server/server.js</p><pre>...<br>     <br>     response.end(<br>        `&lt;html maaa=a &gt;<br>      &lt;head&gt;<br>            &lt;style&gt;<br>      #container {<br>        width:500px;<br>        height:300px;<br>        display:flex;<br>        background-color:rgb(139,195,74);<br>      }<br>      #container #myid {<br>        width:200px;<br>        height:100px;<br>        background-color:rgb(255,235,59);<br>      }<br>      #container .c1 {<br>        flex:1;<br>        background-color:rgb(56,142,60);<br>      }<br>        &lt;/style&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;<br>        &lt;div id=&quot;container&quot;&gt;<br>            &lt;div id=&quot;myid&quot;/&gt;<br>            &lt;div class=&quot;c1&quot; /&gt;<br>        &lt;/div&gt;<br>      &lt;/body&gt;<br>      &lt;/html&gt;`);<br>      ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*mQGXL-0_kNnI5TW80jxZeg.png" /></figure><p>As you can see from the new DOM tree, the positions of the elements are already there. It’s ready to be rendered!</p><h3>Step five: render</h3><p>In the field of computer graphics, the term “render” specifically refers to the process of turning a model into a bitmap. Note that some frameworks, like React, call the “process from data to HTML code” as to render, which is different.</p><p>The bitmap here is a two-dimensional table built in memory, and the color corresponding to each pixel of a picture is saved.</p><p>Here we use the “images” library for painting in the viewport, it supports painting background-color, border, background-image, etc.</p><p>npm install images</p><h4>Render one flex item</h4><p>In the beginning, let’s try to render one flex item.</p><p>./client/render.js</p><pre>const images = require(&quot;images&quot;);</pre><pre>function render(viewport, element) {<br>  if (element.style) {<br>    let img = images(element.style.width, element.style.height);<br>    // to simplify, only deal with background color<br>    if (element.style[&quot;background-color&quot;]) {<br>      let color = element.style[&quot;background-color&quot;] || &quot;rgb(0, 0, 0)&quot;;<br>      color.match(/rgb\((\d+),(\d+),(\d+)\)/);<br>      img.fill(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3));<br>      viewport.draw(<br>        img,<br>        element.style.left || 0,<br>        element.style.top || 0<br>      );<br>    }<br>  }<br>}</pre><pre>module.exports = render;</pre><p>./client/index.js</p><pre>const net = require(&#39;net&#39;);<br>const images = require(&quot;images&quot;);<br>const parser = require(&#39;./parser&#39;);<br>const render = require(&quot;./render&quot;);</pre><pre>...</pre><pre>void async function () {<br>  const request = new Request({...});</pre><pre>  const response = await request.send();<br>  const dom = parser.parseHTML(response.body);</pre><pre>  const viewport = images(800, 600);<br>  render(viewport, dom.children[0].children[3].children[1].children[3]); // the element to render<br>  viewport.save(&#39;viewport.jpg&#39;);<br>}()</pre><p>Go check the viewport.jpg, we rendered the item out successfully!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*C--W4nSK0HxNZuMHyPPkdA.jpeg" /></figure><h4>Full rendering</h4><p>This step is quite easy, calling the render() method of the children elements recursively can render the whole DOM tree.</p><p>Text rendering is difficult, it relying on the font library to turn the font into a picture. We ignore it in our mini-browser project.</p><p>./client/render.js</p><pre>function render(viewport, element) {<br>  if (element.style) {<br>    ...<br>  }</pre><pre>  if (element.children) {<br>    for (const child of element.children) {<br>      render(viewport, child);<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sowzMWRazs0QMAWQ3dZhHg.jpeg" /></figure><p>Run the index.js and check the picture again, you’ll find that the elements are rendered perfectly.</p><p>Let’s change some flex rules to see whether the browser can handle it, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbWTj_-TZHDxxI1EBOqMKw.png" /></figure><p>The answer is yes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QnnmIFkQPx4uJy1nIhlTg.jpeg" /></figure><p>We have successfully developed a toy mini-browser that supports HTTP requests, HTML/CSS parsing, and flexbox layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ja34YXnWUZF40kwNx5adA.png" /></figure><p>After going through these steps, I hope you have a deeper understanding of how browsers works. If you want to view the complete code, please refer to this <a href="https://github.com/BeijiYang/mini-browser">repository</a>. The index.js in the client-side is separated into a few more files, but the basic structure remains.</p><pre>src<br>├── client<br>│   ├── index.js<br>│   ├── Request.js<br>│   ├── HTMLparser.js<br>│   ├── ResponseParser.js<br>│   ├── ChunkedBodyParser.js<br>│   ├── layout.js<br>│   ├── render.js<br>│   ├── package.json<br>│   ├── package-lock.json<br>│   └── viewport.jpg<br>└── server<br>    ├── server.js<br>    ├── package.json<br>    └── package-lock.json</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa63a32851e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/understanding-how-browsers-work-by-creating-one-9aa63a32851e">Understanding how browsers work by creating one</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we help your chatbot learn over time]]></title>
            <link>https://medium.com/jobpal-dev/how-we-help-your-chatbot-learn-over-time-2f0ac72d0d6c?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f0ac72d0d6c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Klaudia Niedbałowska]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 07:30:46 GMT</pubDate>
            <atom:updated>2020-06-19T09:13:35.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Surprise! How we help your chatbot learn over time</h3><p>A conversational agent, or chatbot, can learn over time in different ways. One important way is through human intervention when we resolve the most ambiguous cases and <a href="https://jobpal.ai/en/blog/what-do-job-seekers-ask-about-during-pandemic/">respond to emerging topics</a>.</p><blockquote>Your users will always surprise you.</blockquote><p>After you set up your chatbot — flow, and a great FAQ dataset with all possible knowledge that your users, job seekers and candidates, would like to know about your company — you publish it and then you realise that chatbot users do want to know how the chatbot is doing, say hello or quickly access the main menu. Or something else entirely! The good news is — once our team at jobpal notices this kind of user behavior across all chatbots, we can help the chatbot respond to contextual questions better, without creating additional work for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABKGLsvBW9OVbRs5lCupHA.png" /><figcaption>How many small talk queries chatbot encounters and what are the main types?</figcaption></figure><p>Behind every great new Machine Learning technology, there is a human factor — people that dedicate their time to support the learning process of the particular language model, allowing it to respond to questions like “How are you?”, “What is your purpose?” or “Who are you?” without creating a need for supporting these topics in the company-specific FAQs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Jj2AkSGaCuQ6z858nS_vg.png" /><figcaption>Small talk and Job discovery are maintained by jobpal, FAQ responses come from out clients’ accounts and are maintained/trained by the client</figcaption></figure><p>All incoming messages go through intent recognition and entity extraction. Some, which are recognized as frequently asked questions (FAQs) go to a dataset specific to a particular company. You can find out more about what <a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">topics FAQs cover in a previous article</a>.</p><p>Training an FAQ dataset is different than training the Intents dataset: Intents are more open-ended and affect all parts of the bot flow. It takes more than one person to assess the most ambiguous, troublesome commands. For example, users might join multiple intents when they ask questions like “Hello, how are you?”(should the bot respond to Hello, or to How are you?) or “Thank you, goodbye” (should it respond to Bye, or to Thanks intent?). To resolve these ambiguities, we created an internal Slack channel to maintain data quality.</p><p>Other topics we discussed in this channel involved misspellings (when to keep and when to delete?); using synonyms (United Kingdom — UK); training common welcome phrases for foreign language models (should “Hi” remain in a German or Chinese dataset); or training single words into the categories (should “Graduates” trigger a job search?).<strong> </strong>This internal channel serves as a resolution to each particular case, and is a great learning experience for the team in the process, especially when it comes to replicating learnings in all supported languages.</p><p>Your users will always surprise you! Whether maintaining the overall chatbot behavior through training intents, or company-specific FAQ sets, the key is to approach data quality as a team. With hundreds or thousands of daily incoming new messages, most are handled correctly — and for those ambiguous cases that need attention, it takes the team to assess, correct the direction, and maintain high data quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0ac72d0d6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/how-we-help-your-chatbot-learn-over-time-2f0ac72d0d6c">How we help your chatbot learn over time</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequential Evaluation to Help Develop Better Chatbots]]></title>
            <link>https://medium.com/jobpal-dev/sequential-evaluation-to-help-develop-better-chatbots-179771c207c5?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/179771c207c5</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mahdi Hamdani]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 17:11:03 GMT</pubDate>
            <atom:updated>2019-12-12T17:12:28.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*ioZmYfF_BzERA-2WnQ95Bg.png" /></figure><p>Continuously improving the quality of classification is crucial for <a href="https://jobpal.ai/en/customers/">chatbot projects that use it</a>. How can we validate the algorithm choice and at the same time understand and improve the data quality?</p><p>The challenge is to select a classification algorithm that doesn’t just work well for <a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">many (100–200) classes</a> but also maintains reliable and consistent performance over time. We’ve worked before <a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">on better evaluation of dataset snapshots</a>, and recently have been looking into evaluation over the long life of dataset development and maintenance.</p><p>We introduce one way to evaluate the chatbot performance using historical data. Implementation can be found here <a href="https://github.com/jobpal/nex-cv">https://github.com/jobpal/nex-cv</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f919cff15807bb8dc5e39b90832f3097/href">https://medium.com/media/f919cff15807bb8dc5e39b90832f3097/href</a></iframe><p>The proposed evaluation can be used to monitor the performance of a specific algorithm over time. Training the chatbot continuously on live incoming data is an important feature that allows the algorithm to show live improvements for the clients. <strong>Sequential evaluation</strong> needs time information to reconstruct the real scenario where new (or updated) data is provided to the trained model. Test data is selected using time information s.t. at each step it is selected from the period of time covered by the training data. This allows “playing back” the real process of a chatbot being trained, and allows comparing a classification algorithm not just at one point in time, but over the re-constructed lifetime of a dataset. Performance metrics are reported, namely:</p><ul><li>Run time (in seconds)</li><li>Accuracy</li><li>Weighted and macro F1 scores</li><li>Precision/recall per class</li><li>Results on randomly selected <em>N</em> examples (for debugging)</li></ul><p>Depending on the training algorithm used, decisions will be made when receiving new data (with or without new classes) or updates to old data (e.g., a changed ground truth label). Will the algorithm perform full re-training in all cases or does it depend on the mentioned conditions?</p><p><strong>Online classifiers</strong> are a natural choice when training on data streams but it comes with the cost of forgetting old knowledge. Sequential evaluation could be used in this context to evaluate the ability of the online classifier to <em>remember</em> old data. Based on <em>50k</em> questions asked over 1 year from 1 chatbot, you see below the performance in accuracy (bars) and run time on an AWS r5.xlarge instance (blue line) of an online classifier. The dark grey bars indicate that one or more classes are added s.t. a full re-training is needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oA6e4oWawLpJ483W57558w.png" /><figcaption>Sequential evaluation on a company FAQ dataset</figcaption></figure><p>Furthermore, data insights could be developed from analysing the sequential evaluation results. <strong>Concept drift</strong> for instance is a hard to detect problem that can emerge over time for different reasons, e.g. a new reviewer with a different understanding of the what a class means in a dataset will apply the “ground truth” labels differently. The sequential evaluator helps giving a more in-depth view of a classification algorithm performance, including how much changes in the dataset impact measures of the classifier performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=179771c207c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/sequential-evaluation-to-help-develop-better-chatbots-179771c207c5">Sequential Evaluation to Help Develop Better Chatbots</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Puppeteer isn’t just for testing! How to generate great docs and ease development]]></title>
            <link>https://medium.com/jobpal-dev/puppeteer-isnt-just-for-testing-how-to-generate-great-docs-and-ease-development-1b18a6c5bb2e?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/1b18a6c5bb2e</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[puppeteer]]></category>
            <dc:creator><![CDATA[Valentin Vago]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 09:49:28 GMT</pubDate>
            <atom:updated>2019-12-05T09:49:28.082Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever heard of <a href="https://pptr.dev/">Puppeteer</a>? The tool that allows to control Google Chrome and Chromium based browsers programmatically.</p><p>The two main usages of puppeteer are end-2-end testing and site scraping but you can do so much more with it and this article is about 2 other possible usages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*bDKzc4MBNqhWWHxneBEvNA.jpeg" /></figure><h3>Generating documentation</h3><p>Creating documentation can be tedious work. Usually it requires to take screenshots of the app at very specific steps of its usage, moving those screenshots to a document to which you still need to add some comments.</p><p>And you will have to update all that when something changes in the app.</p><p>The perfect example of a un-satisfying and repetitive grunt work.<br>Bummer!</p><p>Luckily, if you have Puppeteer set up right, you can take screenshots and attach them the right comments in a programmatic fashion.</p><p>One way to achieve that is to create a function in the <a href="https://jestjs.io/">Jest</a> environment file and expose it to your tests.<br>The function will take a screenshot of the page at the precise moment you want, store the path of the image in conjunction with the comments and at the end of the tests (at teardown) will compile all that as an HTML document.</p><p>The Jest environment should look somehow like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d526946b9aa25d2625b2f64357cce4d/href">https://medium.com/media/4d526946b9aa25d2625b2f64357cce4d/href</a></iframe><p>With a template to render the collected documentation more or less like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b46fab8be368830e549798954f02a50f/href">https://medium.com/media/b46fab8be368830e549798954f02a50f/href</a></iframe><p>And finally call the “writeDocs” function in your tests…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5237ff8ca02a1efe2d4b7b86395a44e3/href">https://medium.com/media/5237ff8ca02a1efe2d4b7b86395a44e3/href</a></iframe><p>Once the tests are run, the teardown compiles the screenshots taken with the information you passed to the writeDocs function and produce a neat HTML file (see the teardown method in the code above).</p><h3>Improve your front-end developer experience</h3><p>Progresses in front-end tooling, like live-reloading and later hot-reloading, have eased development by avoiding most (but not all) need for reloading the browser window manually.</p><p>They are still edge-cases for which you might spend several minutes in order to reproduce a situation or state in the app.<br>Again un-satisfying and repetitive grunt work (and prone to mistakes).</p><p>The trick is to actually code those steps in your tests, launch them in a non-headless way (the default behaviour keeps the browser invisible, headless) and keep the browser open instead of closing it at the end of the test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/603903ed6251a25bcb33e08b504174af/href">https://medium.com/media/603903ed6251a25bcb33e08b504174af/href</a></iframe><p>Additionally you may want to run this against your development environment (opposed to the production build that you should use when doing proper testing) in order to benefit from the hot-reloading once you’re at the state you wanted to reach.<br>So start your development server first (here running on port 3000) npm start (or whatever suits your project) and then run jest TEST_KEEP_BROWSER=1 PORT=3000 npx jest --runInBand .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b18a6c5bb2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/puppeteer-isnt-just-for-testing-how-to-generate-great-docs-and-ease-development-1b18a6c5bb2e">Puppeteer isn’t just for testing! How to generate great docs and ease development</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Will this be a dealbreaker?”]]></title>
            <link>https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/1a323e58ee2c</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[conversational-ui]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[talent-acquisition]]></category>
            <dc:creator><![CDATA[Kit Kuksenok]]></dc:creator>
            <pubDate>Fri, 29 Nov 2019 09:08:08 GMT</pubDate>
            <atom:updated>2019-11-29T09:09:28.241Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve noticed that <a href="https://medium.com/jobpal-dev/picking-up-where-you-leave-off-5b58eabc8bf8">candidates approach recruiting chatbots more than half of the time <em>outside</em> of the working hours</a>; so, what topics do they ask about?</p><p>In <a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">an analysis from a few months ago</a>, we saw some broad topics:</p><ul><li><strong>25% </strong>of end-user queries fall into 5 major themes: <em>Application Process; Salary; Professional Growth &amp; Development; Internships; Contact a Human</em></li><li><strong>25% </strong>of end-user queries fall into 14 minor themes: <em>Application Evaluation; Application Deadline; Application Delete or Modify; How Long to Apply and Hear Back; Qualification; Application Documents; Language Expectations; Thesis; Working Hours; Location; Starting at the Company; Commute; Equipment; Benefits.</em></li><li><strong>40% </strong>concern company-specific FAQs, and the rest are too specific (e.g., contain identifying information), or are noise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wJMoFRJnal1s1KXCtZ2ig.png" /></figure><p>There are some fascinating use cases in the last 40%: like responding quickly to emerging topics. For example, a candidate may have received a fraudulent phishing email claiming to be from a well-known employer brand; the candidate can go to the chatbot and ask, “I got an email from xyz@abc.com about a position, is this real?” — and through <a href="https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc">a machine-learning mediated layer</a>, the recruiters can quickly create an automated response.</p><p>But even within commonly-occurring topics, <strong>directness </strong>is an interesting theme. When interacting with a conversational agent, people get right to the point: one of the most common questions across systems is “what is the salary?” — as well as questions about benefits, parental leave, and so forth. In particular, candidates ask about <strong>dealbreakers</strong>: “I have tattoos; will it be a problem?” or “My English is not very good, can I still apply?”</p><p>These are particularly interesting queries because they focus on skill or requirement <em>lack</em>, in a very straightforward way, often without hedging<em>. </em>The answers given by recruiters through the conversational agents are also more direct, at least by virtue of chat messages being relatively short.</p><p>So, why is it easier for people to pose direct questions to a bot and not to another person? One hypothesis could be that the conversational agent here is more human <em>because</em> it is not human: if you are interested in a job, you might hesitate to just ask outright about something that you <em>already think</em> might be a dealbreaker. However, there is no penalty to asking an automated, anonymous system. And in the best-case scenario? The chatbot delivers an answer, written by a recruiter, that anticipates this potentially complicated topic, and provides information that might help the candidate determine fit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a323e58ee2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/will-this-be-a-dealbreaker-1a323e58ee2c">“Will this be a dealbreaker?”</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asyncio, why and how?]]></title>
            <link>https://medium.com/jobpal-dev/asyncio-why-and-how-66a6b4db146?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/66a6b4db146</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Hamza Saadaoui]]></dc:creator>
            <pubDate>Wed, 13 Nov 2019 10:44:06 GMT</pubDate>
            <atom:updated>2019-12-17T22:31:42.618Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we are going to explore parallel programming and concurrency taking as example Asyncio, Motor, aiohttp.</p><h4>Concurrent programming:</h4><p>Concurrency is a programming concept that requires breaking down a problem into small tasks in order to increase the efficiency of our program in terms of CPU usage and execution time.</p><h4>Parallel programming:</h4><p>Parallel programming is executing multiple tasks <em>at the same time</em> using different CPU cores. In other words, parallel programming is one of the methods of implementing concurrency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*1iR0JFZ8LAlFqGsdPXkhyg.png" /></figure><blockquote>So what type of problems can concurrency solve?</blockquote><p><strong>CPU</strong> bound problem: Is in simple words, the problem where our program is spending most of the time in computing using the CPU .</p><p><strong>IO</strong> bound problem: Is usually referring to disk read/write operations, but it covers specially http requests and DB calls.</p><blockquote>Which problem does <strong>asyncio</strong> solve?</blockquote><p>Asyncio is a python library that will allow us to solve the IO bound problem, giving developers the possibility to use a <strong>single threaded</strong> program more efficiently by creating <strong>coroutines </strong>and having a full control over them.<br>Note that using python3.5+ the syntax is:</p><pre><br>async/await</pre><p>however using lower python versions the syntax is:</p><pre><br> @asyncio.coroutine/yield from</pre><p>well, let’s have concrete examples.<br>In the following examples we will use <strong>python3.6</strong>.</p><p>In the following example we will simulate an I/O operation using asyncio.sleep</p><pre>import asyncio<br><br><br>async def print_after_sleep(msg, s):<br>    await asyncio.sleep(s)<br>    print(&quot;Running Task&quot;, msg)<br>    <br><br>if __name__ == &#39;__main__&#39;:<br>    loop = asyncio.get_event_loop()<br>    tasks = [asyncio.ensure_future(print_after_sleep(1, 2)), asyncio.ensure_future(print_after_sleep(2, 1)),<br>         asyncio.ensure_future(print_after_sleep(3, 3))]<br>    loop.run_until_complete(asyncio.wait(tasks))<br>    loop.close()</pre><p>The output will be as follows and the event loop will pick up tasks from the queue while an I/O operation is running:</p><pre>Running Task 2<br>Running Task 1<br>Running Task 3</pre><p>In the following example we will implement a non blocking <em>Get</em> endpoint using <strong>aiohttp, motor </strong>to get customers by id.</p><pre>from motor.motor_asyncio import AsyncIOMotorClient</pre><pre>from bson.json_util import dumps<br></pre><pre>client = AsyncIOMotorClient(&#39;localhost&#39;, 27017)</pre><pre>db = client.customers_db<br></pre><pre>async def get_customer(request):</pre><pre>    customer_id = request.rel_url.query[&quot;customer_id&quot;]</pre><pre>    db = request.app[&#39;db&#39;]</pre><pre>    result = await db.customers.find_one({&#39;customer_id&#39;:  customer_id})</pre><pre>    if not result:<br>        return web.Response(text=&#39;customer with id:{!r}  doesn&#39;t      exist.&#39;.format(customer_id))</pre><pre>    return web.Response(body=dumps(result),<br>        content_type=&quot;application/json&quot;)</pre><pre>app = web.Application()<br>app.add_routes([web.get(<em>&#39;/&#39;</em>, get_customer)])<br></pre><pre>if __name__ == <em>&#39;__main__&#39;</em>:<br>    web.run_app(app)</pre><h3>To take away:</h3><p><a href="https://en.wikipedia.org/wiki/Concurrent_computing">Concurrency is a programming paradigm</a> while parallel programming is a specific implementation of concurrency, where multiple CPU cores are used simultaneously. “The Python <strong>Global Interpreter Lock</strong> or GIL, in simple words, is a mutex (or a lock) that allows <strong>only one thread to hold the control of the Python interpreter</strong>. … [In a] multi-processing approach where you use multiple processes instead of threads[,] each Python process gets its own Python interpreter and memory space so the GIL won’t be a problem. Python has a multiprocessing module [for this.]” [<a href="https://realpython.com/python-gil/">1</a>]</p><p>“Threads [in Python; so <em>not</em> parallel processes] can interact in ways that are subtle and hard to detect. These interactions can cause race conditions that frequently result in random, intermittent bugs that can be quite difficult to find. … An important point of<strong> asyncio is that the tasks never give up control without intentionally doing so</strong>. They never get interrupted in the middle of an operation. This allows us to share resources a bit more easily in asyncio than in threading. You don’t have to worry about making your code thread-safe.” [<a href="https://realpython.com/python-concurrency/">2</a>]</p><p>“asyncio takes a very, very explicit approach to asynchronous programming: only code written in methods flagged as async can call any code in an asynchronous way. Which creates a <strong>chicken/egg problem: your async methods can only be called by other async methods, so how do you call the first one?</strong> The answer: you don’t. What you have to do instead is turn over control of the task to an event loop, after arranging for the loop to (sooner or later) invoke your async code.” [<a href="https://cheat.readthedocs.io/en/latest/python/asyncio.html">3</a>]</p><p>To use asyncio, you must use <strong>awaitables</strong>, which are objects that “can be used in an await expression,” new in Python 3.5, which can “suspend the execution of coroutine [and] can only be used inside a coroutine function.”[<a href="https://docs.python.org/3/library/asyncio-task.html#awaitables">4</a>] [<a href="https://docs.python.org/3/reference/expressions.html#await">5</a>]</p><p><em>And a bonus link, on how Python async/await relates to JavaScript promises! </em>“If you’re coming from a JavaScript background, it’s tempting to try to use the promises that you know and love with Python. [But it] turns out that promises are not pythonic: I should have used async/await instead. This post explains why async/await is a better idiom that you can use both in Python and JavaScript.” [<a href="https://quentin.pradet.me/blog/you-dont-need-promises-in-python-just-use-asyncawait.html">6</a>]</p><h3><strong><em>Conclusion:</em></strong></h3><p>In this blog post, we described the difference between concurrent and parallel programming. We also made some examples that showed how Asyncio, and libraries built on top such as aiohtpp and motor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a6b4db146" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/asyncio-why-and-how-66a6b4db146">Asyncio, why and how?</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plausible Negative Examples for Better Multi-Class Classifier Evaluation]]></title>
            <link>https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/d8e8cb2422db</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Kit Kuksenok]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 13:46:58 GMT</pubDate>
            <atom:updated>2019-11-08T13:46:58.635Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://www.aclweb.org/anthology/W19-4110/">ACL2019, we introduced <strong>nex-cv</strong></a><strong>: </strong>a metric based on cross-validation, adapted for improvement of small, unbalanced natural-language datasets used in chatbot design. The main idea is to use <strong>plausible negative examples</strong> in the evaluation of text classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRTU4rPTX0P0ibGOFSUIuw.png" /></figure><p>Our experiences draw upon building <strong>recruitment chatbots </strong>that mediate communication between job-seekers and recruiters by <strong>exposing the ML/NLP dataset<br> to the recruiting team. </strong>Recruiter teams motivated by scale and accessibility to build and maintain chatbots that provide answers to frequently asked questions (FAQs) based on ML/NLP datasets.</p><p>Enterprise clients may have up to 100K employees, and commensurate hiring rate. Over 50% of end-user (job-seeker) traffic occurs outside of working hours or during holidays (consistent with the anecdotal reports that using the chatbot reduces email and ticket load) —we <a href="https://medium.com/jobpal-dev/picking-up-where-you-leave-off-5b58eabc8bf8">dig into this in another post</a>.</p><p>Evaluation approaches must be be <a href="https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc">understandable to various stakeholders, and useful for improving chatbot performance</a>. We validate the metric based on seven recruitment domain datasets in English and German over the course of one year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNQ1hFopRpeOJGYLapDd1g.png" /></figure><h3>Data Quality Improvements</h3><p>Existing chatbot guidelines include “transparency” as an important topic, but, in practice, why something does not work, and under what conditions, can puzzle designers and developers, not just end-users (<a href="https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc">we’ve written about this in another paper and post</a>). The nex-cv metric helps because it:</p><ul><li>produces accuracy scores more in line with human judgment than, for example, F1 on cross-validation (details in <a href="https://www.aclweb.org/anthology/W19-4110/">paper</a>)</li><li>ensures that data from low-population classes is included in both training and testing, at least as a “negative example”</li><li>can be used to generate internal recommendations and as part of ongoing data quality maintenance</li></ul><p>The principle of these “recommendations” is to solve the worst problems first. The most common problem we have is when a smaller category overlaps in meaning with a larger one, and degrades both. The above graphic shows suggested pairs to focus on. The category <em>Remote_work</em> has fewer questions (only 15) than <em>Company_location</em> (which has 26). This may mean that <em>Remote_work</em> should be merged into <em>Company_location</em>; redistributed elsewhere in the dataset; or enriched and refined. Our internal tools use the metric to provide actionable guidance that has helped improve overall data quality significantly and consistently. The above recommendation is a generated text summary of confusion matrix results that is used by non-developer staff to improve data quality.</p><h3><strong>Data Quality and Maintenance in Chatbots</strong></h3><p>Classes — chatbot “<strong>intents</strong>” — are trained with synthetic data and constitute <strong>anticipated use, rather than actual use</strong>. Existing general chatbot platforms include this synthetic data step as part of design and maintenance.</p><p>For example, when it comes to invocations for a voice agent (Ali et al., 2018)*, dataset construction encodes findings about how users imagine asking for an action: the authors use crowdsourcing to achieve both consistency useful for classification, and <strong>reflection of user expectations in the dataset</strong>.</p><p>We work on enabling domain-experts (recruiters) to maintain the dataset, which helps map end-user (jobseeker) needs to recruiters’ goals.</p><p>Data cleaning is not only relevant to chatbots. Model-agnostic systems for understanding machine learning can help iteratively develop machine learning models (Zhang et al., 2019)*. Feature engineering can be made accessible to non-developers or domain experts, e.g. (Ribeiro et al., 2016)*. We make use of representative examples in the process that surfaces <strong>nex-cv</strong> to non-developers; using the the <strong>inspection-explanation-refinement</strong> approach employed in (Zhang et al., 2019)*. Enabling non-developers to perform data cleaning effectively allows developers to focus on model adjustments and feature engineering.</p><p>There are many ways to measure overall chatbot quality, such as manual check-lists of high-level feature presence (Kuligowska, 2015; Pereira and Díaz, 2018)*. User behavior measurements — both explicit, like ratings or feedback, and implicit, like timing or sentiment — are explored in (Hung et al., 2009)*. During metric development, we used qualitative feedback from domain-expert users, and key performance indicators (KPIs), such as automatic response rate. The use of a <strong>classifier as a component in a complex flow</strong> demands robust and <strong>actionable</strong> evaluation of that component.</p><p>* — see <a href="https://www.aclweb.org/anthology/W19-4110/">paper</a> for full references</p><h3>Code &amp; Implementation</h3><p>The code available online — <a href="https://github.com/jobpal/nex-cv">https://github.com/jobpal/nex-cv</a> — provides the evaluation implementation, an abstract black-box definition for a classifier, and two strategies to help test an implementation. For integration testing, <em>CustomClassifier.test()</em> can be used to check consistency of classifier wrapper. For functional testing, nex-cv with both K = 0 (Alg. 2) and P = 0 (Alg. 2) should yield results similar to 5-fold cross-validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UAFkLCYOnaPn5CQheRKLA.png" /></figure><p><strong>Evaluation and Improvement of Chatbot Text Classification Data Quality Using Plausible Negative Examples. </strong>Kit Kuksenok &amp; Andriy Martyniv — presented at <em>ACL 2019 Workshop on NLP for Conversational AI, August 1, 2019</em></p><p>Code: <a href="https://github.com/jobpal/nex-cv">https://github.com/jobpal/nex-cv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8e8cb2422db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/plausible-negative-examples-for-better-multi-class-classifier-evaluation-d8e8cb2422db">Plausible Negative Examples for Better Multi-Class Classifier Evaluation</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Beautiful Time-Series Visualisation with React-Vega]]></title>
            <link>https://medium.com/jobpal-dev/how-to-create-a-beautiful-time-series-visualisation-with-react-vega-3fd3e22ec445?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/3fd3e22ec445</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vegas]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Yujie Wang]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 10:55:49 GMT</pubDate>
            <atom:updated>2019-10-31T10:55:48.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Vega is a powerful grammar for visualisation, but to use it in a real web app project, it is necessary to make subtle and important UX tweaks dynamically. In this article, we walk you through a time-series area plot with facets, and additional line-chart layer in a React.js project. Here are the topics we cover:</p><ul><li>Showing integers in the y-axis.</li><li>Showing more readable timestamps on the x-axis by dynamically switching between ordinal and temporal data types.</li><li>Adding a more readable and customizable color legend to a layered chart.</li><li>Including the chart in a React project, including all the above UX tweaks as well as showing only the SVG/PNG exports in the export widget.</li><li>Enabling dynamic resizing of the chart when the user changes window size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*XHIGLTsshSYc37GZPF3_oA.gif" /></figure><h3>Libraries</h3><p>Open Google.com, search for “Vega”, and this is what you’ll see: <strong>Vega</strong>, <strong>Vega-Lite</strong>, <strong>Vega-Embed</strong>, <strong>React-Vega</strong>, so many libraries. If you don’t have much knowledge about them, you will get lost.</p><p>Don’t worry, below is the most simplified explanation:</p><ul><li><a href="https://vega.github.io/vega/"><strong>Vega</strong></a>: A visualization grammar. You can describe the chart using JSON, and get a Canvas or SVG. It is powerful and flexible.</li><li><a href="https://vega.github.io/vega-lite/"><strong>Vega-Lite</strong></a>: A high-level grammar for interactive charts and graphs, also JSON in Canvas/SVG out. Vega-Lite specifications can be compiled to Vega specifications. It is a convenient way to create a chart quickly.</li><li><a href="https://github.com/vega/vega-embed"><strong>Vega-Embed</strong></a>: A tool to embed the Vega/Vega-Lite chart into web pages.</li><li><a href="https://github.com/vega/react-vega/tree/master/packages/react-vega"><strong>React-Vega</strong></a>: A tool to help you use the Vega/Vega-Lite chart in a React project.</li></ul><p>Since Vega-Lite is quicker but not as powerful as Vega, you can first quickly express your idea using Vega-Lite, then edit/add more advanced functionality based on the Vega specifications generated from Vega-Lite.</p><h3>The chart</h3><p>Since most of the articles online focus on the bar chart as an example, in this post we will focus on making a good time-series area chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*c5u_i9wl_9tJBpKZtkinbg.png" /></figure><p>First, we start with a basic area chart. It shows the active users in the first week in October.</p><p>You can copy &amp; paste this JSON specification into the<a href="https://vega.github.io/editor/#/">Vega editor</a>.</p><pre>{<br>  &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v4.json&quot;,<br>  &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#0084FF&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>  &quot;encoding&quot;: {<br>    &quot;x&quot;: {<br>      &quot;field&quot;: &quot;date&quot;,<br>      &quot;type&quot;: &quot;temporal&quot;,<br>      &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>      &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;}<br>    },<br>    &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {&quot;title&quot;: &quot;Active Users&quot;}<br>    },<br>    &quot;opacity&quot;: {&quot;value&quot;: 1}<br>  },<br>  &quot;width&quot;: 400,<br>  &quot;height&quot;: 300,<br>  &quot;data&quot;: {<br>    &quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;}<br>    ]<br>  },<br>  &quot;config&quot;: {}<br>}</pre><p>It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*ntoxb4Uxhgguj-AM7SGi7Q.png" /></figure><h3>Show integer labels in the y-axis</h3><p>As you may have noticed, the number of active users is pretty small. We do this to highlight one problem of Vega’s default behavior. The chart looks very good for larger numbers, but for smaller numbers, the labels of the y-axis become float numbers. You can edit the data in the Vega editor by yourself.</p><p>There is no “half of a user”, the labels are supposed to be integers.</p><p>According to the official documentation, we can use the format function d to make the labels integers.</p><pre>...<br> &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;Active Users&quot;,<br>        &quot;format&quot;: &quot;d&quot;<br>        }<br>    },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*vkua6Pd0uukbzb41CIQM2w.png" /></figure><p>Now the floats are gone but a new issue appears. Some labels are duplicated.</p><p>We need to explicitly set the visible axis tick values using values on the y-axis.</p><pre>...<br> &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;Active Users&quot;,<br>        &quot;format&quot;: &quot;d&quot;,<br>        &quot;values&quot;: [1,2]<br>        }<br>    },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*0v4V6l91o2knYTn1WDRaMA.png" /></figure><p>Now we get a proper y-axis. Notice that there is no 0 in the array, so we can omit the label when the data is empty.</p><p>The values will change when the data change, so it needs to be passed into the spec JSON in the React component dynamically. We will return to this later in the article.</p><h3>Show proper labels in the x-axis(time axis)</h3><p>Currently, the x-axis looks good. But if we minimize the amount of data, or increase the width of the chart, the same duplicate-issue occurs.</p><p>Let’s try to make the chart larger.</p><pre>&quot;width&quot;: 1200,<br>&quot;height&quot;: 600,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHAIfjbltKJWueKvfjn91Q.png" /></figure><p>Setting the type as <a href="https://vega.github.io/vega-lite/docs/type.html#ordinal">ordinal</a> can solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQY9HpDqs24rGa2Ncf87ag.png" /></figure><p>But it is not a silver bullet: when the amount of data increases, too-crowded labels harms readability.</p><pre>...<br>  &quot;width&quot;: 400,<br>  &quot;height&quot;: 300,<br>  &quot;data&quot;: {<br>    &quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-08&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-09&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-10&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-11&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-12&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-13&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-14&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-15&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-16&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-17&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-18&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-19&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-20&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-21&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-22&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-23&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-24&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-25&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-26&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-27&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-28&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-29&quot;}<br>    ]<br>  },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*BhrD8XLZbGNhxb0j4ZxpNg.png" /></figure><p>So we need to add a condition: if the range is longer than 30 days, use temporal, otherwise, use ordinal.</p><p>For the sake of the user’s neck, let’s adjust the angle of the labels by setting labelAngle.</p><pre>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});</pre><p>If we only want to solve the labels-too-crowded problem, basically the labelAngle can do the job.</p><pre>...<br>&quot;x&quot;: {<br>    &quot;field&quot;: &quot;date&quot;,<br>    &quot;type&quot;: &quot;ordinal&quot;,<br>    &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>    &quot;axis&quot;: {<br>      &quot;title&quot;: &quot;Date&quot;,<br>      &quot;labelAngle&quot;: -45<br>    }<br> },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*fNr_3j6pZBh9fryZ8fW5xg.png" /></figure><p>The true difference between temporal and ordinal is:</p><ul><li>The former puts the data on an <strong>incompressible</strong> timeline.</li><li>The latter only displays the existing data.</li></ul><p>The following two pictures can be used to illustrate the difference. Note that only one day is added to the data.</p><pre>&quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2020-01-01&quot;} // happy new year~<br>    ]</pre><p><strong>temporal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*2I_u6KGzmZbEvh3997LYfw.png" /></figure><p><strong>ordinal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*SCdNXw5PbKOstEgnYIWPxA.png" /></figure><p>Now we already know how to make a single layer chart. What about multi layer chart?</p><h3>Multi-layer Chart</h3><p>There is nothing special about the multi-layer chart. All we need to do is to add a layer array. It is like a stack, we push the chart items in from the top.</p><p>To demonstrate a multi-layer chart, we add the &quot;user_comments&quot; in the previous data.</p><pre>...<br>&quot;data&quot;: {<br>  &quot;values&quot;: [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ]<br>},<br>...</pre><p>We can create a single layer “User Comments” chart using the same Vega-Lite grammar as the previous one. Just replacing certain items in the y-axis object is enough.</p><pre>...<br>&quot;mark&quot;: { &quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot; },<br>  &quot;encoding&quot;: {<br>    &quot;x&quot;: {<br>      &quot;field&quot;: &quot;date&quot;,<br>      &quot;type&quot;: &quot;ordinal&quot;,<br>      &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>       &quot;axis&quot;: { &quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45 }<br>    },<br>    &quot;y&quot;: {<br>      &quot;field&quot;: &quot;user_comments&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;User Comments&quot;,<br>        &quot;format&quot;: &quot;d&quot;,<br>        &quot;values&quot;: [1, 2, 3]<br>      }<br>    }<br>  },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*nr9NMof98U33K6lDlOkN3A.png" /></figure><p>Then we add a layer array. Push the &quot;User Comments&quot; chart object in this array. Nothing changed, it is still a single layer chart.</p><pre>...<br>&quot;layer&quot;:[<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          }<br>      }<br>    }<br>  ],<br>  ...</pre><p>What will happen if we push the “Active Users” object in this array, too?</p><pre>...<br>&quot;layer&quot;:[<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          }<br>      }<br>    },<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#0084FF&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;: {<br>          &quot;field&quot;: &quot;date&quot;,<br>          &quot;type&quot;: &quot;ordinal&quot;,<br>          &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>          &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>          &quot;field&quot;: &quot;active_users&quot;,<br>          &quot;type&quot;: &quot;quantitative&quot;,<br>          &quot;axis&quot;: {<br>          &quot;title&quot;: &quot;Active Users&quot;,<br>          &quot;format&quot;: &quot;d&quot;,<br>          &quot;values&quot;: [1,2]<br>          }<br>        }<br>      }<br>    }<br>  ],<br>  ...</pre><p>Here it is! A double layer chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*5jFDKrimUfkf9ZswLUGFEQ.png" /></figure><h3>Add legend</h3><p>Although this chart looks pretty, it has a problem with clarity. Our user can not know which color indicates which data in a glance. Now is when we need to add legends in the chart.</p><p>There are several approaches to make it happen, here is my solution:</p><ul><li>using stroke to create the legend.</li><li>using legend to optimize the style.</li></ul><p>Add the stroke object in any chart object:</p><pre>...<br>  {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          },<br>        &quot;stroke&quot;: {<br>          &quot;field&quot;: &quot;symbol&quot;,<br>          &quot;type&quot;: &quot;ordinal&quot;,<br>          &quot;scale&quot;: {<br>            &quot;domain&quot;: [&quot;User Comments&quot;, &quot;Active Users&quot;],<br>            &quot;range&quot;: [&quot;#e0e0e0&quot;, &quot;#0084FF&quot;]<br>          }<br>        }<br>      }<br>  },<br>    ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*AyK_HqzKF0HvOOTYMwrB7Q.png" /></figure><p>We get a lame legend in the right-top corner.</p><p>Let’s make it look a bit better! First, we add legend object in the top config object.</p><pre>...<br> &quot;legend&quot;: {<br>        &quot;offset&quot;: -106, // Adjust the horizontal distance of the legend<br>        &quot;title&quot;: null,<br>        &quot;padding&quot;: 5,<br>        &quot;strokeColor&quot;: &quot;#9e9e9e&quot;,<br>        &quot;strokeWidth&quot;: 2,<br>        &quot;symbolType&quot;: &quot;stroke&quot;,<br>        &quot;symbolOffset&quot;: 0,<br>        &quot;symbolStrokeWidth&quot;: 10,<br>        &quot;labelOffset&quot;: 0,<br>        &quot;cornerRadius&quot;: 10,<br>        &quot;symbolSize&quot;: 100,<br>        &quot;clipHeight&quot;: 20<br>    }<br>   ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*vPJmJH1XyEArEFYI-fpA0w.png" /></figure><p>Already it looks so much better.</p><p>Since we already have the legend, we can safely get rid of the labels on the y-axis. Just delete the title of y.axis object, or leave it empty.</p><p>When the amount of the layer grows, we can also use both the area chart and the line chart at the same time, just like the example down blew. Looks nice, doesn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*in9UfhnfvWsOqj6Ff22TkA.png" /></figure><h3>Display Vega-Lite chart in the React project</h3><p>Install the react-vega library.</p><pre>npm install react vega vega-lite react-vega --save</pre><p>First, let’s simply put our chart above in the React project.</p><pre>...<br>import { Vega } from &#39;react-vega&#39;;<br><br><br>const spec = {<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;, <br>  layer: [<br>    {<br>      mark: { type: &#39;area&#39;, color: &#39;#e0e0e0&#39;, interpolate: &#39;monotone&#39; },<br>      encoding: {<br>        x: {<br>          field: &#39;date&#39;,<br>          type: &#39;ordinal&#39;,<br>          timeUnit: &#39;yearmonthdate&#39;,<br>          axis: { title: &#39;Date&#39;, labelAngle: -45 },<br>        },<br>        y: {<br>          field: &#39;user_comments&#39;,<br>          type: &#39;quantitative&#39;,<br>          axis: {<br>            title: &#39;User Comments&#39;,<br>            format: &#39;d&#39;,<br>            values: [1, 2, 3],<br>          },<br>        },<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [&#39;#e0e0e0&#39;, &#39;#0084FF&#39;],<br>          },<br>        },<br>      },<br>    },<br>    {<br>      mark: { type: &#39;area&#39;, color: &#39;#0084FF&#39;, interpolate: &#39;monotone&#39; },<br>      encoding: {<br>        x: {<br>          field: &#39;date&#39;,<br>          type: &#39;ordinal&#39;,<br>          timeUnit: &#39;yearmonthdate&#39;,<br>          axis: { title: &#39;Date&#39;, labelAngle: -45 },<br>        },<br>        y: {<br>          field: &#39;active_users&#39;,<br>          type: &#39;quantitative&#39;,<br>          axis: {<br>            title: &#39;Active Users&#39;,<br>            format: &#39;d&#39;,<br>            values: [1, 2],<br>          },<br>        },<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: {<br>      offset: -106, // Adjust the horizontal distance of the legend<br>      title: null,<br>      padding: 5,<br>      strokeColor: &#39;#9e9e9e&#39;,<br>      strokeWidth: 2,<br>      symbolType: &#39;stroke&#39;,<br>      symbolOffset: 0,<br>      symbolStrokeWidth: 10,<br>      labelOffset: 0,<br>      cornerRadius: 10,<br>      symbolSize: 100,<br>      clipHeight: 20,<br>    },<br>  },<br>};<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>    ]<br><br>...<br><br>return (<br>  ...<br><br>    &lt;Vega<br>      spec={{<br>        ...spec,<br>         width: 400,<br>         height: 300,<br>         data: { values: data },<br>       }}<br>      /&gt;<br>  ...<br>)</pre><p>Then we can make it chart better by doing some refactoring work.</p><ul><li>the condition function on the x-axis we have talked about earlier.</li><li>a new getSpec function to return the spec object.</li><li>a function to generate the values array based on the biggest key value from the data.</li></ul><pre>import React from &#39;react&#39;;<br>import { Vega } from &#39;react-vega&#39;;<br><br>// chart config<br>const jobpalBlue = &#39;#e0e0e0&#39;;<br>const jobpalLightGrey = &#39;#0084FF&#39;;<br>const jobpalDarkGrey = &#39;#9e9e9e&#39;;<br><br>const areaMark = {<br>  type: &#39;area&#39;,<br>  color: jobpalBlue,<br>  interpolate: &#39;monotone&#39;,<br>};<br><br>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});<br><br>const getQuantitativeYObj = (field, title, values) =&gt; ({<br>  field,<br>  type: &#39;quantitative&#39;,<br>  axis: {<br>    title,<br>    format: &#39;d&#39;,<br>    values,<br>  },<br>});<br><br>const legendConfig = {<br>  title: null,<br>  offset: -106,<br>  padding: 5,<br>  strokeColor: jobpalDarkGrey,<br>  strokeWidth: 2,<br>  symbolType: &#39;stroke&#39;,<br>  symbolOffset: 0,<br>  symbolStrokeWidth: 10,<br>  labelOffset: 0,<br>  cornerRadius: 10,<br>  symbolSize: 100,<br>  clipHeight: 20,<br>};<br><br>const getSpec = (yAxisValues = [], rangeLen = 0) =&gt; ({<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;,<br>  layer: [<br>    {<br>      mark: {<br>        ...areaMark,<br>        color: jobpalLightGrey,<br>      },<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;user_comments&#39;, &#39;&#39;, yAxisValues),<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [jobpalLightGrey, jobpalBlue],<br>          },<br>        },<br>      },<br>    }, {<br>      mark: areaMark,<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;active_users&#39;, &#39;&#39;, yAxisValues),<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: legendConfig,<br>  },<br>})<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ]</pre><pre>// React component</pre><pre>const App = () =&gt; {<br>  // get max value from data arary<br>  const yAxisMaxValueFor = (...keys) =&gt; {<br>    const maxList = keys.map(key =&gt; data.reduce(<br>         // find the item containing the max value<br>        (acc, cur) =&gt; (cur[key] &gt; acc[key] ? cur : acc)<br>      )[key]<br>    );<br>    return Math.max(...maxList);<br>  };<br><br>  const yAxisValues = Array.from(<br>    { length: yAxisMaxValueFor(&#39;active_users&#39;, &#39;user_comments&#39;) },<br>  ).map((v, i) =&gt; (i + 1));<br><br><br>  const spec = getSpec(yAxisValues, data.length);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;Vega<br>        spec={{<br>          ...spec,<br>          autosize: &#39;fit&#39;,<br>          resize: true,<br>          contains: &#39;padding&#39;,<br>          width: 400,<br>          height: 300,<br>          data: { values: data },<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>So far, we have successfully introduced the charts described by Vega-Lite in the React project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Wu-edUjnQ4IFc_LAbjJ4QA.png" /></figure><h3>Manage the widget</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*gyqXPVKvcY9KkjVwG6k0Ig.png" /></figure><p>On the right-top corner, there is a widget. Click it and you’ll see all the actions you can take: download the chart in different formats, view source/complied Vega, open in Vega editor.</p><p>The last three items should only appear in the development stage. In the production, we leave the first two download options, and it would be better if we can specify the download file name instead of a default one.</p><p>Luckily, it can be done using React-Vega. This is an advantage of React-Vega, which supports several configuration features of Vega-Embed, as described in the <a href="https://vegawidget.github.io/vegawidget/reference/vega_embed.html">documentation</a>.</p><p>Here, we only need two more configurations: actions and downloadFileName. The former uses Boolean values to control exported functions, the latter specifies the name of the downloaded file.</p><pre>...<br>  &lt;Vega<br>    spec={ ... }<br>    actions={{<br>        export: true,<br>        source: false,<br>        compiled: false,<br>        editor: false,<br>      }}<br>      downloadFileName={&#39;Just Name It&#39;}<br>    /&gt;<br>  ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*CqP4wIb1KguwM5TF3GbwAQ.png" /></figure><h3>Resize</h3><p>In a real project, we have to make sure that the size of the chart always fits the browser window. Currently the chart doesn’t rescale, but we can make it happen by letting the React component take charge of the width/height of the chart.</p><p>Basically:</p><ul><li>mange width/height in state.</li><li>repaint the chart by using setState.</li><li>in the lifecycle method, set event listener to listen to resize event.</li><li>get the current right width/height value by using CSS and ref in the wrapper div.</li></ul><p>Talk is cheap, here is the code.</p><pre>import React from &#39;react&#39;;<br>import { Vega } from &#39;react-vega&#39;;<br><br>// chart config<br>const jobpalBlue = &#39;#e0e0e0&#39;;<br>const jobpalLightGrey = &#39;#0084FF&#39;;<br>const jobpalDarkGrey = &#39;#9e9e9e&#39;;<br><br>const areaMark = {<br>  type: &#39;area&#39;,<br>  color: jobpalBlue,<br>  interpolate: &#39;monotone&#39;,<br>};<br><br>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});<br><br>const getQuantitativeYObj = (field, title, values) =&gt; ({<br>  field,<br>  type: &#39;quantitative&#39;,<br>  axis: {<br>    title,<br>    format: &#39;d&#39;,<br>    values,<br>  },<br>});<br><br>const legendConfig = {<br>  title: null,<br>  offset: -106,<br>  padding: 5,<br>  strokeColor: jobpalDarkGrey,<br>  strokeWidth: 2,<br>  symbolType: &#39;stroke&#39;,<br>  symbolOffset: 0,<br>  symbolStrokeWidth: 10,<br>  labelOffset: 0,<br>  cornerRadius: 10,<br>  symbolSize: 100,<br>  clipHeight: 20,<br>};<br><br>const getSpec = (yAxisValues = [], rangeLen = 0) =&gt; ({<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;,<br>  layer: [<br>    {<br>      mark: {<br>        ...areaMark,<br>        color: jobpalLightGrey,<br>      },<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;user_comments&#39;, &#39;&#39;, yAxisValues),<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [jobpalLightGrey, jobpalBlue],<br>          },<br>        },<br>      },<br>    }, {<br>      mark: areaMark,<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;active_users&#39;, &#39;&#39;, yAxisValues),<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: legendConfig,<br>  },<br>})<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ];<br><br>// get max value from data arary<br>const yAxisMaxValueFor = (...keys) =&gt; {<br>  const maxList = keys.map(key =&gt; data.reduce(<br>    // find the item containing the max value<br>    (acc, cur) =&gt; (cur[key] &gt; acc[key] ? cur : acc)<br>  )[key]<br>  );<br>  return Math.max(...maxList);<br>};<br><br>const { addEventListener, removeEventListener } = window;<br><br>class App extends React.Component {<br><br>  state = {<br>    width: 400,<br>    height: 300,<br>  }<br><br>  componentDidMount() {<br>    addEventListener(&#39;resize&#39;, this.resizeListener, { passive: true, capture: false });<br>  }<br><br>  componentWillUnmount() {<br>    removeEventListener(&#39;resize&#39;, this.resizeListener, { passive: true, capture: false });<br>  }<br><br>  resizeListener = () =&gt; {<br>    if (!this.chartWrapper) return;<br><br>    const child = this.chartWrapper.querySelector(&#39;div&#39;);<br>    child.style.display = &#39;none&#39;;<br><br>    const {<br>      clientWidth,<br>      clientHeight: height,<br>    } = this.chartWrapper;<br>    const width = clientWidth - 40; // as padding: &quot;0 20px&quot;<br>    this.setState({ width, height });<br><br>    child.style.display = &#39;block&#39;;<br>  }<br><br>  refChartWrapper = el =&gt; {<br>    this.chartWrapper = el<br>    if (el) this.resizeListener();<br>  }<br><br>  yAxisValues = Array.from(<br>    { length: yAxisMaxValueFor(&#39;active_users&#39;, &#39;user_comments&#39;) },<br>  ).map((v, i) =&gt; (i + 1));<br><br>  render() {<br>    const { <br>      state: { width, height},<br>      yAxisValues,<br>    } = this;<br><br>    const spec = getSpec(yAxisValues, data.length);<br><br>    return (<br>      &lt;div<br>        ref={this.refChartWrapper}<br>        style={{ margin: &#39;10vh 10vw&#39;, width: &#39;80vw&#39;, height: &#39;50vh&#39; }}<br>        &gt;<br>        &lt;Vega<br>          spec={{<br>            ...spec,<br>            autosize: &#39;fit&#39;,<br>            resize: true,<br>            contains: &#39;padding&#39;,<br>            width,<br>            height,<br>            data: { values: data },<br>          }}<br>          actions={{<br>            export: true,<br>            source: false,<br>            compiled: false,<br>            editor: false,<br>          }}<br>          downloadFileName={&#39;Just Name It&#39;}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*XHIGLTsshSYc37GZPF3_oA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd3e22ec445" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/how-to-create-a-beautiful-time-series-visualisation-with-react-vega-3fd3e22ec445">How to Create a Beautiful Time-Series Visualisation with React-Vega</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why (and How) Explainable AI Matters for Chatbot Design]]></title>
            <link>https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc?source=rss----2cca75d51128---4</link>
            <guid isPermaLink="false">https://medium.com/p/21d3089b33dc</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[chi2019]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[conference]]></category>
            <dc:creator><![CDATA[Kit Kuksenok]]></dc:creator>
            <pubDate>Tue, 17 Sep 2019 09:34:07 GMT</pubDate>
            <atom:updated>2019-09-17T09:33:40.929Z</atom:updated>
            <content:encoded><![CDATA[<p>When the goal is to design chatbots that are “honest and transparent when explaining why something doesn’t work,”* how do we — <em>practically</em> — do that?In practice, what doesn’t work, and why, can be difficult to find out — let alone explain to the end-user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao3NL5NEtzQW3ELIXKUQJw.png" /><figcaption>Get the PDF of our position paper for a recent workshop on AI and HCI at CHI2019: <a href="https://arxiv.org/abs/1905.03640">https://arxiv.org/abs/1905.03640</a></figcaption></figure><p>At jobpal, explainability means actionable and understandable feedback that helps project managers iterate on a chatbot during design, implementation, and maintenance, and especially improve data quality.</p><p>Earlier this year, we participated at CHI2019 in Glasgow, in <a href="https://michae.lv/ai-hci-workshop/">a workshop on AI and Human-Computer Interaction (HCI)</a> to learn about the most current approaches in Explainable AI (“XAI”) and related topics that might help us to build better, more transparent NLP/ML-based chatbots.</p><p>For the rest of this post, I will focus on the take-aways from the conference about Explainable AI, and apply these ideas to two of the three possible sources of error above: data quality and NLP/ML system improvement.</p><h3><strong>What is Explainable AI?</strong></h3><p>Most of the specific cases and application discussed were about machine learning ( system learns through examples), and some were reinforcement learning ( system learns through feedback). The term “AI” or “AI systems” is useful to refer to a range of systems that use human input and improve over time; but, in this case, it does <em>not</em> mean “general AI”. In all cases, we talked about very concrete forms of process automation or partial automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsFR08BKFAHrvqPR15-ZGQ.png" /><figcaption>When you use <a href="http://m.me/palcareers">our own careers bot</a>, the questions you ask are classified based on an NLP/ML dataset we maintain. We provide the answers to many question topics; those questions that fall outside the known topics will get forwarded to a person.</figcaption></figure><p>In the case of jobpal’s recruitment chatbots, the part that is automated using machine learning is question-answering. The system improves over time as people train it, and <a href="https://jobpal.ai/en/blog/why-data-quality-chatbots-foundation-success/">improve the quality of the example data</a>.</p><p>Many of the “Explainable AI” papers presented at CHI2019 used the term AI this way: it was an AI component that had to be made explainable to the user, but often the technology behind it was ML. For example, Microsoft Research researchers Kocielnik, Amershi, and Bennett in their paper “<a href="http://saleemaamershi.com/papers/chi2019.AI.Expectations.pdf">Will you Accept an Imperfect AI? Exploring Designs for Adjusting End-User Expectations of AI Systems</a>” looked at how end-user acceptance of a meeting scheduler suggestion based on emails was affected by surfacing information about the suggestion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C7tMHXaAb1OX7mAw" /><figcaption>Read the full paper here: <a href="http://saleemaamershi.com/papers/chi2019.AI.Expectations.pdf">http://saleemaamershi.com/papers/chi2019.AI.Expectations.pdf</a></figcaption></figure><p>One finding that particularly stood out to me was that “contrary to expectations from anecdotal reports from practitioners, that user satisfaction and acceptance of a system optimized for … [a] system that make more False Positive mistakes (High Recall)… can be significantly higher than for a system optimized for High Precision. We hypothesize that since users can easily recover from a False Positive in our interface (highlighting can be ignored) than from a False Negative (no highlighting and therefore more careful reading as well as manual scheduling of the meeting required) that the optimal balance of precision and recall is likely in part a function of the cost of recovery from each of these error types.”</p><p>When it comes to chatbots, what is the <strong>cost of recovery</strong> from different types of errors? In this case, a “false positive” could be something like a wrong answer given to a question; and a “false negative” could be deferral to a human even though the question actually is in a dataset. Recovery from a false positive might mean that the end-user rephrases their question; recovery from a false negative might mean that the end-user has to wait to get an answer from a recruiter, which can take some time (<a href="https://jobpal.ai/en/blog/when-do-applicants-approach-you/">half of applicants approach recruitment bots outside of working hours</a>).</p><p>One of the paper authors, Dr. Amershi also co-authored <a href="https://medium.com/microsoft-design/guidelines-for-human-ai-interaction-9aa1535d72b9">Guidelines for Human-AI Interaction</a> with Microsoft Research colleagues, which also stresses that an AI system must “make clear why the system did what it did” (point 11). As a vendor, we have to think about the explanations we provide during the course of iterative design and implementation to all project stakeholders.</p><h3><strong>Problem <em>Solving</em> <em>versus</em> Problem Setting</strong></h3><p>Who is the target audience for explanation depends on the AI system context and problem domain. When the target audience for explanation is the end-user, they encounter the AI system briefly, and the explanation informs how they interpret a short interaction. The workshop’s keynote speaker Dr. <a href="http://www.jennwv.com/">Wortman Vaughan</a> discussed some of the findings from prior work on <a href="http://www.jennwv.com/papers/accuracy-trust.pdf">trust in models</a> among laypeople, and how it’s affected by presenting “stated accuracy.” They found in a sequence of large-scale controlled trials that the system’s stated accuracy influenced perception, but as people used the system and observed its accuracy <em>in practice</em> their own estimations were much more important than what the system stated.</p><p>When I work on explanations of the ML/NLP systems at jobpal, the target audience is other stakeholders in the design an development process, both internally and in external teams we work with. The main distinction between the layperson case above, and the case relevant to B2B chatbot building, was referred to in the workshops as “<strong>problem solving <em>versus </em>problem setting</strong>” — in other words, the stakeholders in the process of chatbot building need to understand the AI system well enough to <strong>propose and enact changes</strong> to it, based on their own respective agendas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*GoOTHz1U78S1ddXC3Un66g.png" /><figcaption>Figure from <a href="https://arxiv.org/abs/1905.03640">our position paper</a> that shows the many responsibilities of project managers at jobpal to bridge external stakeholders and internal technical staff, using a variety of shared documents, such as data quality guidelines.</figcaption></figure><p>One of the challenges I described initially was data quality. As an engineer and researcher, I want high-quality data for interesting experiments and exciting new features — but, as an engineer and researcher, I have no influence on it. In the world of data science, data quality is a major topic, and data <em>cleaning</em> — a time-consuming, necessary, and not particularly fun activity.</p><p>The presentation and paper “<a href="https://fredhohman.com/papers/19-gamut-chi.pdf">Gamut: A Design Probe to Understand How Data Scientists Understand Machine Learning Models</a>” presented a system that was used to explore the same real estate test problem mentioned above in <a href="http://www.jennwv.com/papers/accuracy-trust.pdf">the paper by Dr. Wortman Vaughan</a> but among a different audience of people with some amount of prior exposure to data science or ML. The creators of <em>GAMUT</em> found that their interactive tool was used not only to explore and understand the AI system, but to dig into data quality:</p><ul><li>“<strong>Hypothesis generation. </strong>As participants used Gamut, they constantly generated hypotheses about the data and model while observing different explanations.</li><li>“<strong>Data understanding </strong>… while a predictive model has its own uses, e.g., inference and task automation, many participants explained that they use models to gain insight into large datasets”</li><li><strong>“Communication</strong>. … nearly every participant described a scenario in which they were using model explanations to communicate what features were predictive to stakeholders who wanted to deploy a model in the wild.”</li></ul><p>There are concrete design decisions that can help an interactive system These observations were consistent with one of the main immediate benefits of making our AI system explainable internally: <a href="https://jobpal.ai/en/blog/why-data-quality-chatbots-foundation-success/">improved data quality from day one on projects</a>, resulting not only in better chatbots, but in the opportunity to experiment with ML system improvements in the core product.</p><h3>The Measure of Success</h3><p>I’ve sketched out in the prior sections what explainable AI is, and who is its audience. When it comes to building B2B chatbots, “explainable” means understandable and actionable, and the audience includes the variety of stakeholders involved, on the side of the vendor as well as in the team that is ultimately responsible for chatbot content. When the AI system is understandable and actionable to this audience, they can make informed decisions an actions on not only the NLP data, but also the surrounding conversational flow UX, to provide a better experience to the end-user.</p><p>But what does it mean for an AI system explanation to be successful? <a href="https://michae.lv/ai-hci-workshop/">Workshop</a> participants identified three different, complementary ways of looking at measures of success. First, the person being explained to has a<strong> sense </strong>of understanding. Second, if the person puts their understanding into <strong>action</strong>, it will have the expected effect. Third, the explanation is <strong>true</strong> to how the AI system functions. The second, <em>practical</em> concern is already difficult to articulate and measure in an experimental setting; the third — even more so.</p><p>I started this article by asking what is practically needed to design chatbots that are “<a href="https://designguidelines.withgoogle.com/conversation/conversational-components/errors.html">honest and transparent when explaining why something doesn’t work</a>.” Explainable AI (and related terms) can refer to ongoing research at the intersection of Human-Computer Interaction (HCI) and AI that tries to provide some explanation for AI systems. These systems are not “general AI” but typically ML (with some variation) components of other complex systems. In the case of building recruitment chatbots, ML and NLP inform just one of several aspects of custom chatbot projects.</p><p>*To be “<em>honest and transparent when explaining why something doesn’t work</em>” quotes <a href="https://designguidelines.withgoogle.com/conversation/conversational-components/errors.html">Actions on Google’s design guideline document</a>, and was actually part of the DialogFlow manual since at least 2017 when I first started quoting it. This is basically a good idea and I’ve seen a version of it in almost any design guideline relevant to chatbots, and is deceptively obvious: of course, we can all agree! But <em>then</em> what? It was great to start this conversation internally and draw from so much existing and interesting work, and there is a great deal left to explore in this space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21d3089b33dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/why-and-how-explainable-ai-matters-for-chatbot-design-21d3089b33dc">Why (and How) Explainable AI Matters for Chatbot Design</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>