<?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[Stories by Syed Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Syed Ahmed on Medium]]></description>
        <link>https://medium.com/@nxsyed?source=rss-2a41a487876------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9mW3ktxE-IX1beiQ_WEytA.jpeg</url>
            <title>Stories by Syed Ahmed on Medium</title>
            <link>https://medium.com/@nxsyed?source=rss-2a41a487876------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:04:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nxsyed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What’s holding us back from having a useful quantum computer?]]></title>
            <link>https://medium.com/@nxsyed/whats-holding-us-back-from-having-a-useful-quantum-computer-30c4f5a68529?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c4f5a68529</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[future-technology]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 14:10:06 GMT</pubDate>
            <atom:updated>2024-03-18T14:10:06.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="cat manipulated qubits with its paws" src="https://cdn-images-1.medium.com/max/1024/1*ipcFLIsgUwZeefuZLc8DWw.png" /><figcaption>Is big tech trying to mog us with a low qubit count?</figcaption></figure><p>Every year, we hear a new story come out about Big (old) Tech achieving a new qubit count. IBM most recently reached 433 physical qubits on their osprey machine. Towards the end of last year, Atom computing unveiled their 1180 qubit sci-fi widget that creates qubits by trapping neutral atoms in a 2-dimensional array. In fact, you can run an algorithm on a quantum computer now, yet despite access, there is no demonstration of a killer application</p><p>The past decade of incremental improvements has been dubbed as the Noisy Intermediate-Scale Quantum (NISQ) era. For the normal people in the room, NISQ is a way to say we can’t afford the cheesy crust from pizza hut so we’re eating DiGiorno thin crust instead. Effectively, we’re yet to develop killer applications because the architecture, logic and infrastructure required to build a generation-defining universal quantum is still too far out of reach.</p><p>tbh instead of the qubit count, what should actually matter is:</p><ul><li><strong>when is there even a slight advantage to using a quantum computer? </strong><em>(quantum advantage)</em></li><li><strong>when is a quantum computer is the only option? </strong><em>(quantum supremacy)</em></li></ul><p>**there are plenty of other factors, but we’ll just cover these for now.</p><h3>The quantum advantage with Noisy Intermediate State Quantum (NISQ) algorithms</h3><p>You would think that the “hamiltonian of the system”<strong> </strong>is a term you’d only hear from tumblr girls, but in fact is important in the context of quantum computing<strong>. </strong>Through a Hamiltonian, all the dynamics of a physical system can be described via a set of energies.</p><p>let’s look at the trajectory of the humble basketball.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-8O5vdM9alVtp_M-ldsiw.png" /></figure><p>If we were to simplify the forces acting on the ball, we could say there is the kinetic energy of the ball being thrown and the potential energy of gravity. Now, by summing up all the forces we can get the hamiltonian.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fv7qEKcRiDDTL4Qte6umNF4&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fv7qEKcRiDDTL4Qte6umNF4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="233" height="151" frameborder="0" scrolling="no"><a href="https://medium.com/media/604fb852b8c33d263defb9703067c531/href">https://medium.com/media/604fb852b8c33d263defb9703067c531/href</a></iframe><p>In this basic example, we can learn a lot about a system by understanding the forces acting on it. This same process of identifying energies of a system can be used at the level of quantum mechanics (aka the miniverse). Taking it a few steps further and we can start predicting the behaviour of a system and gaining insights about how the system interacts.</p><p>At this point, you’re probably wondering, why can’t we just do this on a raspberry pi (cheap computer)? The problem arises when we talk about runtime. Meaning, as the physical system grows it takes exponentially longer or computationally large via a classical computer.</p><h3>Noise and decoherence</h3><p>The fundamental building block of a quantum computer is a qubit, which is what we use to store information. Whether it be through a logic gate or an algorithm, we are manipulating these qubits to process information. Just like traditional computers, these qubits create their own errors often in the form of noise and decoherence.</p><p>When we talk about noise, we are talking about anything in the universe that can effect the state of our particle. This could literally be a cosmic ray interfering with our cubit.</p><p>The most prominent effect of noise would be in the form of decoherence. This is when a qubit loses it’s quantum mechanical properties such as <strong>superposition </strong>(existing as 1 or 0 at the same time)<strong> </strong>and<strong> entanglement </strong>(two particles that become linked). When a qubit goes through decoherence it goes back to being a regular particle.</p><p>Many NISQ computers / solutions are designed and built with the intention of solving a specific problem. With a specific focus, they can focus on reducing the noise entering the system and reduce the operations on the qubit to solve that specific task.</p><p>In essence, they are not general purpose quantum computers. An example of this would be D-wave’s quantum computer, as they’ve specifically built a quantum processing unit that solves problems via a process known as quantum annealing.</p><p>the main tradeoff between a purpose built quantum computer or a universal computer is control. In a universal quantum computer, developers can create their own algorithms via gate operations and submit them to a universal quantum computer. This allows much greater flexibility in the type of algorithms you can run as well as the data you can process.</p><p>The caveat being, when you gain control via gate operations you introduce the opportunity of noise and decoherence since the gates may apply different operations each time.</p><h3>Quantum error correction (QEC) and reaching fault tolerance (FT)</h3><p>For us to address the factors effecting noise in our system, we would need to develop some sort of architecture for error-correction. This architecture involved using many <strong>physical </strong>qubits to encode one <strong>logical </strong>qubit. Meaning, when we run operations on a logical qubit, there is some built in redundancy to make sure the qubit doesn’t experience decoherence or any other error while our algorithm is running.</p><p>In an effort to run complex computation, we not only have to build in error-correction but also scale the logical qubit count to handle complex algorithms. Depending on the QEC scheme, the number of physical qubits per logical cubit could but many multiples more. That’s why many researchers say we would need millions of qubits to reach a fault tolerant quantum computer.</p><p>No matter which way you look at it, there are multiple incredibly challenging hurdles that are holding back the physical development of a useful quantum computer.</p><p>But I think in a world where a quantum computer exists, it doesn’t matter whether it can perform these operations if there isn’t a meaningful transition from academia to people actually building quantum solutions.</p><p>Some might argue that quantum education will naturally come as the economic opportunity materializes. To which I agree, and in fact, we do have great content and papers available for the average developer / engineers to understand quantum computing. That being said, the access to information shouldn’t detract from barrier of entry to understanding that information.</p><p>Quantum computing remains an elusive niche which makes it hard to discern reality from marketing. So, while there maybe complex technical hurdles that are holding back a useful quantum computer, we should be aware that without the access to the right information, we can’t make anything useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c4f5a68529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing single qubit state using Bloch spheres with rust]]></title>
            <link>https://medium.com/@nxsyed/visualizing-single-qubit-state-using-bloch-spheres-with-rust-9b1ea7980f87?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b1ea7980f87</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 09:07:04 GMT</pubDate>
            <atom:updated>2024-02-26T09:16:08.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A cat in black in white encased in a bloch sphere trying to represent phase shift" src="https://cdn-images-1.medium.com/max/1024/1*BiAVs8UG4Gv0IrIPyRUVKA.jpeg" /><figcaption>do you think quantum cats like lasagna?</figcaption></figure><h3>Visualizing single qubit states using Bloch spheres with rust</h3><p>When we were looking at logic gates in rust, we saw that a qubit has a probability of being either 1 or 0. We can use complex numbers (<em>α,β) </em>to describe the amplitude (probability) of a qubit being in either the ∣0⟩ state or ∣1⟩ state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fw1NvEW1qaxFEfRCFchHe5K&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fw1NvEW1qaxFEfRCFchHe5K&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="160" frameborder="0" scrolling="no"><a href="https://medium.com/media/08163dc7f6a9347ec58286026cf2db1d/href">https://medium.com/media/08163dc7f6a9347ec58286026cf2db1d/href</a></iframe><p>In fact, we can define the ∣0⟩ state or ∣1⟩ state as vectors.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fk5vfuko8n9UWmi9ccXUVzS&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fk5vfuko8n9UWmi9ccXUVzS&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="112" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9a832768da358ae41fa9138d7a6c15/href">https://medium.com/media/6b9a832768da358ae41fa9138d7a6c15/href</a></iframe><p>Now, by normalizing our amplitudes we can measure the probability of the qubit being in either state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fa9HvtAnib6yhyhnrjiTFTd&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fa9HvtAnib6yhyhnrjiTFTd&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="352" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff33714b3e9ba532c3266e9fc41131a/href">https://medium.com/media/5ff33714b3e9ba532c3266e9fc41131a/href</a></iframe><p>When we looked at the Pauli X gate and the Hadamard gate we were applying those gates on to the single qubit state. Both these gates are easier to understand since they are analogous to the gates available in classical computing.</p><p>filename: src/qubit.rs</p><pre><br>pub struct QuantumCat {<br>    pub asleep_amplitude: Complex&lt;f64&gt;,<br>    pub awake_amplitude: Complex&lt;f64&gt;,<br>}<br><br>impl QuantumCat {<br>    // Initializes a qubit given the amplitudes for |0⟩ and |1⟩ states.<br>    // Note: In a real scenario, you&#39;d want to add checks to ensure that<br>    // the amplitudes satisfy the normalization condition.<br>    pub fn new(asleep_amplitude: Complex&lt;f64&gt;, awake_amplitude: Complex&lt;f64&gt;) -&gt; Self {<br>      QuantumCat {<br>          asleep_amplitude,<br>          awake_amplitude,<br>      }<br>  }<br>    <br>    // Example method to represent the measurement of a qubit.<br>    // This is a simplification and not how actual quantum measurement works.<br>    pub fn measure(&amp;self) -&gt; String {<br>        if self.asleep_amplitude.norm_sqr() &gt; self.awake_amplitude.norm_sqr() {<br>            &quot;|0⟩&quot;.to_string()<br>        } else {<br>            &quot;|1⟩&quot;.to_string()<br>        }<br>    }<br><br>  // Pauli-X Gate: Flips the cat&#39;s state from asleep to awake or vice versa<br>  pub fn pauli_x(&amp;self) -&gt; Self {<br>    Self::new(self.awake_amplitude, self.asleep_amplitude)<br>  }<br><br>  pub fn hadamard(&amp;self) -&gt; Self {<br>    let factor = Complex::new(1.0 / f64::sqrt(2.0), 0.0);<br>    Self::new(<br>        (self.asleep_amplitude + self.awake_amplitude) * factor,<br>        (self.asleep_amplitude - self.awake_amplitude) * factor,<br>    )<br>  }</pre><p>The Hadamard gate being the most subtle introduction to quantum algorithms since it demonstrates superposition by entering our quantum cat into the in-between state of being asleep and awake.</p><pre>After Hadamard: Asleep amplitude: 0.7071067811865475+0i, Awake amplitude: 0.7071067811865475+0i</pre><p>While we’ve had a chance to see the effect of gates in respect to the probability of a qubit being between 1 and 0, there are other gates that change our qubit but the probabilities aren’t effected.</p><h3>Qubit operations on a Bloch sphere</h3><p>If we were to take the state of a qubit and put it into a shape, the best way to describe it would be a sphere. The Bloch sphere is that representation of a qubit with all the quantum lingo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*aWMUb0cKABnFfR9Jvi_8cw.png" /><figcaption>Bloch sphere of qubit in a 0 state</figcaption></figure><p>The point on the Bloch sphere is the probability of outcome. In the diagram above, the probability of the measurement being 0 is 1.</p><p>We can use the same single qubit state and represent it as a point on the Bloch sphere. <em>θ </em>represents the probability of measuring 0 or 1, while <em>ϕ </em>is the phase shift.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FgFaDeUxP3MEii9jn5jUd8t&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FgFaDeUxP3MEii9jn5jUd8t&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="295" height="158" frameborder="0" scrolling="no"><a href="https://medium.com/media/81eee8845ea1fec3f057707699532d31/href">https://medium.com/media/81eee8845ea1fec3f057707699532d31/href</a></iframe><p>What happens to that qubit when we apply the x-gate (quantum NOT) on a zero state qubit?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*PkeMN6mp8dvukyCrJ13aZA.gif" /><figcaption>bloch sphere visualization of x-gate operation on a qubit</figcaption></figure><p>In the animation above you can see how applying the X gate operation flips the amplitude of both 0 and 1. In this case, the phase factor is unchanged while <em>θ </em>now equals <em>π.</em></p><h3>Phase shift on a single qubit</h3><p>The gates we’ve dissected so far apply a change to the probability of measuring a 0 or 1. There are some gates that apply an operation to a qubit but don’t change the probability of measuring a 0 or 1. Both the S gate and T gate have an affect on only the phase factor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*7qE_c7XVn5RV3d_II5vvww.gif" /><figcaption>Bloch sphere visualization of S-gate and T-gate operation on a qubit</figcaption></figure><p>There are a few gates that apply a phase factor in their operations.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FoyVpcGe3JHsxLR6G419f55&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FoyVpcGe3JHsxLR6G419f55&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="545" height="159" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fa0cf8104e1f636fab361b523ac07cd/href">https://medium.com/media/1fa0cf8104e1f636fab361b523ac07cd/href</a></iframe><p>When we apply the s-gate on a qubit state we end up with a state vector with a phase shift.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FaJXaJ2rZYBy5JiaL7SVJmb&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FaJXaJ2rZYBy5JiaL7SVJmb&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="128" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc9cddf36373e3f7e7c7d606a585caa2/href">https://medium.com/media/bc9cddf36373e3f7e7c7d606a585caa2/href</a></iframe><p>try to apply the T† on a qubit state and see what the affect is.</p><h3>Apply multiple gates with phase shift</h3><p>You might be wondering, what would be a scenario where a phase factor has an effect on the final probability of a qubit measuring 0 or 1?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwa5QhxHUGMWbhncv965-g.gif" /></figure><p>the Hadamard gate puts our qubit into superposition, meaning the probability of measuring a 0 or 1 is somewhere in between.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FnyNrKHyWgNcHkMbgso2cnu&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FnyNrKHyWgNcHkMbgso2cnu&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="156" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2fe7519a2c4d5043f11575ffdd6d8d/href">https://medium.com/media/eb2fe7519a2c4d5043f11575ffdd6d8d/href</a></iframe><p>the Z gate on the other hand is used to apply a 180 degree rotation around the z axis. The matrix for the Z gate shows us that this operation is only done on the ∣1⟩ component, leaving the ∣0⟩ component unchanged.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FuKiYEi9CgqMdcdHhRfWLJx&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FuKiYEi9CgqMdcdHhRfWLJx&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="160" frameborder="0" scrolling="no"><a href="https://medium.com/media/46b1525061af8679e9a7c641892edd30/href">https://medium.com/media/46b1525061af8679e9a7c641892edd30/href</a></iframe><p>Now if we apply the Z gate, we can see that the result is the Hadamard operation but now the phase for the ∣1⟩ component is flipped.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F4CwPqfCk5WBc7nqYFi8Jss&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F4CwPqfCk5WBc7nqYFi8Jss&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="470" height="158" frameborder="0" scrolling="no"><a href="https://medium.com/media/65d2f67ce2afb4b3d07382016f75d57a/href">https://medium.com/media/65d2f67ce2afb4b3d07382016f75d57a/href</a></iframe><p>Finally, by applying another Hadamard, we can see how the operations we perform are equivalent to performing the X gate.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F5z4eZBk8jDdiArzjDXtLMd&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F5z4eZBk8jDdiArzjDXtLMd&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="756" height="256" frameborder="0" scrolling="no"><a href="https://medium.com/media/5503a71e3ba855ce1518ff997e5f7084/href">https://medium.com/media/5503a71e3ba855ce1518ff997e5f7084/href</a></iframe><p>Interesting use cases for phase shift come to light when we look at entanglement and interference with circuits using more than one qubit. For now, we’ll implement the various gates and explore entanglement later.</p><h3>S gate and T gate functions in rust</h3><p>We have a basic understanding of the effects of phase shift, so let’s go ahead and create some simple functions to apply a S gate and T gate.</p><p>filename: src/qubit.rs</p><pre>use num_complex::Complex;<br><br>pub struct QuantumCat {<br>    pub asleep_amplitude: Complex&lt;f64&gt;,<br>    pub awake_amplitude: Complex&lt;f64&gt;,<br>}<br><br>impl QuantumCat {<br>    // rest of our quantum cat code<br><br>    pub fn phase_shift(&amp;self, phi: f64) -&gt; Self {<br>        Self::new(<br>            self.asleep_amplitude,<br>            self.awake_amplitude * Complex::new(phi.cos(), phi.sin()),<br>        )<br>    }<br><br>    // S-gate<br>    pub fn s_gate(&amp;self) -&gt; Self {<br>        self.phase_shift(std::f64::consts::PI / 2.0)<br>    }<br><br>    // T-gate<br>    pub fn t_gate(&amp;self) -&gt; Self {<br>        self.phase_shift(std::f64::consts::PI / 4.0)<br>    }<br><br>}</pre><p>We’ve created three functions in the example above.</p><p>The first function phase_shift takes an input of the phase factor <em>ϕ (phi) </em>while the s_gate and t_gate functions provide the respective phase factors for each operations.</p><p>You’ll notice that the phase factor for the s_gate is <em>π</em>/2 and for the t_gate it&#39;s <em>π</em>/4. That’s because when these gates are applied the phase shift is equivalent to those degrees.</p><p>knowing this, let’s create a z_gate function and verify that applying the following circuit is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*0tzJQWQ_HCGT-Clztk03LA.png" /></figure><pre>    // Z-Gate<br>    pub fn z_gate(&amp;self) -&gt; Self {<br>      self.phase_shift(std::f64::consts::PI)<br>    }</pre><p>By using the same phase_shift function from earlier we can apply the phase shift from the z gate which would be <em>π.</em></p><p>Before we test our functions, you can confirm we’re using the same QuantumCat struct.</p><p>filename: src/qubit.rs</p><pre>use num_complex::Complex;<br><br>pub struct QuantumCat {<br>    pub asleep_amplitude: Complex&lt;f64&gt;,<br>    pub awake_amplitude: Complex&lt;f64&gt;,<br>}<br><br>impl QuantumCat {<br>    // Initializes a qubit given the amplitudes for |0⟩ and |1⟩ states.<br>    // Note: In a real scenario, you&#39;d want to add checks to ensure that<br>    // the amplitudes satisfy the normalization condition.<br>    pub fn new(asleep_amplitude: Complex&lt;f64&gt;, awake_amplitude: Complex&lt;f64&gt;) -&gt; Self {<br>        QuantumCat {<br>            asleep_amplitude,<br>            awake_amplitude,<br>        }<br>    }<br><br>    // Example method to represent the measurement of a qubit.<br>    // This is a simplification and not how actual quantum measurement works.<br>    pub fn measure(&amp;self) -&gt; String {<br>        if self.asleep_amplitude.norm_sqr() &gt; self.awake_amplitude.norm_sqr() {<br>            &quot;|0⟩&quot;.to_string()<br>        } else {<br>            &quot;|1⟩&quot;.to_string()<br>        }<br>    }<br><br>    // Pauli-X Gate: Flips the cat&#39;s state from asleep to awake or vice versa<br>    pub fn x_gate(&amp;self) -&gt; Self {<br>        Self::new(self.awake_amplitude, self.asleep_amplitude)<br>    }<br><br>    pub fn hadamard(&amp;self) -&gt; Self {<br>        let factor = Complex::new(1.0 / f64::sqrt(2.0), 0.0);<br>        Self::new(<br>            (self.asleep_amplitude + self.awake_amplitude) * factor,<br>            (self.asleep_amplitude - self.awake_amplitude) * factor,<br>        )<br>    }<br><br>    pub fn phase_shift(&amp;self, phi: f64) -&gt; Self {<br>        Self::new(<br>            self.asleep_amplitude,<br>            self.awake_amplitude * Complex::new(phi.cos(), phi.sin()),<br>        )<br>    }<br><br>    // S-gate<br>    pub fn s_gate(&amp;self) -&gt; Self {<br>        self.phase_shift(std::f64::consts::PI / 2.0)<br>    }<br><br>    // T-gate<br>    pub fn t_gate(&amp;self) -&gt; Self {<br>        self.phase_shift(std::f64::consts::PI / 4.0)<br>    }<br><br>    // Z-Gate<br>    pub fn z_gate(&amp;self) -&gt; Self {<br>      self.phase_shift(std::f64::consts::PI)<br>    }<br>}</pre><p>we can test the quantum circuit by applying the gates on one qubit then comparing to another qubit with just the z gate applied.</p><p>filename: src/main.rs</p><pre>use quantum_gates::QuantumCat;<br>use num_complex::Complex;<br><br>fn main() {<br>    // Initialize QuantumCat in the |0&gt; state<br>    let cat = QuantumCat::new(Complex::new(1.0, 0.0), Complex::new(0.0, 0.0));<br>    <br>    // Apply HZH sequence<br>    let cat_hzh = cat.hadamard().z_gate().hadamard();<br>    <br>    // Apply X gate<br>    let cat_x = cat.x_gate();<br><br>    // Compare the results<br>    println!(&quot;Final state after HZH: {}&quot;, cat_hzh.measure());<br>    println!(&quot;Final state after X gate: {}&quot;, cat_x.measure());<br>}</pre><p>Our output should show how both sets of operations are equivalent;</p><pre>Final state after HZH: |1⟩<br>Final state after X gate: |1⟩</pre><h3>Next steps</h3><p>Hopefully we have a better understanding of using Bloch sphere and how phase shifts can possibiliy effect a single qubit state. Here are some things you can do to get a better understanding.</p><ul><li>Create the functions for T† and S† gates</li><li>Apply the various phase shift matrix’s to see how phi changes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b1ea7980f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum computing logic gates in rust]]></title>
            <link>https://medium.com/@nxsyed/quantum-computing-logic-gates-in-rust-2d406d596cd4?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d406d596cd4</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 12:08:45 GMT</pubDate>
            <atom:updated>2024-02-10T21:56:01.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cat representing a qubit going through a cosmic quantum gate" src="https://cdn-images-1.medium.com/max/1024/1*oOscWc3iAziI3qqmG-RVjg.png" /><figcaption>Watch as a quantum cat peers through the quantum gate</figcaption></figure><p>For the uninitiated in the quantum computing world, as I was, there’s one thing we have to swear by: everything we know about computing till now will be known as “classical computing” moving forward. The reason for this is because quantum computers allow us to solve problems that are impossible to solve with our current form of computing. Below I’ve made a fictional graph to confirm my bias.</p><figure><img alt="Fictional graph about quantum computing vs classical computing" src="https://cdn-images-1.medium.com/max/1024/1*87Ef4fpUU7Xd2WaEg5QppQ.png" /><figcaption>Fictional graph about quantum computing vs classical computing</figcaption></figure><p>Other than the physical limitation of classical computing, in the race to quantum supremacy we must also dominate the collective lingo-sphere by negging all blockchain developers by referring to them as “retro software developers”.</p><p>In classical computing, we think of an output as a collection of bits in the form of 0s or 1s. To be more specific, a <em>discrete</em> output. Take a step back and we have a gate which manipulates these bits based on a set of operations.</p><h3>What are the classical logic gates</h3><p>Here’s a quick refresh on classical gates. If you have questions, post them in the bottom so we can boost the engagement on this article.</p><ul><li><strong>NOT Gate:</strong> Flips the input bit. i.e 0 becomes 1</li></ul><pre>fn not_gate(input: bool) -&gt; bool {<br>    !input<br>}</pre><ul><li><strong>AND Gate:</strong> Outputs 1 if both inputs are 1.</li></ul><pre>fn and_gate(input1: bool, input2: bool) -&gt; bool {<br>    input1 &amp;&amp; input2<br>}</pre><ul><li><strong>OR Gate:</strong> Outputs 1 if at least one input is 1.</li></ul><pre>fn or_gate(input1: bool, input2: bool) -&gt; bool {<br>    input1 || input2<br>}</pre><ul><li><strong>XOR Gate (Exclusive OR):</strong> Outputs 1 if exactly one of the inputs is 1.</li></ul><pre>fn xor_gate(input1: bool, input2: bool) -&gt; bool {<br>    input1 ^ input2<br>}</pre><h3>Representing a quantum bit using classical bits</h3><p>To actually use and work with a qubit on a classical computer we need to bake in the functionality of superposition. A good data structure for this purpose often involves complex numbers, as they can represent the probability amplitudes for a qubit being in the |0⟩ or |1⟩ state. A qubit’s state can be written as |ψ⟩ = α|0⟩ + β|1⟩, where α and β are complex numbers satisfying the condition |α|² + |β|² = 1.</p><p>For these examples, to make it easier to understand, instead of a qubit we’re going to represent a cat. Instead of 0s and 1s, the cat is going to be either |Asleep⟩ and |Awake⟩. Similar to a qubit, our quantum cat can be in a superposition of being both asleep and awake until observed.</p><p>Let’s start by create a new rust project.</p><pre>cargo new quantum_gates<br>cd ./quantum_gates/</pre><p>We’re going to be using the num-complex crate, so let’s add it to our project.</p><pre>cargo add num-complex</pre><p>Now inside the src folder of our new rust project we can create a data structure representing a qubit.</p><p>filename: src/qubit.rs</p><pre>use num_complex::Complex;<br><br>pub struct QuantumCat {<br>    pub asleep_amplitude: Complex&lt;f64&gt;,<br>    pub awake_amplitude: Complex&lt;f64&gt;,<br>}<br><br>impl QuantumCat {<br>    // Initializes a qubit given the amplitudes for |0⟩ and |1⟩ states.<br>    // Note: In a real scenario, you&#39;d want to add checks to ensure that<br>    // the amplitudes satisfy the normalization condition.<br>    pub fn new(asleep_amplitude: Complex&lt;f64&gt;, awake_amplitude: Complex&lt;f64&gt;) -&gt; Self {<br>      QuantumCat {<br>          asleep_amplitude,<br>          awake_amplitude,<br>      }<br>  }<br>    <br>    // Example method to represent the measurement of a qubit.<br>    // This is a simplification and not how actual quantum measurement works.<br>    pub fn measure(&amp;self) -&gt; String {<br>        if self.asleep_amplitude.norm_sqr() &gt; self.awake_amplitude.norm_sqr() {<br>            &quot;|0⟩&quot;.to_string()<br>        } else {<br>            &quot;|1⟩&quot;.to_string()<br>        }<br>    }<br><br>}</pre><p>Let’s make it so that we can access it from the rest of our program.</p><p>filename: src/lib.rs</p><pre>mod qubit;<br>pub use qubit::QuantumCat;</pre><p>We can confirm that our quantum cat is operating correctly by initializing a cat with a |Asleep⟩ amplitude (probability) of 100% and a |Awake⟩amplitude of 0%. A qubit in this state can also be referred to being in a “ground state”. We can represent the qubit via bra-ket notation:</p><p>∣<em>ψ</em>⟩=1∣Asleep⟩+0∣Awake⟩</p><p>In a classical computer, this state would simply be “0”. Let’s create the qubit and measure it’s state.</p><p>filename: src/main.rs</p><pre>use quantum_gates::QuantumCat;<br>use num_complex::Complex;<br><br>fn main() {<br>    let initial_cat = QuantumCat::new(Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)); // Definitely asleep<br>    println!(&quot;Cat sleep measurement: {}&quot;, initial_cat.measure());<br>}</pre><p>If all went according to plan, when we run cargo run we should get the following output.</p><pre>Cat sleep measurement: |0⟩</pre><h3>Quantum Logic Gates</h3><p>In contrast to classical gates, quantum gates, operate on qubits using the principles of quantum mechanics. From what we lightly touched on earlier, qubits have amplitudes for each state. There are multiple unique characteristics of qubits that we can take advantage of via logic gates.</p><h4><strong>Pauli gates</strong></h4><p>— <strong>X Gate (Quantum NOT Gate):</strong> The X gate acts as a quantum NOT gate, flipping the state of a qubit. Similar to a classical NOT gate but for qubits.</p><p><em>X</em>∣Asleep⟩=∣Awake⟩ and <em>X</em>∣Awake⟩=∣Asleep⟩</p><p>We can update our quantum cat struct to now include a function that changes the cat’s state from asleep to awake.</p><p>filename: src/qubit.rs</p><pre>// struct code<br><br>impl QuantumCat {<br>   //... new() &amp; measure() functions<br><br><br>   // Pauli-X Gate: Flips the cat&#39;s state from asleep to awake or vice versa<br>   pub fn pauli_x(&amp;self) -&gt; Self {<br>    Self::new(self.awake_amplitude, self.asleep_amplitude)<br>  }<br>}</pre><p>Now if we perform this operation on our cat, we can see the state change from ∣Asleep⟩ to ∣Awake⟩.</p><p>filename: src/main.rs</p><pre>use quantum_gates::QuantumCat;<br>use num_complex::Complex;<br><br>fn main() {<br>    let initial_cat = QuantumCat::new(Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)); // Definitely asleep<br><br>    // Apply Pauli-X Gate: The cat wakes up<br>    let awake_cat = initial_cat.pauli_x();<br>    println!(&quot;After Pauli-X: Asleep amplitude: {}, Awake amplitude: {}&quot;, awake_cat.asleep_amplitude, awake_cat.awake_amplitude);<br><br>}</pre><p>When we run cargo run ;</p><pre>After Pauli-X: Asleep amplitude: 0+0i, Awake amplitude: 1+0i</pre><h4><strong>Other gates</strong></h4><p><strong>Hadamard Gate (H Gate): </strong>Puts a qubit into a superposition, enabling it to be in a combination of |0⟩ and |1⟩ states, crucial for quantum parallelism.</p><p>Applying the Hadamard gate to a cat that’s definitely asleep (|Asleep⟩) would result in the cat being in a state of both asleep and awake. It’s like the cat is dreaming about chasing mice, existing in a blurry line between sleep and wakefulness.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fkr7ZH2rv9Fq2hzY4rF6qwa&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fkr7ZH2rv9Fq2hzY4rF6qwa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="268" height="156" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7e71a5852421b90d72d277095d5418d/href">https://medium.com/media/a7e71a5852421b90d72d277095d5418d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fb48adyoRwb9PBoQXyEerBs&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fb48adyoRwb9PBoQXyEerBs&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="268" height="156" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a214ebee196642e78e83a281c56dfbd/href">https://medium.com/media/5a214ebee196642e78e83a281c56dfbd/href</a></iframe><p>Here’s how the hadamard operation would look like in rust.</p><p>filename: src/qubit.rs</p><pre>// struct code<br><br>impl QuantumCat {<br>   //... new() &amp; measure() functions<br><br>   pub fn hadamard(&amp;self) -&gt; Self {<br>    let factor = Complex::new(1.0 / f64::sqrt(2.0), 0.0);<br>    Self::new(<br>        (self.asleep_amplitude + self.awake_amplitude) * factor,<br>        (self.asleep_amplitude - self.awake_amplitude) * factor,<br>    )<br>  }<br>}</pre><p>let’s see how the hardamard effects the state of the cat.</p><p>filename: src/main.rs</p><pre>use quantum_gates::QuantumCat;<br>use num_complex::Complex;<br><br>fn main() {<br>    let initial_cat = QuantumCat::new(Complex::new(1.0, 0.0), Complex::new(0.0, 0.0)); // Definitely asleep<br><br>    // Apply Pauli-X Gate: The cat wakes up<br>    let awake_cat = initial_cat.pauli_x();<br>    println!(&quot;After Pauli-X: Asleep amplitude: {}, Awake amplitude: {}&quot;, awake_cat.asleep_amplitude, awake_cat.awake_amplitude);<br><br>    // Apply Hadamard Gate: The cat is now in a superposition of asleep and awake<br>    let superposition_cat = initial_cat.hadamard();<br>    println!(&quot;After Hadamard: Asleep amplitude: {}, Awake amplitude: {}&quot;, superposition_cat.asleep_amplitude, superposition_cat.awake_amplitude);<br><br>}</pre><p>Now if we look at the output, we can see that the cat is in some inbetween state.</p><pre>After Hadamard: Asleep amplitude: 0.7071067811865475+0i, Awake amplitude: 0.7071067811865475+0i</pre><p><strong>Controlled-NOT Gate (CNOT): </strong>A two-qubit gate where the state of the second qubit (target) is flipped if the first qubit (control) is in the |1⟩ state. It’s fundamental for creating entangled states, where the state of one qubit is dependent on the state of another.</p><p><em>CX</em>∣00⟩=∣00⟩, <em>CX</em>∣01⟩=∣01⟩, <em>CX</em>∣10⟩=∣11⟩, <em>CX</em>∣11⟩=∣10⟩</p><p><strong>Phase Shift Gates:</strong> Changes the phase of a qubit without affecting its amplitude.</p><p>For a quantum cat, this might mean adjusting the “mood” of its superposition without changing whether it’s more asleep or awake. If our cat was in a balanced superposition of |Asleep⟩ and |Awake⟩, applying a Phase Shift gate could make its state lean emotionally more towards one, like being in a superposition but with a dreamy (positive phase) or a nightmare (negative phase).</p><p><em>Rϕ</em>​∣0⟩=∣0⟩ and <em>Rϕ</em>​∣1⟩=<em>eiϕ</em>∣1⟩</p><h3>Importance in Quantum Computing</h3><p>These gates enable quantum computers to perform complex calculations more efficiently than classical computers in some specific tasks, such as factoring large numbers (important for cryptography) or simulating quantum physical processes. The superposition and entanglement properties of qubits allow for the exploration of computational paths in parallel, offering potential speedups for certain types of algorithms.</p><h3>Challenges</h3><p>Quantum computing faces challenges like decoherence (loss of quantum state) and the probabilistic nature of qubit measurement, making quantum error correction and algorithm design both crucial and complex.</p><p>In essence, quantum logic gates allow quantum computers to leverage the principles of quantum mechanics for processing information in ways that classical logic gates and computers cannot, promising breakthroughs in various fields, albeit with significant technical hurdles to overcome.</p><h3>Next steps</h3><p>Now that you know how to implement some basic gates in rust, try to implement the other gates such as Phase shift and CNOT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d406d596cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Smart Contracts? A Hands-on Approach]]></title>
            <link>https://medium.com/better-programming/what-are-smart-contracts-a-hands-on-approach-9fc6e02abaa2?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fc6e02abaa2</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Fri, 30 Aug 2019 15:01:01 GMT</pubDate>
            <atom:updated>2020-04-15T23:24:44.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Are Smart Contracts? A Hands-On Approach</h3><h4>Let’s clear up all the confusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKbyJPBrMqCdGOikwj5feA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Distel</a> on <a href="https://unsplash.com/s/photos/blockchain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Information asymmetry was the most significant hidden problem before the internet. We couldn’t contrast and compare prices. People had to go to brokers who would quote them on a price which the consumer had to assume was correct.</p><p>Travel brokers, real estate agents, and car salespeople were perfect examples of how people took advantage of information asymmetry. Consumers had to bring prior knowledge to the table to be able to negotiate on price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQjgf9k5GZQV087D6uKP2A.png" /></figure><p>Only recently did we get resources such as Kayak and Autotrader that let the consumer take control of information.</p><p>They can now reap the benefits of knowing competitive prices for goods or services. Ultimately, giving room for consumers to win by saving money on the things they buy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWUAPum9SSTDdseuR32aXA.png" /></figure><p>Understanding information asymmetry helps us begin to understand how distributed technologies like blockchain could start to paint a clearer picture for consumers by creating trust.</p><p>Blockchain provides a collection of independent machines working towards recording, sharing, and synchronizing transactions. These machines are part of the system of information sharing, letting more and more consumers converge towards information symmetry.</p><p>In this application of blockchain, smart contracts play a vital role in executing the agreement between the two parties.</p><p>Transactions aren’t the only thing smart contracts can be used for. We’ll be looking at smart contracts and how we can use them to interact with the blockchain.</p><h3>What are Smart Contracts?</h3><p>Smart contracts are a layer of logic on a distributed and decentralized blockchain network which outlines the agreement between at least two parties.</p><p>A smart contract is always written in code and automatically executes when the buying party accepts the deal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*694HxgFzaFfnkmc_p2wVYg.png" /></figure><p>The smart contract flow above is specific to the information asymmetry use case we explored earlier.</p><p>It’s important to note that smart contracts don’t always have to be agreements and are primarily code for writing and reading from the blockchain.</p><p>Similar to the case of information asymmetry, a smart contract makes it transparent for a buyer to know the terms of the transaction. In the case of a travel broker, the price of the flight package would manifest through the contract.</p><p>The technical operation that a smart contract executes is allowing your application to write to the blockchain. In the case of a car dealership, a smart contract could be used to update the value you’ve agreed on for the car, or even pay for the vehicle itself.</p><p>Now, let’s look at what smart contracts look like and have a live application running.</p><h3>How to Code a Smart Contract</h3><p>There are a couple of key players in the blockchain space that make it easier to create smart contracts and decentralized applications. We’ll be exploring how to create a smart contract using <a href="https://studio.nearprotocol.com/">NEAR Studio</a>.</p><p>Before we write any actual code, we need to choose where we’re going to write the code. The best option for developers looking to get their feet wet with developing smart contracts is the Near Studio IDE because it creates a ready to go environment from the start.</p><p>Keep in mind that you need to know a bit of JavaScript and possibly some TypeScript to go with it. If not, don’t worry as we’ll be breaking everything down into simple and easy-to-understand terms.</p><p>Now, if you head over to Near Studio, you’ll find that you can create a new project from a list of templates.</p><p>Select the “Counter Smart Contract” project. The counter template creates a basic TypeScript application that increments, decrements, and fetches a counter variable.</p><p>This example is perfect as it shows us how smart contracts are not always just agreements. They hold our back-end logic for use with the blockchain as a database.</p><p>Selecting the template creates the application, and now, if we head over to assembly/main.ts using the file explorer on the left, we can see the counter code for our smart contract.</p><p>You can take a couple of minutes to explore the functionality of this template by clicking the <em>run</em> command in the top toolbar and navigating to the new window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XokNi2b4V3cTWFYS" /></figure><p>Then, in the new window, you can test out the commands by opening up the console and entering the commands shown on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gypMOYsDL3GlGLgZ" /></figure><p>Now, let’s have a look at the assembly/main.ts file, line-by-line.</p><pre>import { context, storage, near } from “./near”;</pre><p>The importing statement adds all the library classes we’ll need for the functionality of our app to work. If we want to see what the imported classes do, we can navigate to the “near” folder and find the correct class.</p><p>The first function we should see when we open main.ts is the increment function.</p><pre>export function incrementCounter(): void {</pre><pre> let newCounter = storage.get &lt; i32 &gt; “counter” + 1;</pre><pre>  storage.set &lt; i32 &gt; (“counter”, newCounter);</pre><pre>  near.log(“Counter is now: “ + newCounter.toString());</pre><pre>}</pre><p>The function executes three steps. First, we get an integer value with the key “counter” and add 1 to it. The counter variable looks like this in storage before the increment function:</p><pre>{</pre><pre>  counter: 0</pre><pre>}</pre><p>Once we increment, the value looks like this:</p><pre>{</pre><pre>  counter: 1</pre><pre>}</pre><p>The logical question now is: “How do we decrement by 1?”</p><pre>export function decrementCounter(): void {</pre><pre>  let newCounter = storage.get &lt; i32 &gt; “counter” — 1;</pre><pre>  storage.set &lt; i32 &gt; (“counter”, newCounter);</pre><pre>  near.log(“Counter is now: “ + newCounter.toString());</pre><pre>}</pre><p>The first step is to get the current value for “counter” and reduce it by 1. Then we send the new value to the same counter variable in the blockchain.</p><p>This is how counter changes before we decrement:</p><pre>{</pre><pre>  counter: 1</pre><pre>}</pre><p>This is how counter changes after we decrement:</p><pre>{</pre><pre>  counter: 0</pre><pre>}</pre><p>The last function takes the crux of the previous functions, getting the counter variable, and returns that value.</p><pre>export function getCounter(): i32 {</pre><pre>  return storage.get &lt; i32 &gt; “counter”;</pre><pre>}</pre><p>The main.ts creates and exports the functionality we need, but for our users to use and see our feature, we’ll need to import those functions and frame our front end with our new functionality.</p><h3>Using JavaScript and HTML to Show Data From the Blockchain</h3><p>Now that we have our back end set up, it’s helpful to write some front end to interact with the “smart contract” we wrote.</p><p>There isn’t a requirement to use any specific framework or library, so we’ll work with Vanilla JavaScript and HTML, but you could use any framework/library you’re comfortable with.</p><p>For us to access the functions we were looking at, we’ll need to modify our src/main.js by finding the window.contract initialization.</p><pre>window.contract = await near.loadContract(nearConfig.contractName, {</pre><pre>  viewMethods: [“getCounter”],</pre><pre>  changeMethods: [“incrementCounter”, “decrementCounter”],</pre><pre>  sender: window.walletAccount.getAccountId()</pre><pre>});</pre><p>The viewMethods key is assigned the functions that return a value. In contrast, the changeMethods key is related to all the functions that write to storage.</p><p>Now, inside the same src/main.js, we can create a function that inserts the current counter value to our index.html page.</p><pre>async function displayCounter(){</pre><pre>  let counter = await contract.getCounter();</pre><pre>  document.getElementById(‘counter’).innerText = counter; </pre><pre>  console.log(counter);</pre><pre>}</pre><p>Then, in the src.index.html file, we can add a button inside the after-sign-in div, which shows the value of the counter variable.</p><pre>&lt;div&gt;</pre><pre>  &lt;label&gt;Counter:&lt;/label&gt;</pre><pre>  &lt;p id=”counter” /&gt;</pre><pre>  &lt;button onClick={displayCounter()}&gt;Get Counter&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><p>Now you can hit the <em>run</em> button in the menu to the top of the IDE to see what the app looks like and, hopefully, it should look something similar to what I’ve made in NEAR Studio:</p><ul><li><a href="https://app.near.ai/app/52d7s4s1w/">What I made in NEAR Studio</a>.</li></ul><p>If you’re wondering where you can find the code, look no further:</p><ul><li><a href="https://studio.nearprotocol.com/?f=52d7s4s1w">Code</a></li></ul><h3>Coding Challenge</h3><p>Now that you know the basics of smart contracts and how to read and write to the blockchain, try to add addition and subtraction to your application and share with the community what it looks like.</p><p>Paste your share link below so people can see what you’ve made!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fc6e02abaa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/what-are-smart-contracts-a-hands-on-approach-9fc6e02abaa2">What Are Smart Contracts? A Hands-on Approach</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</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 Build a Geographically-aware, Location-based Android Dating App]]></title>
            <link>https://medium.com/hackernoon/how-to-build-a-geographically-aware-location-based-android-dating-app-c1aaa26f2f60?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1aaa26f2f60</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Wed, 17 Apr 2019 18:00:49 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:40.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>I built an app to rig the chances of me getting a date.</h3><p>With over a <a href="https://www.statista.com/statistics/809524/us-users-meeting-someone-in-person-dating-app-service-gender/">third of people opting to create meaningful relationships online</a>, it’s only fitting that instant gratification-driven dating apps like Tinder and Bumble have flourished. That got me thinking — how hard is it to build a <a href="https://www.pubnub.com/solutions/chat/dating-apps/">geo-aware mobile dating app</a> from scratch? Turns out, with microservices and serverless design patterns, backed by a realtime network, it’s not so hard.</p><p>In this tutorial, we’ll cover two very important parts of building a mobile, geo-aware dating application — geolocation and swiping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*x8kFRAky5pxuobTH.gif" /></figure><p>Shoutout to <a href="http://danmeth.tumblr.com/post/119457060107/the-sexy-new-social-app-for-bearded-guys">Dan</a> for making this!</p><h3>Microservices Architecture for a Dating App</h3><p>Let’s cover the flow of our application and cover a quick overview of what we’ll build. To keep things straightforward, when I say <strong>user</strong> I’m referring the person who opens the <a href="https://hackernoon.com/tagged/android">Android</a> app, and when I say <strong>partner(s)</strong> I’m referring to every other user who opens the application.</p><p>We know that we need to find every partner aside from the user, and we also need to know their <a href="https://hackernoon.com/tagged/location">location</a>. This means that every device needs to share a unique ID and their location. Next, we need each device to be able to check against each other device while also adding themselves to list or updating their current location. Once the user has added themselves to the list of partners, we can choose every other user from the list and check their distance against the current user’s.</p><p>That means we can split our whole system up into three parts:</p><h3>Android Application</h3><p>The actual Android application that sends it’s own unique ID with location and receives the ID and location of other users.</p><h3>Save and Filter</h3><p>This section ingests data from the Android application and returns out the location and unique ID of every user who isn’t the one who called the service.</p><h3>Calculate Distance</h3><p>This takes in a user with their location as well as the location of another user and spit back the distance. There is some math involved because we’ll be calculating the distance between two latitude and longitude distances. This service will return the unique user and the distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BCdOSwQ0XEdoOYxp.png" /></figure><h3>Creating Microservices</h3><p>To make things simple and efficient, we need to find a provider to run our microservices. To do so, we’ll use PubNub Functions.</p><p>You’ll first have to sign up for an account using the embedded form below. After that, head over to the <a href="https://admin.pubnub.com/">Admin Dashboard</a> and enable the Functions feature.</p><p>This will let us build out the <strong>Save and Filter </strong>feature, as well as the <strong>Calculate Distance</strong> microservice on PubNub, and give us the realtime, scalable experience we want.</p><h3>Saving and Filtering Users in Realtime</h3><p>Our client application will publish the current user’s ID and location to a serverless PubNub Function, which will save the location to a keyset-wide persistent storage called <a href="https://www.pubnub.com/docs/blocks/tutorials/kv-store">PubNub KV Store</a>.</p><p>From there, our first Function will check the current ID against every item in the KV Store and append it to the list of users. Once we have the full list, we’ll publish that message back to channel that’s unique to the device using its ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec8f47ea2d35680b3cc9af6001e7b04/href">https://medium.com/media/fec8f47ea2d35680b3cc9af6001e7b04/href</a></iframe><p><em>Note: PubNub Functions allows of a </em><a href="https://www.pubnub.com/docs/blocks/soft-and-hard-limitations"><em>maximum of 3 requests per function</em></a><em> call.</em></p><h3>Calculating Distance in Realtime</h3><p>We’ll be getting the data in the form of an array. The first two elements of the array are the IDs of the user and the last two elements are the location of the user who initiated the request. The first element is the ID of the initiator, and the second is a possible swipe candidate. Once we finish the calculation, we’ll send the ID of the unique user and the distance they are from the initiator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ad05d6503091223d5782f1573db624f/href">https://medium.com/media/4ad05d6503091223d5782f1573db624f/href</a></iframe><p>The result of this function will look like this:</p><pre>{ &quot;ID&quot;: &quot;Unique User ID&quot;, &quot;distance&quot;: 5 }</pre><h3>How to Swipe Through Users on the Android App</h3><p>To start off, create an empty Android Studio project with Kotlin support checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hoYMJxzRTsR2fvdZ.png" /></figure><p>Next, look at the dependencies we’re going to add to our app-level Gradle file to ensure our application runs smoothly.</p><p>The first dependency is the <strong>PubNub SDK</strong>, which will help us publish and subscribe to the logic we just created. Related to the PubNub SDK, we’ll also need our <strong>Publish</strong> and <strong>Subscribe</strong> keys. You can get your publish and subscribe keys by going through the quick setup below.</p><p>The other dependencies needed are for the visual component of our application — the swiping functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89ab8ca822b34dc35f39880eb927b78e/href">https://medium.com/media/89ab8ca822b34dc35f39880eb927b78e/href</a></iframe><h3>Creating the User Interface</h3><p>First, we’ll adjust our activity_main.xml to accommodate for our swiping feature that’ll be initialized in our MainActivity.kt file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc5492a5b8e5a9064348302c36650eb6/href">https://medium.com/media/fc5492a5b8e5a9064348302c36650eb6/href</a></iframe><p>Next, we’ll create each profile card’s UI, as well as the overlay on each of them, taking into consideration whether the user is swiping to the left or right.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1c1d39330e09087bc843f2f213c5e1/href">https://medium.com/media/ed1c1d39330e09087bc843f2f213c5e1/href</a></iframe><p>That’s it for the UI, now let’s cover the backend.</p><h3>Integrating the Application Logic</h3><p>For our application to be complete we’ll be creating four separate files. The first file we’re going to need is a class that will act as an object for each profile and will contain the related information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00152ace16494a6697fa49b89e042e6c/href">https://medium.com/media/00152ace16494a6697fa49b89e042e6c/href</a></iframe><p>Next, we’re going to create a file that will have some helper functions to update our collection of profiles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86a19881e944dff978a60b47280fdcbd/href">https://medium.com/media/86a19881e944dff978a60b47280fdcbd/href</a></iframe><p>Now, we can load each profile into the frontend. We’ll do this within a class called the CardStackAdapter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a6fa9d3c8db8d3b4553446ddf8e18e/href">https://medium.com/media/e4a6fa9d3c8db8d3b4553446ddf8e18e/href</a></iframe><h3>Stitching Everything Together</h3><p>We can head over to the MainActivity.kt file to see how everything fits together.</p><p>Let’s have a quick look at the onCreate and onStart methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6550e866b183600ec0d9450bb9d2fdc2/href">https://medium.com/media/6550e866b183600ec0d9450bb9d2fdc2/href</a></iframe><p>We can break down everything that’s happening into three things.</p><p>First, we’ll get the location of the device using <a href="https://developers.google.com/location-context/fused-location-provider/"><strong>Fused Location</strong></a>. Next, we’ll subscribe to a channel with the same name as our device ID, since all the possible people we can swipe on are published to that channel. Lastly, in the <strong>onStart</strong>, we’ll be publishing the date related to the device, just like the ID and Location. The reason we publish in the onStart and <strong>not</strong> the onCreate is because we won’t be able to get all the information we need to publish until the activity starts.</p><p>With that, let’s add all the features and using your pub/sub keys (they’re in your <a href="https://admin.pubnub.com/">Admin Dashboard</a>), in our MainActivity. In the end, our file will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb6713bf8996cab3d9b535966473e2bf/href">https://medium.com/media/eb6713bf8996cab3d9b535966473e2bf/href</a></iframe><p>Let’s run the app! In either an emulator or on a device, you can see the swiping functionality, as well as the user’s distance from you.</p><p>Nice work! Want to explore more features and ideas around mobile dating apps? Check out our <a href="https://www.pubnub.com/solutions/chat/dating-apps/">realtime dating apps overview</a>, and see how you can power cross-platform, fast, and secure dating apps at global scale with PubNub’s chat APIs and messaging infrastructure.</p><p><em>Originally published at </em><a href="https://www.pubnub.com/blog/how-to-build-a-location-based-dating-app-in-android/"><em>www.pubnub.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1aaa26f2f60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-to-build-a-geographically-aware-location-based-android-dating-app-c1aaa26f2f60">How to Build a Geographically-aware, Location-based Android Dating App</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Chat Basic Tutorial]]></title>
            <link>https://medium.com/hackernoon/react-chat-basic-tutorial-7bd2af16a57e?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd2af16a57e</guid>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-chat-tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-chat]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Sun, 03 Feb 2019 23:46:00 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:40.795Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial is for you if you are a <strong>software developer</strong>, <strong>engineer</strong> or are just interested in programming. This walk-through is open source and free; <a href="https://en.wikipedia.org/wiki/MIT_License">MIT</a> style. You can check out the full <a href="https://github.com/nxsyed/ReactChatEngineApp">React Chat GitHub repository</a>.</p><p><a href="https://reactjs.org/">React</a> is a <a href="https://hackernoon.com/tagged/javascript">JavaScript</a> library that empowers you to make sophisticated front-end applications that can handle business logic in a fast and efficient manner. We’ll use React to build out our web application frontend for our robust chat app. The unique benefit of React, aside from it having one of the largest JavaScript communities and incredible flexibility, is its compatibility with React Native, allowing us to easily turn our web app into a native mobile app for iOS and Android.</p><p>In this tutorial, we’ll build a simple, yet featured rich chat application with React and <a href="https://pubnub.com/products/chatengine/">PubNub ChatEngine</a>. React coupled with the <a href="https://material-ui.com/">material-UI </a>will be used to organize and enhance our application, and ChatEngine is going to be used as the backbone messaging infrastructure and framework to connect our chat users.</p><h3>An Overview of React</h3><p>Before we get coding, we need to have a deeper understand of what React is and what it provides for us. Primarily, React is built on JavaScript. This means that we can use our existing understanding of JavaScript and still be fairly comfortable with React.</p><p>The main thing that differentiates React from the rest, is the idea of components and the lifecycle within components. If you don’t have too much experience with React, don’t fret! I recommend having a look at the <a href="https://reactjs.org/">official React Docs</a> before we go on but it isn’t required.</p><p>Let’s start coding our react chat app! To make it easier, go ahead and pull from the repo: <a href="https://github.com/nxsyed/ReactChatEngineApp">React Chat GitHub Repository</a>.</p><h3>Step 1 : Environment Setup</h3><p>We need to do a couple things before we get into the code. The first is the Node Package Manager (NPM) which will let us add the packages we need to get all the juicy functionality we need. To get NPM, we need to get the latest version of Node and with that, we’ll have the npm/npx commands available to use in the terminal. Once that’s up and running, we’ll use the terminal to install some prerequisite packages and create the project hierarchy ( it’ll save us some time later down the line).</p><pre><em>    ## Enter these on your command line.</em><br>    <em>## If you have not already, install Node.js (preferably LTS).</em><br>    npx create-react-app react-chat-engine-app<br><br>    <em>## Change into the new directory</em><br><br>    cd react-chat-engine-app<br><br>    npm start</pre><p>Using the npx command sets up a boilerplate React project with the required packages and the preferred folder structure as described by the React development team. Once we run npm start, we should see a welcome page open up on the url “localhost:3000”</p><p>You’ll see that the instance will be running in the terminal. Be sure to keep that window open because it will allow us to see hot updates as we make them.</p><h3>Step 2 : ChatEngine Setup</h3><p>The best way to use ChatEngine is to install the package using NPM</p><p>npm install chat-engine --save</p><p>Running that command will get us the prerequisites for getting our app to be able to chat.</p><h3>Step 3 : Create the ChatEngine Service</h3><p>Now that we have a rudimentary React project created, we can start adding some flavor to it. All we’re going to do is initialize the ChatEngine Object. We’ll go through the functionality more in-depth in a bit.</p><p><strong>react-chat-engine-app/src/index.js</strong></p><pre><strong>import</strong> React, { Component } <strong>from</strong> &#39;react&#39;;<br>    <strong>import</strong> ChatEngineCore <strong>from</strong> &#39;chat-engine&#39;;<br>    <br>    <strong>const</strong> now <strong>=</strong> <strong>new</strong> Date().getTime();<br>    <strong>const</strong> username <strong>=</strong> [&#39;user&#39;, now].join(&#39;-&#39;);<br>    <br>    <strong>const</strong> ChatClient <strong>=</strong> ChatEngineCore.create({<br>        publishKey: &#39;your-pub-key&#39;,<br>        subscribeKey: &#39;your-sub-key&#39;<br>    }, {<br>        globalChannel: &#39;chatting&#39;<br>    });<br>    <br>    <strong>class</strong> App <strong>extends</strong> Component {<br>    <br>      <strong>constructor</strong>(props) {<br>        <strong>super</strong>(props);<br>        <strong>this</strong>.chat <strong>=</strong> <strong>new</strong> ChatClient.Chat(`BasicChatApp`);<br>      }<br>      <br>      render(){<br>        <strong>&lt;</strong>div<strong>&gt;</strong> <strong>&lt;</strong>/div&gt;<br>      }<br>    }<br>    <br>    ChatClient.on(&#39;$.ready&#39;, () <strong>=&gt;</strong> {<br>        ReactDOM.render(<strong>&lt;</strong>App <strong>/&gt;</strong>, document.getElementById(&#39;root&#39;));<br>    });</pre><p>Since ChatEngine relies on the PubNub’s Data Stream <a href="https://hackernoon.com/tagged/network">Network</a>, <strong>we need</strong> the PubNub Publish/Subscribe keys to get get-started. configure ChatEngine and get your keys, use the form below:.</p><ol><li>The generated keys will be displayed on your screen.</li><li>Replace the newly generated Publish key and Subscribe key with the string <strong>&lt;YOUR-PUBNUB-PUBLISH-KEY&gt; </strong>and <strong>&lt;YOUR-PUBNUB-SUBSCRIBE-KEY&gt; </strong>in the <strong>index.js</strong></li></ol><h3>Step 4: Building the App UI with React</h3><p>In the previous step, we were able to add the primary backend feature which would let our app communicate with other instances. Now, the next step is to connect</p><p>For displaying the chat messages, we use the <em>&lt;ion-list&gt;</em> with <em>&lt;ion-grid&gt;</em> UI elements.</p><p>The entire HTML code of the app UI is declared in <strong>home.html</strong>. You can overwrite the file as per the new UI declaration for this app.</p><p><strong>react-chat-engine-app/src/index.js</strong> (Modified File)</p><pre><strong>    import</strong> React, { Component } <strong>from</strong> &#39;react&#39;;<br>    <strong>import</strong> ReactDOM <strong>from</strong> &#39;react-dom&#39;;<br>    <strong>import</strong> &#39;./index.css&#39;;<br>    <strong>import</strong> ChatEngineCore <strong>from</strong> &#39;chat-engine&#39;;<br>    <br>    <strong>import</strong> { withStyles } <strong>from</strong> &#39;@material-ui/core/styles&#39;;<br>    <strong>import</strong> Card <strong>from</strong> &#39;@material-ui/core/Card&#39;;<br>    <strong>import</strong> CardActions <strong>from</strong> &#39;@material-ui/core/CardActions&#39;;<br>    <strong>import</strong> CardContent <strong>from</strong> &#39;@material-ui/core/CardContent&#39;;<br>    <strong>import</strong> List <strong>from</strong> &#39;@material-ui/core/List&#39;;<br>    <strong>import</strong> ListItem <strong>from</strong> &#39;@material-ui/core/ListItem&#39;;<br>    <strong>import</strong> Button <strong>from</strong> &#39;@material-ui/core/Button&#39;;<br>    <strong>import</strong> Typography <strong>from</strong> &#39;@material-ui/core/Typography&#39;;<br>    <strong>import</strong> Input <strong>from</strong> &#39;@material-ui/core/Input&#39;;<br>    <strong>import</strong> opengraph <strong>from</strong> &#39;chat-engine-open-graph&#39;;<br>    <br>    <br>    <strong>const</strong> now <strong>=</strong> <strong>new</strong> Date().getTime();<br>    <strong>const</strong> username <strong>=</strong> [&#39;user&#39;, now].join(&#39;-&#39;);<br>    <br>    <strong>const</strong> ChatClient <strong>=</strong> ChatEngineCore.create({<br>        publishKey: &#39;your-pub-key&#39;,<br>        subscribeKey: &#39;your-sub-key&#39;<br>    }, {<br>        globalChannel: &#39;chatting&#39;<br>    });<br>    <br>    ChatClient.connect(username, {<br>      signedOnTime: now<br>    }, &#39;auth-key&#39;);<br>    <br>    <strong>const</strong> styles <strong>=</strong> {<br>      card: {<br>        maxWidth: 345,<br>        margin: &#39;0 auto&#39;, <br>        float: &#39;none&#39;, <br>        marginbottom: &#39;10px&#39; <br>      },<br>      openCard:{<br>        maxWidth: 200<br>      },<br>      openMedia: {<br>        height: 80,<br>      },<br>      media: {<br>        objectFit: &#39;cover&#39;,<br>      },<br>      container: {<br>        display: &#39;flex&#39;,<br>        flexWrap: &#39;wrap&#39;,<br>      },<br>    };<br>    <br>    <strong>class</strong> Message <strong>extends</strong> Component{<br>    <br>      render () {<br>          <strong>return</strong> ( <br>            <strong>&lt;</strong>div <strong>&gt;</strong> <br>              { <strong>this</strong>.props.uuid }: { <strong>this</strong>.props.text } <br>            <strong>&lt;</strong>/div&gt;<br>          );<br>      }<br>    };<br>    <br>    <strong>class</strong> App <strong>extends</strong> Component {<br>    <br>      <strong>constructor</strong>(props) {<br>        <strong>super</strong>(props);<br>        <strong>this</strong>.chat <strong>=</strong> <strong>new</strong> ChatClient.Chat(`BasicChatApp`);<br>      }<br>    <br>      sendChat <strong>=</strong> () <strong>=&gt;</strong> {<br>        console.log(&quot;Sending Chat&quot;);<br>      }<br>    <br>      setChatInput <strong>=</strong> (event) <strong>=&gt;</strong> {<br>        <strong>this</strong>.setState({ chatInput: event.target.value })<br>      }<br>    <br>      componentDidMount() {<br>        <br>      }<br>    <br>      handleKeyPress <strong>=</strong> (e) <strong>=&gt;</strong> {<br>        <strong>if</strong> (e.key <strong>===</strong> &#39;Enter&#39;) {<br>            <strong>this</strong>.sendChat();<br>        }<br>      }<br>    <br>      render(){<br>        <strong>const</strong> { classes } <strong>=</strong> <strong>this</strong>.props;<br>        <strong>return</strong>(<br>          <strong>&lt;</strong>Card className<strong>=</strong>{classes.card}<strong>&gt;</strong><br>              <strong>&lt;</strong>CardContent<strong>&gt;</strong><br>                <strong>&lt;</strong>Typography gutterBottom variant<strong>=</strong>&quot;headline&quot; component<strong>=</strong>&quot;h2&quot;<strong>&gt;</strong><br>                  Messages<br>                <strong>&lt;</strong>/Typography&gt;<br>                  <strong>&lt;</strong>div className<strong>=</strong>{classes.root}<strong>&gt;</strong><br>                    <strong>&lt;</strong>List component<strong>=</strong>&quot;nav&quot;<strong>&gt;</strong><br>                      <strong>&lt;</strong>ListItem<strong>&gt;</strong><br>                      <strong>&lt;</strong>Typography component<strong>=</strong>&quot;div&quot;<strong>&gt;</strong><br>                        { <strong>this</strong>.state.messages }<br>                      <strong>&lt;</strong>/Typography&gt;<br>                      <strong>&lt;</strong>/ListItem&gt;<br>                    <strong>&lt;</strong>/List&gt;<br>                  <strong>&lt;</strong>/div&gt;<br>              <strong>&lt;</strong>/CardContent&gt;<br>              <strong>&lt;</strong>CardActions<strong>&gt;</strong><br>                <strong>&lt;</strong>Input<br>                  placeholder<strong>=</strong>&quot;Enter a message&quot;<br>                  value<strong>=</strong>{<strong>this</strong>.state.chatInput}<br>                  className<strong>=</strong>{classes.input}<br>                  onKeyDown<strong>=</strong>{<strong>this</strong>.handleKeyPress}<br>                  onChange<strong>=</strong>{<strong>this</strong>.setChatInput}<br>                  inputProps<strong>=</strong>aria<strong>-</strong>label<br>                <strong>/&gt;</strong><br>                <strong>&lt;</strong>Button size<strong>=</strong>&quot;small&quot; color<strong>=</strong>&quot;primary&quot;<strong>&gt;</strong><br>                  Github<br>                <strong>&lt;</strong>/Button&gt;<br>                <strong>&lt;</strong>Button size<strong>=</strong>&quot;small&quot; color<strong>=</strong>&quot;primary&quot;<strong>&gt;</strong><br>                  Exit<br>                <strong>&lt;</strong>/Button&gt;<br>              <strong>&lt;</strong>/CardActions&gt;<br>            <strong>&lt;</strong>/Card&gt;<br>          );<br>        }<br>      }<br>    <br>    <strong>const</strong> ChatComponent <strong>=</strong> withStyles(styles)(App);<br>    <br>    ChatClient.on(&#39;$.ready&#39;, () <strong>=&gt;</strong> {<br>        ReactDOM.render(<strong>&lt;</strong>ChatComponent <strong>/&gt;</strong>, document.getElementById(&#39;root&#39;));<br>    });</pre><p>It may seem like we’ve added a lot of code here. But rest assured, all we’ve done is create a simple UI using the Material-UI library. However, note the components and the state we’re changing. We created a component called Message which will act as a dummy component to handle our chat messages. The other thing is the state that we’ve made in the App component, which allows us to clear the input of our chat when the user hits enter. The other variable we’ve stored in state is the messages array. This is to anticipate the messages that will come into our app and to re-render with every new message that we append to the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/0*FJ51Xi2ffKkxYZXs" /></figure><h3>Step 5: Coding the Business Logic for App UI</h3><p>This part is fairly simple. All we’ll be looking at here is the two functions componentDidMount and sendChat. All of our logic for sending and receiving messages is going to be stored here.</p><p><strong>react-chat-engine-app/src/index.js/src/index.js</strong> (Modified File)</p><pre><strong>    import</strong> React, { Component } <strong>from</strong> &#39;react&#39;;<br>    <strong>import</strong> ReactDOM <strong>from</strong> &#39;react-dom&#39;;<br>    <strong>import</strong> &#39;./index.css&#39;;<br>    <strong>import</strong> ChatEngineCore <strong>from</strong> &#39;chat-engine&#39;;<br>    <br>    <strong>import</strong> { withStyles } <strong>from</strong> &#39;@material-ui/core/styles&#39;;<br>    <strong>import</strong> Card <strong>from</strong> &#39;@material-ui/core/Card&#39;;<br>    <strong>import</strong> CardActions <strong>from</strong> &#39;@material-ui/core/CardActions&#39;;<br>    <strong>import</strong> CardContent <strong>from</strong> &#39;@material-ui/core/CardContent&#39;;<br>    <strong>import</strong> List <strong>from</strong> &#39;@material-ui/core/List&#39;;<br>    <strong>import</strong> ListItem <strong>from</strong> &#39;@material-ui/core/ListItem&#39;;<br>    <strong>import</strong> Button <strong>from</strong> &#39;@material-ui/core/Button&#39;;<br>    <strong>import</strong> Typography <strong>from</strong> &#39;@material-ui/core/Typography&#39;;<br>    <strong>import</strong> Input <strong>from</strong> &#39;@material-ui/core/Input&#39;;<br>    <strong>import</strong> opengraph <strong>from</strong> &#39;chat-engine-open-graph&#39;;<br>    <br>    <br>    <strong>const</strong> now <strong>=</strong> <strong>new</strong> Date().getTime();<br>    <strong>const</strong> username <strong>=</strong> [&#39;user&#39;, now].join(&#39;-&#39;);<br>    <br>    <strong>const</strong> ChatClient <strong>=</strong> ChatEngineCore.create({<br>        publishKey: &#39;your-pub-key&#39;,<br>        subscribeKey: &#39;your-sub-key&#39;<br>    }, {<br>        globalChannel: &#39;chatting&#39;<br>    });<br>    <br>    ChatClient.connect(username, {<br>      signedOnTime: now<br>    }, &#39;auth-key&#39;);<br>    <br>    <strong>const</strong> styles <strong>=</strong> {<br>      card: {<br>        maxWidth: 345,<br>        margin: &#39;0 auto&#39;, <br>        float: &#39;none&#39;, <br>        marginbottom: &#39;10px&#39; <br>      },<br>      openCard:{<br>        maxWidth: 200<br>      },<br>      openMedia: {<br>        height: 80,<br>      },<br>      media: {<br>        objectFit: &#39;cover&#39;,<br>      },<br>      container: {<br>        display: &#39;flex&#39;,<br>        flexWrap: &#39;wrap&#39;,<br>      },<br>    };<br>    <br>    <strong>class</strong> Message <strong>extends</strong> Component{<br>    <br>      render () {<br>          <strong>return</strong> ( <br>            <strong>&lt;</strong>div <strong>&gt;</strong> <br>              { <strong>this</strong>.props.uuid }: { <strong>this</strong>.props.text } <br>            <strong>&lt;</strong>/div&gt;<br>          );<br>      }<br>    };<br>    <br>    <strong>class</strong> App <strong>extends</strong> Component {<br>    <br>      <strong>constructor</strong>(props) {<br>        <strong>super</strong>(props);<br>        <strong>this</strong>.chat <strong>=</strong> <strong>new</strong> ChatClient.Chat(`BasicChatApp`);<br>      }<br>    <br>      sendChat <strong>=</strong> () <strong>=&gt;</strong> {<br>        console.log(&quot;Sending Chat&quot;);<br>      }<br>    <br>      setChatInput <strong>=</strong> (event) <strong>=&gt;</strong> {<br>        <strong>this</strong>.setState({ chatInput: event.target.value })<br>      }<br>    <br>      componentDidMount() {<br>        <br>      }<br>    <br>      handleKeyPress <strong>=</strong> (e) <strong>=&gt;</strong> {<br>        <strong>if</strong> (e.key <strong>===</strong> &#39;Enter&#39;) {<br>            <strong>this</strong>.sendChat();<br>        }<br>      }<br>    <br>      render(){<br>        <strong>const</strong> { classes } <strong>=</strong> <strong>this</strong>.props;<br>        <strong>return</strong>(<br>          <strong>&lt;</strong>Card className<strong>=</strong>{classes.card}<strong>&gt;</strong><br>              <strong>&lt;</strong>CardContent<strong>&gt;</strong><br>                <strong>&lt;</strong>Typography gutterBottom variant<strong>=</strong>&quot;headline&quot; component<strong>=</strong>&quot;h2&quot;<strong>&gt;</strong><br>                  Messages<br>                <strong>&lt;</strong>/Typography&gt;<br>                  <strong>&lt;</strong>div className<strong>=</strong>{classes.root}<strong>&gt;</strong><br>                    <strong>&lt;</strong>List component<strong>=</strong>&quot;nav&quot;<strong>&gt;</strong><br>                      <strong>&lt;</strong>ListItem<strong>&gt;</strong><br>                      <strong>&lt;</strong>Typography component<strong>=</strong>&quot;div&quot;<strong>&gt;</strong><br>                        { <strong>this</strong>.state.messages }<br>                      <strong>&lt;</strong>/Typography&gt;<br>                      <strong>&lt;</strong>/ListItem&gt;<br>                    <strong>&lt;</strong>/List&gt;<br>                  <strong>&lt;</strong>/div&gt;<br>              <strong>&lt;</strong>/CardContent&gt;<br>              <strong>&lt;</strong>CardActions<strong>&gt;</strong><br>                <strong>&lt;</strong>Input<br>                  placeholder<strong>=</strong>&quot;Enter a message&quot;<br>                  value<strong>=</strong>{<strong>this</strong>.state.chatInput}<br>                  className<strong>=</strong>{classes.input}<br>                  onKeyDown<strong>=</strong>{<strong>this</strong>.handleKeyPress}<br>                  onChange<strong>=</strong>{<strong>this</strong>.setChatInput}<br>                  inputProps<strong>=</strong>aria<strong>-</strong>label<br>                <strong>/&gt;</strong><br>                <strong>&lt;</strong>Button size<strong>=</strong>&quot;small&quot; color<strong>=</strong>&quot;primary&quot;<strong>&gt;</strong><br>                  Github<br>                <strong>&lt;</strong>/Button&gt;<br>                <strong>&lt;</strong>Button size<strong>=</strong>&quot;small&quot; color<strong>=</strong>&quot;primary&quot;<strong>&gt;</strong><br>                  Exit<br>                <strong>&lt;</strong>/Button&gt;<br>              <strong>&lt;</strong>/CardActions&gt;<br>            <strong>&lt;</strong>/Card&gt;<br>          );<br>        }<br>      }<br>    <br>    <strong>const</strong> ChatComponent <strong>=</strong> withStyles(styles)(App);<br>    <br>    ChatClient.on(&#39;$.ready&#39;, () <strong>=&gt;</strong> {<br>        ReactDOM.render(<strong>&lt;</strong>ChatComponent <strong>/&gt;</strong>, document.getElementById(&#39;root&#39;));<br>    });</pre><p>Let’s Analyze this code Function by Function.</p><h4>A. constructor()</h4><p>Two things are happening here. First is the initialization of our ChatEngine object with a channel name. The second is creating a couple variables to track changes in our app, including the message that’s been typed and new messages coming into the application.</p><h4>B. sendChat()</h4><p>This function checks the state for whether the user has entered a message or not. In the case that they have pressed enter, the function will send a publish to the channel we’ve defined.</p><h4>C. setChatInput(event)</h4><p>This method is used to retrieve all the users who have joined the chat room. This is used to populate the header section of the UI to display all the users that are currently present in the chat room.</p><h4>D. componentDidMount()</h4><p>This method is used to send the chat message from the app client. It is bound to the <em>&lt;input&gt;</em> box as well as the <em>&lt;button&gt;</em> element of the UI.</p><h3>Next Steps</h3><p>We now have a basic functional chat app built with React library. You can check out the <a href="https://github.com/nxsyed/ReactChatEngineApp">GitHub repo</a> for the complete code of this app. Now you can run the project on your machine!</p><p><em>Originally published at </em><a href="https://reactjs.chat/tutorials/react-basic-chat-module/"><em>reactjs.chat</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd2af16a57e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/react-chat-basic-tutorial-7bd2af16a57e">React Chat Basic Tutorial</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Simple Slackbot with Serverless PubNub Functions]]></title>
            <link>https://medium.com/hackernoon/build-your-own-simple-slackbot-with-serverless-pubnub-functions-98549204ec39?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/98549204ec39</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 22:39:07 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:41.184Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone is using <a href="https://hackernoon.com/tagged/slack">Slack</a>. From sharing code to sending cat memes to your coworker at 2 am, Slack has become the go-to chat and collaboration platform for businesses. Unfortunately, messaging isn’t at the top of the <a href="https://hackernoon.com/tagged/productivity">productivity</a> food chain.</p><p>What’s really rocking the minds of number-crunchers and thought leaders is the ubiquitous need for chatbots. Namely, Slackbots. The reasoning behind this is that a bot allows for 24-hour access to either task handling or information lookup without the need of another person. Think of it this way, without Slackbots, we’d be forced to schedule our own meetings. Oh, the humanity!</p><h3>So You Want to Build a Slackbot?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*6qZy6Zluq20Fa1Hd.gif" /></figure><p>To get started, head over to the <a href="https://api.slack.com/">Slack API resource center</a> and create a new Slack app. We’ll need to set a name and also a development Slack group. In my case, I’ve name mined <strong>PNbot </strong>and have assigned it to one of my groups.</p><p>Once our application is created, we’re given the option to add different functionality to our app. Since we’re focusing on creating a Slackbot, click into the option of Bots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cc86qncGhfX7lbdp.png" /></figure><p>Inside the Bots section, we’ll be given the opportunity to add the username and display name for our bot. In both situations, I’ve chosen to name the bot <strong>pnbot</strong>. Keep in mind that there is a toggle near the bottom, that when selected, keeps the bot online. This makes sense in our scenario since, thanks to PubNub, our bot will be available <a href="https://support.pubnub.com/support/solutions/articles/14000043627-does-pubnub-provide-a-premium-sla-">approximately 99.999%</a> of the time.</p><p>So we have our bot set now, but how will we get it working in our workspace? Simply click into the install app subheading in the settings section located in the sidebar. That’s it! Our bot should now be available in our demo workspace.</p><p>And with that, our bot is up and running! Now the next step is to check out the features section in the sidebar on the Slack API site. In that section, we’re going to look for the <a href="https://api.slack.com/events-api"><strong>Event Subscriptions</strong></a> button and navigate to that. This will lead us to an empty page, but have no fear because if we click the toggle button, we can enable the feature.</p><p>Once enabled, notice that there is a space for a redirect URL. Don’t worry too much about that as we’ll be diving more into it as we build out our <em>serverless</em> Function. What we will be looking at is the workspace events just below the redirect URL. Here we can choose a number of events which have been properly outlined in the documentation. In our case, to make things simple, we’ll choose the mention event. This means that when the bot is mentioned in any channel that it’s present in, it will send a JSON payload with relevant information to the redirect URL. So far this is all we need for now.</p><h3>Creating a Serverless Slackbot Function</h3><p>First things first, you’ll have to <a href="https://admin.pubnub.com/#/register">sign up for a PubNub account</a>. In this order, we’ll need to -&gt; Create an app -&gt;Navigate to the keyset -&gt; click on the functions tab on the left. Here we’re going to create a new on-request module. What this means is that our module will act as a web-hook that the Slackbot can redirect to.</p><p>Now we have our Function configured, we’re going to need to set a path and copy the URL to set in the redirect URL field we were avoiding earlier. This will make it so that every time the bot is mentioned our function will receive a payload similar to this:</p><pre>&quot;request&quot;{  <br>   <strong>&quot;verb&quot;</strong>:&quot;rest&quot;,<br>   <strong>&quot;pubkey&quot;</strong>:&quot;your pub key&quot;,<br>   <strong>&quot;subkey&quot;</strong>:&quot;your sub key&quot;,<br>   <strong>&quot;timetoken&quot;</strong>:null,<br>   <strong>&quot;timetoken_v1&quot;</strong>:null,<br>   <strong>&quot;timetoken_v2&quot;</strong>:null,<br>   <strong>&quot;version&quot;</strong>:&quot;v1&quot;,<br>   <strong>&quot;meta&quot;</strong>:{  <br>      <strong>&quot;clientip&quot;</strong>:&quot;100.25.152.207&quot;,<br>      <strong>&quot;origin&quot;</strong>:&quot;pubsub.pubnub.com&quot;,<br>      <strong>&quot;useragent&quot;</strong>:&quot;Slackbot 1.0 (+https://api.slack.com/robots)&quot;<br>   },<br>   <strong>&quot;params&quot;</strong>:{  <br><br>   },<br>   <strong>&quot;uri&quot;</strong>:&quot;/your-path/bot&quot;,<br>   <strong>&quot;path&quot;</strong>:&quot;/bot&quot;,<br>   <strong>&quot;method&quot;</strong>:&quot;POST&quot;,<br>   <strong>&quot;body&quot;</strong>:&quot;{\&quot;token\&quot;:\&quot;token\&quot;,\&quot;team_id\&quot;:\&quot;T0431NL8C\&quot;,\&quot;api_app_id\&quot;:\&quot;AEQFW5DFV\&quot;,\&quot;event\&quot;:{\&quot;client_msg_id\&quot;:\&quot;4d282463-9622-4979-ae71-2b073895711c\&quot;,\&quot;type\&quot;:\&quot;message\&quot;,\&quot;text\&quot;:\&quot;&amp;lt;@UEQEUM144&amp;gt; &amp;lt;@UEQG0576F&amp;gt;\&quot;,\&quot;user\&quot;:\&quot;UA69Q4A64\&quot;,\&quot;ts\&quot;:\&quot;1544556685.000600\&quot;,\&quot;channel\&quot;:\&quot;DES1K0SGN\&quot;,\&quot;event_ts\&quot;:\&quot;1544556685.000600\&quot;,\&quot;channel_type\&quot;:\&quot;im\&quot;},\&quot;type\&quot;:\&quot;event_callback\&quot;,\&quot;event_id\&quot;:\&quot;EvESLB9J4E\&quot;,\&quot;event_time\&quot;:1544556685,\&quot;authed_users\&quot;:[\&quot;UEQG0576F\&quot;]}&quot;,<br>   <strong>&quot;headers&quot;</strong>:{  <br>      <strong>&quot;user-agent&quot;</strong>:&quot;Slackbot 1.0 (+https://api.slack.com/robots)&quot;,<br>      <strong>&quot;content-length&quot;</strong>:&quot;418&quot;,<br>      <strong>&quot;accept&quot;</strong>:&quot;*/*&quot;,<br>      <strong>&quot;accept-encoding&quot;</strong>:&quot;gzip,deflate&quot;,<br>      <strong>&quot;content-type&quot;</strong>:&quot;application/json&quot;,<br>      <strong>&quot;pfunc-original-uri&quot;</strong>:&quot;/your url/bot&quot;,<br>      <strong>&quot;x-forwarded-host&quot;</strong>:&quot;sub-key_js-on-rest&quot;,<br>      <strong>&quot;x-slack-request-timestamp&quot;</strong>:&quot;1544556686&quot;,<br>      <strong>&quot;x-slack-signature&quot;</strong>:&quot;v0=signature&quot;<br>   }<br>}</pre><p>Our bot is now connected to our Function, now we want our bot to start sending messages. Looking at the Slack documentation, we can see that the best way is by sending our message to the Slack web API.</p><p>In this case we’re going to enable <a href="https://api.slack.com/incoming-webhooks"><strong>incoming webhooks</strong></a> for our bot. This will allow us to be able to post to that webhook to have our messages sent. We can enable this feature by navigating to the sub-heading in the features section where we enabled events subscriptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fk9MDReYYRtTOTMh.png" /></figure><p>Once the authorization is done, the endpoint we’re going to post to will look like this:</p><pre><a href="https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX">https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX</a></pre><p>To test the functionality, inside of our serverless function, send the <a href="https://www.pubnub.com/docs/blocks/xhr-module"><strong>XHR request</strong></a> to the incoming webhook Slack provided us with a message.</p><pre>export default (request, response) =&gt; {<br>  const pubnub = require(&quot;pubnub&quot;);<br>  const kvstore = require(&quot;kvstore&quot;);<br>  const xhr = require(&quot;xhr&quot;);<br>  let body = JSON.parse(request.body);<br>  const http_options = {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({ text: &quot;cool story bro!!!&quot; })<br>  };<br>  const url =<br>    &quot;<a href="https://hooks.slack.com/services/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">https://hooks.slack.com/services/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</a>&quot;;<br>  response.status = 200;<br>  response.headers[&quot;X-Custom-Header&quot;] = &quot;CustomHeaderValue&quot;;<br>  return xhr.fetch(url, http_options).then(x =&gt; {<br>    return response.send(body);<br>  });<br>};</pre><p>In this case, whenever our bot is mentioned in a channel, it will reply with “cool story bro!!!”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*718jSF3fbevF_SdU.png" /></figure><h3>Next Steps</h3><p>And that’s it! If I’ve piqued your interest in bots or serverless, I highly recommend having a looking a few of these articles:</p><p><em>Originally published at </em><a href="https://www.pubnub.com/blog/build-your-own-simple-slackbot-serverless-pubnub-functions/"><em>www.pubnub.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98549204ec39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/build-your-own-simple-slackbot-with-serverless-pubnub-functions-98549204ec39">Build Your Own Simple Slackbot with Serverless PubNub Functions</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Voice, Alexa, and realtime: Making interactions into lasting experiences]]></title>
            <link>https://medium.com/hackernoon/voice-alexa-and-realtime-making-interactions-into-lasting-experiences-fa46aab9503b?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa46aab9503b</guid>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[alexa]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Thu, 12 Jul 2018 20:31:36 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:41.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HP6upETt_BKpKfbzPew_Rg.png" /></figure><p>We’ve progressed as developers from creating applications with complex functionality to focusing on creating experiences that retain our users. Amazing UI’s and clear-cut user flows are becoming the goal for many emerging/existing applications.</p><p>While some industries are still trying to migrate towards a mobile-centric model there are different takes on the next methods to improve the UI and UX. Voice, AR and VR, just to name a few, have become contenders to break the simple model of interacting with a screen and have started to trend more towards augmenting real human interactions. This means that people have begun to abstract their interactions farther away from tapping on a screen to shaking their phones or talking to their device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_PaZbToiwFS7E_QQDFV7g.gif" /><figcaption>\credit: <a href="https://www.behance.net/jihncy">https://www.behance.net/jihncy</a></figcaption></figure><p>The more we delve into these experiences we start to realize the backbone in making them fluid is by providing real-time responses, exceeding a users expectation of augmentation and making the experience as integrated as possible.</p><p>To explore the possibility of how we can connect the ideas of real-time and the paradigm of user-experiences we’re going to make a project involving Amazon’s <a href="https://hackernoon.com/tagged/alexa">Alexa</a>. The main idea is to show how we can improve an existing experience by innovating how people interact.</p><p>This is where what we’ll call <strong>Smart-Intercom</strong> comes in, an Alexa skill that we’ll build which will enable people to augment the typical house intercom experience by letting our voice device allow the speaker to communicate in real-time with the homeowner.</p><p>All the code is <a href="https://github.com/nxsyed/intercom-frontend">available on GitHub</a> and a <a href="https://nxsyed.github.io/intercom/">live demo is available here of the frontend.</a></p><h3>Interaction Model</h3><p>Having little to no interface when dealing with a voice application makes it inherently important to develop some sort model that describes how our user interacts without an application and what happens before, during and after that interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SQaun3XPqH7wYUgk.png" /></figure><p>Currently, the ecosystem is fairly new and there are different terms for different things, but it’s better to break down these bigger concepts into something more digestible. We can split our model into two different actions.</p><h3>Invocations and Responses</h3><p>The idea here is that Alexa (and other voice devices) are essentially waiting for some sort of invocation. This invocation just tells the device that it needs to do something or begin a certain flow. Associated with the invocation is then some sort of response, this could lead into something else or provide whatever the invoker was asking.</p><h3>How PubNub Can Help</h3><p>Analysing the Invocation and Response pattern we can see that the most difficult part of the interaction would be the response. This is where PubNub comes in. We can use PubNub Functions to make smart and real-time responses to what our users invoke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TCurkEw9t9vIV0Co.png" /></figure><p>In this model, we can use PubNub as a way to handle a lot of the custom logic that Alexa or Google Assistant can’t do by itself. In the example of the smart-intercom, we’d want to contact the owner of the home, so we’d use PubNub to check whether this is the person the visitor is looking for (Invoker). At the moment Alexa allows for API requests, which makes PubNub the perfect solution to execute logic remotely.</p><h3>Designing Interaction Models</h3><p>Unfortunately, it seems like creating voice applications is still fairly difficult if we use the conventional approach. The development <a href="https://hackernoon.com/tagged/tools">tools</a> that are out there are not very intuitive and leave developers stranded with complex design patterns.</p><p>Luckily, we can create our flow with a site made by the development community called Storyline. It’s fairly simple and without any coding, we can build out the interaction.</p><p>The general flow of the smart-intercom application looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*sfK0N-fIC7R5P5Ri.png" /></figure><p>Here we can see that the user first invokes our application.</p><p>Alexa then replies with the question of who the invoker would like to see.</p><p>The invoker replies</p><p>Alexa then carries out the logic of reaching out.</p><p>Making some sort of companion app that pushes to a PubNub channel and then sends some data to the PubNub channel which Alexa grabs using an API request.</p><p>Alexa then gives the reply to the person that invoked the app.</p><p>So let’s see how this would look in storyline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*n934nL-ccBvcXaeO.png" /></figure><p>Though Storyline is a fairly intuitive tool, let’s break down what’s going on here:</p><p>The arrows indicate where each action leads to. Many of the blocks you see in the image above, such as the help block, are actually there by default. The only thing we’re adding here is the “Contact Person” block in the second column.</p><p>The reasoning behind this is because when our application is invoked, we have a 3rd user option which we’ve created that allows our user to enter the person they’d like to see. We then store that response in the variable.</p><p>Once the user has given a person name we enter into the “Contact Person” block and we make Alexa do an API request. This request then goes to our PubNub Function that handles the incoming messages from our companion App. We’ll have to wait for a preset amount of time then fetch for the data. This works perfectly because just in case the owner isn’t available we could send a generic reply to let the invoker know.</p><h3>Companion App and PubNub Functions</h3><p>We can start off by creating the mobile app. Here specifically we’re going to be using React Native, but if you want to use Android or iOS we have <a href="https://www.pubnub.com/docs">SDKs available</a>.</p><p>You’ll first have to <a href="https://admin.pubnub.com/#/register?utm_source=Syndication&amp;utm_medium=Medium&amp;utm_campaign=SYN-CY18-Q2-Medium-Jul-12">create a PubNub account</a> to get your pub/sub keys.</p><p>Then, create a new React-Native app. we can do that by running the following command:</p><pre>npx create-react-native-app pubnub-alexa</pre><p>This will create a boilerplate project that has all the things we need to start building. Next, we can navigate into the pubnub-alexafolder we just create and get our project running. We’ll also install the pubnub-react library so that we won’t have to worry about it when we build.</p><pre>cd pubnub-alexa npm i --save pubnub-react npm i npm start</pre><p>Then we can go into our app.js file and add the things necessary to have our app connect to PubNub.</p><p>First import PubNub.</p><pre>import PubNubReact from &#39;pubnub-react&#39;;</pre><p>Then adding a constructor in our component which initializes our PubNub object and then lets our object subscribe to a channel once the component has mounted.</p><pre>constructor(props) { <br>    super(props); <br>    this.pubnub = new PubNubReact({ <br>       publishKey: &#39;Your Publish Key&#39;, <br>       subscribeKey: &#39;Your Subscribe Key&#39; <br>    }); <br>    this.pubnub.init(this); <br>} <br>componentWillMount() { <br>   this.pubnub.subscribe({ <br>       channels: [&#39;Alexa&#39;] <br>   }); <br>}</pre><p>In our main render method lets quickly make a list of pre-determined responses. You can go ahead and design that yourself, but I’ll be using the and design library to make my interface look a bit sleeker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc749a6147054f8fcaec3c6943e291c/href">https://medium.com/media/ebc749a6147054f8fcaec3c6943e291c/href</a></iframe><p>When everything is added, our app.js file should look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ecc21e1c4177134a4fe20e86969308/href">https://medium.com/media/71ecc21e1c4177134a4fe20e86969308/href</a></iframe><p>The next step would be to make our PubNub Function which connects our Alexa skill to our companion application.</p><p>We’ll make an on request function because then it would allow us to create API requests from the Alexa skill.</p><p>The function will look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9da5b2f0787c22a93661411d4a8918d3/href">https://medium.com/media/9da5b2f0787c22a93661411d4a8918d3/href</a></iframe><p>All the function does is check whether the parameter that we send during our API request and performs some actions based on that.</p><p>In our Alexa skill, we had a block called “Contact Person”. In here we make two API calls to our function. Both calls add a parameter called “Action”. The first one says “notify” to let the companion app that for someone is at the door.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Dbq1zpcKRdz1IRl.png" /></figure><h3>Wrapping Up</h3><p>So we now have an Alexa app that allows the person interacting with the Alexa app to interact with someone else in real-time. Nice, but how do we take this to the next level? Of course, you can go deeper and make connections to IoT devices. The front-end allows users to now perform actions based on a request made from Alexa. Now it’s up to you to decide what those actions are.</p><p>All the code is <a href="https://github.com/nxsyed/intercom-frontend">available on GitHub</a> and a <a href="https://nxsyed.github.io/intercom/">live demo is available here of the frontend.</a></p><p><em>Originally published at </em><a href="https://www.pubnub.com/blog/voice-alexa-and-realtime/"><em>www.pubnub.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa46aab9503b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/voice-alexa-and-realtime-making-interactions-into-lasting-experiences-fa46aab9503b">Voice, Alexa, and realtime: Making interactions into lasting experiences</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</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 Build a Smart Chatbot Assistant with ChatEngine and IBM Watson Assistant]]></title>
            <link>https://medium.com/hackernoon/how-to-build-a-smart-chatbot-assistant-with-chatengine-and-ibm-watson-assistant-ffe3f43436b8?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe3f43436b8</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 18:21:43 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:42.615Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pubnub coupled with IBM Watson can enable developers and business owners to streamline their frontlines by creating smart assistants which answers the simple questions for you.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGnQJqaw9usCcgYqnmXisA.png" /></figure><p><a href="https://hackernoon.com/tagged/chatbots">Chatbots</a>, whether they be customer service agents or shopping assistants in an online store, have become commonplace amongst the way we interact with businesses. Intelligent bots and assistants serve to be the frontline for many businesses and now is a better time than any to build a smart approach to solving problems.</p><p>You might be wondering if it’s possible to create an intelligent assistant of your own. The short answer is yes, and that’s exactly what we’ll walk through today, using ChatEngine and <a href="https://www.ibm.com/watson/services/conversation/">IBM Watson Assistant</a>. Our bot will answer basic questions for people looking to learn more information about <a href="https://hackernoon.com/tagged/pubnub">PubNub</a>, but your bot can be trained and customized however you wish. We’ll show you how to do this too.</p><p><a href="https://github.com/nxsyed/commun-ai"><strong>The full project GitHub repo is available here.</strong></a></p><p><a href="https://admin.pubnub.com/#/register?utm_source=Syndication&amp;utm_medium=Medium&amp;utm_campaign=SYN-CY18-Q2-Medium-Jun-12"><strong>You’ll also need to sign up for Pubnub!</strong></a></p><h3>How It Works 👩‍💻</h3><p>Before we get into the code, let’s map out the logic in terms of how our user will interact with our assistant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*9SfYlMP0_YnmjIcY.jpg" /></figure><p>At first, the user asks a question via ChatEngine to send a message to out our chatbot assistant. The reason we have two ChatEngine connections is to make sure that our bot can handle multiple connections at once. In our specific case we’ll make our chatbot on the same client but in an ideal situation, it would be a good idea to have the chatbot running on a separate client.</p><p>Once the bot receives the message via ChatEngine it sends the message to <a href="https://www.pubnub.com/products/functions/">PubNub Functions</a>. The goal behind this is to reduce the amount of backend code we have and just focus on the things that matter — the experience. Functions is how we connect our messaging application to the IBM Watson Assistant service.</p><p>In our <a href="https://www.pubnub.com/docs/blocks-catalog">BLOCKS Catalog</a>, there is an <a href="https://www.pubnub.com/docs/blocks-catalog/pubnub-tutoring-bot">IBM Assistant BLOCK</a> which needs a bit of configuration, and once that’s done it will be connected to IBM Watson. The function will query Watson and get a reply back, which it will then send to our customer.</p><h3>Getting Started with ChatEngine and Watson</h3><h4>Configuring ChatEngine 🚒</h4><p>Building the chat interface and backend for a chatbot can be challenging and time-consuming. We’ll mitigate that using ChatEngine, our PubNub-powered framework that makes building cross-platform a breeze.</p><p>You’ll first have to configure a new ChatEngine application in PubNub. You can <a href="https://www.pubnub.com/docs/tutorials/chatengine#step-one-pubnub-keys"><strong>do this in our ChatEngine quickstart</strong></a>, and it will provide you your pub/sub keys as well as configuring your keyset for ChatEngine.</p><h4>Watson + BLOCKS 🍫</h4><p>Once we have ChatEngine configured, we can start building our assistant.</p><p>First, create a new Function within our ChatEngine Module. We can call this function ‘Assistant’, have an event of ‘On Request’ and make our channel name be ‘assistant’. After adding our new Function we can go ahead and add the code for it to connect to IBM Assistant.</p><p>This is actually a version of the code available in the <a href="https://www.pubnub.com/docs/blocks-catalog/pubnub-tutoring-bot">IBM Assistant BLOCK</a> but slightly changed so that we could fit it with our interaction model. In particular, if we look at lines 55–65 we’ll that the way we handle our response and the method we get data from our client has changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc652d5467c7f80b52c9eaf7f9ad27c1/href">https://medium.com/media/dc652d5467c7f80b52c9eaf7f9ad27c1/href</a></iframe><p>You’ll notice that in the Function code above that we’re using the vault to get access to certain keys available to our module. We’ll need to add three more keys to our vault which can be found when setting up Watson.</p><p><strong>Watson Configuration </strong>🤸</p><p><a href="https://console.bluemix.net/registration/">Head over to Watson</a> to get your keys. If you haven’t already, feel free to <a href="https://console.bluemix.net/catalog/services/watson-assistant-formerly-conversation">set up a Watson instance on your Bluemix console</a>. You’ll see that with your new Watson resource you’ll have a username and password. View those and insert them into the vault in the Assistant Function we just created. The next key we need is the workspaceID, we can go to the launch tool in the Bluemix console and create a workspace.</p><p>In here, we can either create a workspace from scratch or use a sample. For this example, let’s go with the customer service example. Once we’re in the workspace we can open the hamburger menu on the side and go to the improve tab. Near the top of the page, we should see a credentials button, and by clicking that we can get our workspaceID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OQLJZge-K11x68Ub.png" /></figure><p>So, now that we have our keys, our vault should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yEgLyOErlOO7bPxZ.png" /></figure><p>At this point, we have the cogs of our application working. We created the structure that will receive messages from our bot and send that data to our assistant and also have our assistant wired up so that those messages can get a meaningful response.</p><p>Let’s start developing our client and its interface.</p><h3>Me, My Bot, and I 🤖</h3><p>Looking at the client, there are two things that we’re going to make. The first being the input for where the user can submit their message and the second being the bot that can send that data to our function. Ideally, we’d separate these two components but for simplicity, we’ll have them both running on the same client.</p><p>To begin, let’s create a basic React project which we can do by using the create-react-app tool.</p><pre>$ npx create-react-app Watson-Assistan</pre><p>If your version of npm is less than 5.2 feel free to use npm instead of npx. The difference between the two is based on the scope of the installation and whether the command is a one-off or not. If you need more information read about it in <a href="https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner">npm’s blogpost</a>.</p><p>The folder should now be set up so let’s navigate into it.</p><pre>cd Watson-Assistant/</pre><p>Great! Our project tree should look something like this.</p><pre>|-- Watson-Assistant <br>    |-- .gitignore <br>    |-- README.md <br>    |-- package-lock.json <br>    |-- package.json <br>    |-- public <br>    |  |-- favicon.ico <br>    |  |-- index.html <br>    |  |-- manifest.json <br>    |-- src <br>    |-- App.css <br>    |-- App.js <br>    |-- App.test.js <br>    |-- index.css <br>    |-- index.js <br>    |-- logo.svg <br>    |-- registerServiceWorker.js</pre><p>In here we’re going to take out some of the boilerplate that the create-react-app tool as graciously left for us.</p><p>We can take out logo.svg and registerServiceWorker.js. There’s no particular reason other than to clean up our project, but if you feel that you the need to look more into why the service worker file is there have a look at this <a href="https://github.com/facebook/create-react-app/issues/2398">issue</a> on the master GitHub repo.</p><p>After cleaning up our directory our structure should look something like this.</p><pre>|-- Watson-Assistant <br>    |-- .gitignore <br>    |-- package-lock.json <br>    |-- package.json <br>    |-- public <br>    |   |-- favicon.ico <br>    |   |-- index.html <br>    |   |-- manifest.json <br>    |-- src <br>    |-- index.css <br>    |-- index.js</pre><p>Now let’s look at the file where the majority of our app is going to sit:<em> </em><a href="https://github.com/nxsyed/commun-ai/blob/master/src/index.js"><em>index.js</em></a>.</p><p>We’ll start by looking at the lifecycle and what we’re going to render in our browser. First, ensure we have ChatEngine in our package.</p><pre>$ npm i chat-engine</pre><p>At this point, I’d also recommend checking out my <a href="https://github.com/nxsyed/commun-ai/blob/master/package.json">package.json file on GitHub</a>. Here you can follow along completely without breaking your code. I’ll try to make sure that I explain each package I use so that you get a better understanding of how everything fits in.</p><p>So now that we have the packages, let’s start coding.</p><p>To create our client we need to give our ChatEngine client the keys to the ChatEngine app we made earlier. Choosing our app on the <a href="http://admin.pubnub.com/?utm_source=Syndication&amp;utm_medium=Medium&amp;utm_campaign=SYN-CY18-Q2-Medium-Jun-12">PubNub Admin Dashboard</a> then choosing our keyset we can get the publish and subscribe keys. We can then create our client object like this.</p><pre>const ChatClient = ChatEngineCore.create({ <br>    publishKey: &#39;pub-c-e1295433-4475-476d-9e37-4bdb84dacba0&#39;,    subscribeKey: &#39;sub-c-890a0b26-6451-11e8-90b6-8e3ee2a92f04&#39;<br>},{ <br>    globalChannel: &#39;watson-assistant&#39; <br>});</pre><p>Since we are creating the ChatClient and ChatBot on the same client we’re going to duplicate this but change the name to ChatBot.</p><p>It’s also nice to have a username for every connection we make so let’s make a template for usernames, something like this:</p><pre>const now = new Date().getTime(); const username = [&#39;user&#39;, now].join(&#39;-&#39;);</pre><p>Connect our user and chatbot to our ChatEngine.</p><pre>ChatClient.connect(username, { signedOnTime: now }); ChatBot.connect(`${now}bot`, { signedOnTime: now });</pre><p>Create our chat class and look at the different lifecycle methods.</p><p>The constructor is a good place to begin, and in here we’re going to assign our variables with our chat instances. We can also initialize all the variables we want to store in the state.</p><p>Personally, I want to use this <a href="https://www.npmjs.com/package/react-clippy">react-clippy package</a> that will act as our assistant. We can use different animated characters to show our message and animate them. For Clippy we need to have an animation that plays so I’ll define that in my state. We also need the input the user gives and the response we get from our function.</p><p><strong><em>Note: this post has no relation to Microsoft and they had nothing to do with this</em></strong></p><p>In the end, our constructor looks like this.</p><pre>constructor() { super(); this.chat = new ChatClient.Chat(`${now}chat`); <br>this.bot = new ChatBot.Chat(`${now}chat`); <br>this.state = { <br>    reply: &#39;Ask Me Something!&#39;, <br>    chatInput: &#39;&#39;, <br>    animation: &#39;Congratulate&#39; }; <br>}</pre><p>Before going further, it’s a good idea to formulate a bit more about the render function. We know that we’re going to be accepting input so we’ll need some sort of input box. As well, we’ll be displaying a response and I’ll be adding the wonderful Clippy.</p><pre>render() { <br>   return ( <br>     &lt;div style={container}&gt; <br>       &lt;div style={{height:100, width:100}}&gt; <br>          &lt;p&gt; {this.state.reply} &lt;/p&gt; </pre><pre>          &lt;Clippy <br>             actor={ &#39;Clippy&#39; } <br>             animation={ this.state.animation } /&gt; </pre><pre>          &lt;input <br>             id = &quot;chat-input&quot; <br>             type = &quot;text&quot; <br>             name = &quot;&quot; <br>             value = { this.state.chatInput } <br>             onChange = { this.setChatInput } <br>             onKeyPress = { this.handleKeyPress } /&gt; </pre><pre>          &lt;input <br>             type = &quot;button&quot; <br>             onClick = { this.sendChat } <br>             value = &quot;Send Chat&quot; /&gt; <br>       &lt;/div&gt; <br>     &lt;/div&gt; ); }</pre><p>There are a couple other functions that complete some functionality in the chat class such as pressing enter to send the message but I’ll leave that up to you to explore. What we’ll look at now is the sending message part. There are two functions and they directly relate to how the flow of our project works.</p><pre>sendChat = () =&gt; { <br>  if (this.state.chatInput) { <br>    this.chat.emit(&#39;message&#39;, { <br>      text: this.state.chatInput, <br>      channel: `${now}chat` <br>    }); <br>    this.setState({ chatInput: &#39;&#39; }) <br>    this.setState({ animation: &#39;Processing&#39;, reply: &#39;&#39; }); } <br>} <br>componentDidMount() { <br>  this.bot.on(&#39;message&#39;, (payload) =&gt; {      axios.get(`https://pubsub.pubnub.com/v1/blocks/sub-key/sub-c-890a0b26-6451-11e8-90b6-8e3ee2a92f04/chat? question=${payload.data.text}`) .then(response =&gt; { this.setState({ animation: &#39;Writing&#39;, reply: response.data }); }); <br>  }); <br>}</pre><p>The sendChat function lets the user send their message to the bot. Notice how we’re emitting the message and we’re defining the channel by the time. This allows making each chat in its own private session so that we don’t interrupt conversations other customers may be having at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ey7jOkDvzaMnb5ESywkMdg.gif" /></figure><p>We also need to ensure our bot listen for messages coming in. So that when the Chat component has mounted we need to make sure that our bot sends that message to our function and then updates our component with the message. For doing the request I’m using the axios package and you read more about here.</p><p>One last step. We need to make sure that once our ChatEngine connection is established we render our chat component. We can do that by adding this to the bottom of our file.</p><pre>ChatClient.on(&#39;$.ready&#39;, () =&gt; { <br>   ChatBot.on(&#39;$.ready&#39;, () =&gt; { <br>     ReactDOM.render( &lt;Chat /&gt; , document.getElementById(&#39;root&#39;) );     }); <br>});</pre><h3>Our Chatbot is Up-and-Running! 🏃‍</h3><p>This is a great starting point for building something more unique. It would definitely be a good idea to explore the documentation for IBM Assistant to train our bot to be clever and have more depth in their responses. ChatEngine can do a lot of cool things to connect instantly with people and services. I would love to see what you build next 🙂.</p><h3><strong>Follow me on Twitter / Instagram! @nxsyed</strong></h3><p><em>Originally published at </em><a href="https://www.pubnub.com/blog/chatengine-chatbot-ibm-watson-assistant-tutorial/?utm_source=Syndication&amp;utm_medium=Medium&amp;utm_campaign=SYN-CY18-Q2-Medium-Jun-12"><em>www.pubnub.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe3f43436b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/how-to-build-a-smart-chatbot-assistant-with-chatengine-and-ibm-watson-assistant-ffe3f43436b8">How to Build a Smart Chatbot Assistant with ChatEngine and IBM Watson Assistant</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Quickest Way To Have Real-Time Analytics Using PubNub EON]]></title>
            <link>https://medium.com/hackernoon/the-quickest-way-to-have-real-time-analytics-using-pubnub-eon-f7f9a11d9ea2?source=rss-2a41a487876------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f9a11d9ea2</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pubnub]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Syed Ahmed]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 16:23:04 GMT</pubDate>
            <atom:updated>2019-05-07T11:05:43.166Z</atom:updated>
            <content:encoded><![CDATA[<h4>It took me less than a day to create a very rudimentary platform that’s real-time and also allows me to view real time analytics for cryptocurrency prices in a digestible format.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Owa2rsDG6Rwv1IM_RdsL3A.gif" /></figure><p>It seems like everywhere you turn there’s some big corporation trying to take your data with complex environments that take lots of time to set up but aren’t as extensible as advertised 😫.</p><blockquote>For petes sake 😤 I just want to build something quick and add features as I need them .</blockquote><p>I recently discovered <a href="https://www.pubnub.com/">PubNub</a> and decided it warranted an obscenely overcomplicated article to solidify my own understanding, however it also has the added benefit of being easy to use. So maybe this won’t be too complicated.</p><h3>Lets Get Lit And Lets Code 😌🔥</h3><p>First of make sure you have the latest version of all these things:</p><ul><li>Courage 🦁</li><li>Tenacity 🐯</li><li>Spunk 💃🕺</li><li><a href="https://httpd.apache.org/">Apache 🚁</a> (Or some other webserver)</li></ul><p>Now hop into your IDE to start coding. Personally I’ll be using <a href="http://c9.io/">c9</a> because it sets up a quick environment and I don’t have to worry about saving my code online since the IDE is already hosted in the <a href="https://www.howtogeek.com/howto/32016/what-is-cloud-computing-and-what-does-this-stupid-buzzword-mean/"><strong><em>cloud</em></strong>☁<strong><em>.</em></strong></a></p><p>Great, now create 2 folders named jsand css. These will contain our different files that’ll be used in our index.html (The main page).</p><p>My weapon of choice is the terminal so I’ll<em> slide in </em>the following commands to get my environment going.</p><pre>$ mkdir punhub &amp;&amp; cd punhub<br>$ mkdir js<br>$ mkdir css</pre><p>Now is the perfect time to create our index.html. This file is going to be where the structure of our page is going to sit.</p><p>In this file you’re going to want to add the type of charts you want to display your analytics on. We’ll focus on building a website that shows me the prices of different cryptocurrencies that I’m following so I’ll be using the <a href="https://www.pubnub.com/developers/eon/chart/spline/">spline graph</a>.</p><p>To get the different components to work from PubNub we’ll need to add their javascript tags. When working with plain HTML/JSS/CSS I tend to place all my javascript file at the bottom of the closing &lt;/body&gt; tag because it allows the webpage to load visually before grabbing inserting all the javascript.</p><pre>&lt;!-- PubNub Eon --&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;//pubnub.github.io/eon/v/eon/1.0.0/eon.js&quot;&gt;&lt;/script&gt;<br>    &lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;//pubnub.github.io/eon/v/eon/1.0.0/eon.css&quot;/&gt; </pre><p>Next we’ll need to navigate to our js folder and create a file called eon.js . In that file we’ll add all of our PubNub related javascript.</p><p>The flow of the javascript for PubNub starts off by creating a new PubNub Object.</p><pre>let pubnub = new PubNub({<br>      publishKey: &#39;your unique key&#39;,<br>      subscribeKey: &#39;your other unique key &#39;<br>});</pre><p>This object requires two keys. The first key is to send data to PubNub and the second key to listen to data from PubNub. To get both of these keys we’ll need to create a new account and then create a new app in the PubNub dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RG8BU-GgWbZRzDHJuKIuVw.png" /></figure><p>Once the new app is created we’ll see that we are given our publish key and subscribe key.</p><h3>Charts Charts Charts</h3><p>Now let’s <em>insert</em>😌 our chart. We can do this by <a href="https://en.wikipedia.org/wiki/Initialization_(programming)">initializing</a> it in our eon.js file.</p><pre>eon.chart({<br>  channels: [&#39;crypto-chart&#39;], //Where the data will be received from<br>  history: true, // maintains data<br>  flow: true,<br>  pubnub: pubnub, //pubnub object with keys<br>  generate: {<br>    bindto: &#39;#chart&#39;, // tag in html where chart will be inserted<br>    data: {<br>      labels: false<br>    }<br>  }<br>});</pre><p>When we initializing we also need to create a connected tag in our index.html which has the same id as the name in our bindto .</p><pre>&lt;div id=&#39;chart&#39;&gt;<br>    Spline chart<br>&lt;/div&gt;</pre><p>Ok so we have our chart running, but there’s no data.</p><p>This is where our publish key comes into play, as we can start publishing data to our PubNub channel.</p><pre>$.getJSON( &quot;<a href="https://min-api.cryptocompare.com/data/price?fsym=USD&amp;tsyms=XVG,TRON,ZIL,DGB">https://min-api.cryptocompare.com/data/price?fsym=USD&amp;tsyms=XVG,TRON,ZIL,DGB</a>&quot;, function( json ) {<br>      var dateCurrent = new Date();<br>      var dateMilli = dateCurrent.getTime();<br>      <br>      pubnub.publish({<br>        channel: &#39;crypto-chart&#39;,<br>        message: <br>          {&quot;eon&quot;:{<br>            &quot;XVG&quot;: json.XVG,<br>            &quot;TRON&quot;: json.TRON,<br>            &quot;ZIL&quot;: json.ZIL,<br>            &quot;DGB&quot;: json.DGB,<br>            &quot;_eonDatetime&quot;: dateMilli<br>            }<br>          }<br>        });<br>    })</pre><p>Right now the data is being fetched from a <a href="http://searchmicroservices.techtarget.com/definition/RESTful-API">REST api</a> and it’s sending the data to our channel in a readable format (defined by PubNub). But this only sends data once, we want something real-time that’s constantly updating, so in the same eon.js file we can add an interval the continues to fetch the data indefinitely.</p><pre>setInterval(() =&gt; {<br>    $.getJSON( &quot;<a href="https://min-api.cryptocompare.com/data/price?fsym=USD&amp;tsyms=XVG,TRON,ZIL,DGB">https://min-api.cryptocompare.com/data/price?fsym=USD&amp;tsyms=XVG,TRON,ZIL,DGB</a>&quot;, function( json ) {<br>      var dateCurrent = new Date();<br>      var dateMilli = dateCurrent.getTime();<br>      <br>      pubnub.publish({<br>        channel: &#39;crypto-chart&#39;,<br>        message: <br>          {&quot;eon&quot;:{<br>            &quot;XVG&quot;: json.XVG,<br>            &quot;TRON&quot;: json.TRON,<br>            &quot;ZIL&quot;: json.ZIL,<br>            &quot;DGB&quot;: json.DGB,<br>            &quot;_eonDatetime&quot;: dateMilli<br>            }<br>          }<br>        });<br>    })<br>},2000)</pre><p>There you have it! We have a fully real-time graph running at an extremely low latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_NZp7bVy4R7TRdsJhuOJUw.gif" /><figcaption>Goodboy!!!</figcaption></figure><h3>Looking Forward 👀</h3><p>I’m making the code available on my <a href="https://hackernoon.com/tagged/github">GitHub</a> so feel free to add on to this project and improve it. Some points you could add are possibly connecting to an api that provides a more up to date figure or allowing the user to select which currencies they can view.</p><p>There are also other options from <a href="https://hackernoon.com/tagged/pubnub">PubNub</a> for making charts which you can checkout <a href="https://www.pubnub.com/developers/eon/">here</a>.</p><p>You can see my <a href="https://punhub-analytics-stackezz.c9users.io/index.html">PunHub here</a>.</p><p>If you have any questions feel free to drop a line.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f9a11d9ea2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/the-quickest-way-to-have-real-time-analytics-using-pubnub-eon-f7f9a11d9ea2">The Quickest Way To Have Real-Time Analytics Using PubNub EON</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>