<?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 Praguna Manvi on Medium]]></title>
        <description><![CDATA[Stories by Praguna Manvi on Medium]]></description>
        <link>https://medium.com/@praguna?source=rss-1d2721e632bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2Ge8sXQd2JGw51bLAgWUsg.jpeg</url>
            <title>Stories by Praguna Manvi on Medium</title>
            <link>https://medium.com/@praguna?source=rss-1d2721e632bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@praguna/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[Practical Tools for Privacy Preserving Deep Learning (PPDL)]]></title>
            <link>https://medium.com/swlh/practical-tools-for-privacy-preserving-deep-learning-ppdl-7d38066144a?source=rss-1d2721e632bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d38066144a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Praguna Manvi]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 08:47:08 GMT</pubDate>
            <atom:updated>2022-08-30T13:43:06.350Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep learning is a data intensive learning technique applied with great success in many domains. However, practical problem-solving in Medical, Banking, and other sensitive information fields demands privacy. PPDL is a set of approaches that address this issue for Deep Learning. Some seminal works from the cryptography land are borrowed and applied in AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*gfD2xST7On0KtlComYgRRw.png" /><figcaption>Privacy Preserving Deep Learning</figcaption></figure><p>An ideal PPDL system preserves data and model privacy, accuracy, and latency. Methods like <strong>Homomorphic Encryption</strong> allows operations on encrypted data sent from a client but have very high complexity while building deeper models and results can be decrypted only at the client-side. <strong>Federated learning</strong> is already highly used in modern-day applications such as Gboard, sharing encrypted model update information with the service provider after local inference on the client device. <strong>Differential privacy</strong> prevents the leakage of sensitive information which the model might have memorized by using random noise while training. <strong>Secure Enclaves</strong> provide hardware-based security for code and data from other software on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-KdKCPHvek_MQ4MnDzr3A.png" /><figcaption>Homomorphic Encryption[1]</figcaption></figure><p>Recently, <strong>SMC</strong> (Secure Multi-party Computation) has gained a lot of attention which operates on shared data (among any number of clients) without revealing data or model weights during computation. It provides security against adversaries with unbounded computational power. <strong>SMCs</strong> offer the capacity to train a model on combined data. Unlike previous methods above, there is no need to maintain private keys to work. Severe communication overhead is the main challenge for the <strong>SMC</strong> approach on deeper models though it guarantees accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hP0hVIIbTt4DdsnDTc5-Hw.png" /><figcaption>Secure multiparty computation[1]</figcaption></figure><p><strong>Crypten </strong>built on PyTorch implements SMC. It provides an imperative API and we can easily convert torch tensors to crypten tensors.</p><pre>!pip install crypten<br>!pip install torch==1.9.0</pre><pre>import torch<br>import crypten<br>crypten.init()<br>x = torch.tensor([1.0, 2.0, 3.0])<br>x_enc = crypten.cryptensor(x) # encrypt<br>x_dec = x_enc.get_plain_text() # decrypt<br>y_enc = crypten.cryptensor([2.0, 3.0, 4.0])<br>sum_xy = x_enc + y_enc # add encrypted tensors<br>sum_xy_dec = sum_xy.get_plain_text() # decrypt sum<br>print(sum_xy_dec)</pre><pre>Output:<br>tensor([3., 5., 7.])</pre><p>Further examples on training and inference are present <a href="https://github.com/facebookresearch/CrypTen/tree/main/tutorials">here</a>.</p><p>Tensorflow graph compiled library <a href="https://github.com/tf-encrypted"><strong>tf-encrypted</strong></a> also provides learning on encrypted data. An example of calculating the average over five inputs is shown below.</p><pre>!pip install tf-encrypted</pre><pre>import logging<br>import sys<br>import tensorflow as tf<br>import tf_encrypted as tfe</pre><pre><a href="http://twitter.com/tfe">@tfe</a>.local_computation(name_scope=&quot;provide_input&quot;)<br>def provide_input() -&gt; tf.Tensor:<br>    # pick random tensor to be averaged<br>    return tf.random_normal(shape=(10,))</pre><pre><a href="http://twitter.com/tfe">@tfe</a>.local_computation(&quot;result-receiver&quot;, name_scope=&quot;receive_output&quot;)<br>def receive_output(average: tf.Tensor) -&gt; tf.Operation:<br>    # simply print average<br>    return tf.print(&quot;Average:&quot;, average)</pre><pre>if __name__ == &quot;__main__&quot;:</pre><pre>logging.basicConfig(level=logging.DEBUG)</pre><pre># get input from inputters as private values<br>    inputs = [<br>        provide_input(<br>            player_name=&quot;inputter-0&quot;<br>        ),  # pylint: disable=unexpected-keyword-arg<br>        provide_input(<br>            player_name=&quot;inputter-1&quot;<br>        ),  # pylint: disable=unexpected-keyword-arg<br>        provide_input(<br>            player_name=&quot;inputter-2&quot;<br>        ),  # pylint: disable=unexpected-keyword-arg<br>        provide_input(<br>            player_name=&quot;inputter-3&quot;<br>        ),  # pylint: disable=unexpected-keyword-arg<br>        provide_input(<br>            player_name=&quot;inputter-4&quot;<br>        ),  # pylint: disable=unexpected-keyword-arg<br>    ]</pre><pre># sum all inputs and divide by count<br>    result = tfe.add_n(inputs) / len(inputs)</pre><pre># send result to receiver<br>    result_op = receive_output(result)</pre><pre># run a few times<br>    with tfe.Session() as sess:<br>        sess.run(result_op, tag=&quot;average&quot;)</pre><pre>Output:<br>Average: [0.45496113397347965 0.62231367169638774 -0.23807346441091298 ... -0.88690748361530258 0.22709952751105014 0.22085048010973937]</pre><p>Refer for further tutorials on using this library <a href="https://github.com/tf-encrypted/tf-encrypted/tree/master/examples">here</a>.</p><p>Although a few prototyping libraries exist today, training simple models like Lenet-5 on MNIST takes days, and inference runs into many hours. We can anticipate hybrid approaches using both Homomorphic encryption and SMC, parallelization, new types of neural nets (Efficient for PPDL), and unique hardware designs in the future.</p><blockquote>Thanks for going through, Have a nice Day !</blockquote><h4>References:</h4><ul><li><em>H. C. Tanuwidjaja, R. Choi, S. Baek and K. Kim, “Privacy-Preserving Deep Learning on Machine Learning as a Service — a Comprehensive Survey,” in IEEE Access, vol. 8, pp. 167425–167447, 2020, doi: 10.1109/ACCESS.2020.3023084.</em></li><li>Knott, B., Venkataraman, S., Hannun, A., Sengupta, S., Ibrahim, M., &amp; Maaten, L. (2021). CrypTen: Secure Multi-Party Computation Meets Machine Learning. In <em>Advances in Neural Information Processing Systems</em> (pp. 4961–4973). Curran Associates, Inc..</li><li>Kumar, N., Rathee, M., Chandran, N., Gupta, D., Rastogi, A., &amp; Sharma, R. (2020). CrypTFlow: Secure TensorFlow Inference. In <em>IEEE Symposium on Security and Privacy</em>. IEEE.</li><li><a href="https://github.com/tf-encrypted/tf-encrypted">https://github.com/tf-encrypted/tf-encrypted</a></li><li><a href="https://github.com/facebookresearch/CrypTen">https://github.com/facebookresearch/CrypTen</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d38066144a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/practical-tools-for-privacy-preserving-deep-learning-ppdl-7d38066144a">Practical Tools for Privacy Preserving Deep Learning (PPDL)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering Comment Section in React]]></title>
            <link>https://medium.com/swlh/rendering-comment-section-in-react-1cd0521e4b42?source=rss-1d2721e632bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd0521e4b42</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Praguna Manvi]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 19:22:36 GMT</pubDate>
            <atom:updated>2022-01-09T15:54:50.117Z</atom:updated>
            <content:encoded><![CDATA[<p>Every website out there has a comment section. Starting from a simple blog to common social media sites. Therefore, finding a way to code this component in a few easy lines is important: For this exercise, I have used <a href="https://codesandbox.io/s/o872t?module=/example.js&amp;file=/index.js">semantic-ui </a>comments and recursive components for laying out the responsive nested structure.</p><p>Initial data for comments looks as follows:</p><pre>{author : &quot;Matt&quot;,  comment : &quot;How artistic!&quot;, day : &quot;Today&quot;, comments : [] },</pre><pre>{author : &quot;Elliot Fu&quot;,  comment : &quot;This has been very useful for my research. Thanks as well!&quot;, day : &quot;Today&quot;, comments : [{author : &quot;Jenny Hess&quot;,  comment : &quot;Elliot you are always so right :)&quot;, day : &quot;Today&quot;, comments : []}, ]},</pre><pre>{author : &quot;Joe Henderson&quot;,  comment : &quot;Dude, this is awesome. Thanks so much&quot;, day : &quot;Yesterday&quot;, comments : []},<br>]</pre><p>And then, we will use only one component for rendering this as follows :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a663a5877088bb592f0e21db54209e1a/href">https://medium.com/media/a663a5877088bb592f0e21db54209e1a/href</a></iframe><p>Now lets wrap this in first top level comments:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf16985b2e3a8fa8ff2c6c71816bac1/href">https://medium.com/media/edf16985b2e3a8fa8ff2c6c71816bac1/href</a></iframe><p>That’s it !! :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*P-Zr0Asi7_jy39Jupi5spg.gif" /><figcaption>Similarly, additional functionalities can be added</figcaption></figure><h4>Check this out :</h4><ol><li><a href="https://codesandbox.io/s/wizardly-gould-e2dyk?file=/src/CommentExampleComment.js">https://codesandbox.io/s/wizardly-gould-e2dyk?file=/src/CommentExampleComment.js</a></li></ol><p>2. <a href="https://github.com/praguna/react-comment-section">https://github.com/praguna/react-comment-section</a></p><blockquote>Thanks for reading through, Have a Great Day :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd0521e4b42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/rendering-comment-section-in-react-1cd0521e4b42">Rendering Comment Section in React</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tic-Tac-Toe AI]]></title>
            <link>https://medium.com/swlh/tic-tac-toe-ai-ac14d85e52d7?source=rss-1d2721e632bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac14d85e52d7</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[gui]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Praguna Manvi]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 04:59:45 GMT</pubDate>
            <atom:updated>2021-06-15T07:34:13.935Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tic-Tac-Toe AI With Tkinter Visualization</h3><h3>Introduction</h3><p>Tic-tac-toe ,consisting of Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner.</p><p>Each player takes alternative turn. In order to win, a player places three of their marks in a horizontal, vertical, or diagonal row. This article focuses on the development of a programmatic approach with its GUI visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*ELxNO3RFHEpG_2JsViRILw.png" /><figcaption>Tic-Tac-Toe Game</figcaption></figure><h3><strong>Approaches</strong></h3><p>The following are different ways of thinking about building the AI with incremental complexity :</p><ol><li><em>Random Placement method </em>: In this approach, the marking is simply made by the AI randomly in any available cell. The downside is obvious, the AI is not interested in the game at all! But still it has to find out the available cells and track the termination of the game. Here is the pseudocode for this approach :</li></ol><pre>function ai_move(curr_state){<br>     game_has_ended(curr_state)<br>     l = [list of all blank cells]<br>     r,c = select one at random<br>     curr_state[r][c] = &#39;X&#39; <br>     game_has_ended(curr_state)<br>}</pre><pre>function game_has_ended(curr_state){<br>   if all cells are filled:<br>    exit(&quot;Game is Drawn&quot;)<br>   for each row or column in curr_state{<br>    if row or column is filled with same mark: <br>     exit(&quot; Game is won &quot;)<br>   }<br>   if diagonals are filled with same mark:<br>    exit(&quot;Game is won &quot;)</pre><pre>}</pre><p>2. <em>Static Scoring method </em>: Building on top of the previous approach, a priority score is assigned to each cell in the grid. The unmarked cell with the highest priority is marked in the next move. The middle cell has the highest priority followed by the corner and then the other cells, based on the degree of control offered by them. Here is the pseudocode for this approach :</p><pre>function ai_move(curr_state){<br>     game_has_ended(curr_state)<br>     r,c = select cell position of highest priority <br>     curr_state[r][c] = &#39;X&#39;<br>     game_has_ended(curr_state)<br>}</pre><pre>sample static scoring :</pre><pre>  |3 | 1 |3 |<br>  |1 | 7 |1 |<br>  |3 | 1 |3 |</pre><p>3.<em> Brute Force method </em>: The disadvantages of both the methods above is that, they miss to read the opponent and fail to play moves to advantage. So, this method is built on the above methods. When the opponent has two markings in a row or column or diagonal, it is blocked. Otherwise, static scores are used to fill the empty cells. In the case where two cells are previously marked, it is completed to win the game. Here is the pseudocode for this approach :</p><pre>function ai_move(curr_state){<br>     game_has_ended(curr_state)<br>     for each row,col in curr_state{<br>        if row has two markings:<br>           fill the unfilled cell of row and return<br>        if col has two markings,<br>           fill the unfilled cell of column and return<br>     }<br>     game_has_ended(curr_state)<br>     if row or column or diagonal exists with 2 markings:<br>         curr_state[that_row][that_column] = &#39;X&#39;<br>         return<br>     l = [list of all blank cells]<br>     r,c = select one at random of highest priority<br>     curr_state[r][c] = &#39;X&#39;<br>     game_has_ended(curr_state)<br>}</pre><p>4.<em> Minimax method </em>: The approach above is enough to draw the game or winning simple games but to win by tricking a shrewd opponent is more desirable. This method is illustrated as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*DvOibxUMY6dmyGri4W5dtg.jpeg" /><figcaption>minmax approach</figcaption></figure><pre>leaf_scores -&gt; min_of_all_scores -&gt; max_of_all_min_scores -&gt; min_of_all_scores -&gt; ..... -&gt; max_of_all_min_scores (root)<br>   ( This is applied across all children of each node )</pre><p>Here, it is assumed that the opponent plays the game in the most optimal way. Thus, this approach could be used in <a href="https://en.wikipedia.org/wiki/Zero-sum_game">zero-sum</a> game scenario. Each level of the game tree deals with the actions of alternating players. The result computed is calculated with respect to the player at the root as shown above. The root in <em>tic-tac-toe</em> is the AI player.</p><p>The leaf nodes consists of scores at end positions of the<em> tic-tac-toe</em> game. The scores are based on a heuristic which is the <em>nucleus</em> of this approach. The heuristic assigns positive, negative or non-negative scores based on winning, losing or draw positions.</p><p>The pseudocode of the heuristic employed here is :</p><pre>function heuristic(curr_state){<br> if is_draw(curr_state):<br>      return 0<br> if has_won(curr_state):<br>      number of unfilled_cells + 1<br> if has_lost(curr_state):<br>      -number_of_unfilled_cells - 1<br>}</pre><p>Recursive implementation is used. The pseudocode of the approach is :</p><pre>function ai_move(curr_state, ai = True){</pre><pre>     if (res = heuristic(curr_state)) != nil: return res<br>     <br>     poss_moves = get_all_possible_moves<br>     <br>     for move in poss_moves{<br>            scores.append(ai_move(move, ~ai))   <br>     }<br>     <br>     return max(scores) if ai is True else min(scores)<br>}<br>// a move is chosen with the maximum score at the current state (root) based on priority index or randomly if scores clash</pre><h3><strong>Building Tic-Tac-Toe-AI With GUI</strong></h3><blockquote>Find the full code here : <a href="https://github.com/praguna/ai-puzzels/tree/master/tic_tac_toe">https://github.com/praguna/ai-puzzels/tree/master/tic_tac_toe</a></blockquote><p>Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de facto standard GUI. It is a fast and easy way of creating GUI applications.</p><p>Initially, a frame is created in which all the widgets are placed :</p><pre>class App(tk.Frame):<br>    def __init__(self, parent, dim, **kw):<br>        super().__init__(parent, **kw)<br>        parent.minsize(dim[0], dim[1])<br>        parent.title(&quot;Tic Tac Toe&quot;)<br>        self.define_display_widgets()<br>        messagebox.showinfo(&quot;Info&quot;, &quot;Welcome to Tic Tac Toe Game &quot;)<br>        self.ttt_grid = Grid(self, {&quot;tile_color&quot;: &quot;red&quot;, &quot;text&quot;: &quot;Puzzle Grid&quot;})</pre><pre>def define_display_widgets(self):<br>        self.label = tk.Label(self, text=&quot;Let&#39;s play Tic Tac Toe&quot;, font=(&#39;Verdana&#39;, 15, &#39;bold&#39;))<br>        self.label.pack(side=tk.TOP)<br>        self.reset = tk.Button(self, text=&quot;Reset&quot;, bg=&quot;grey&quot;, fg=&quot;white&quot;, command=self.reset_all)<br>        self.reset.pack(side=tk.LEFT, anchor=tk.N)<br>        ttk.Separator(self, orient=tk.HORIZONTAL).pack(after=self.label, fill=tk.X)</pre><pre>def reset_all(self):<br>        self.ttt_grid.disable_or_reset(disable=False)</pre><p>The grid class is where the<em> tic-tac-toe</em> game is played and it is created as follows :</p><pre>class Grid(tk.Frame):</pre><pre>def __init__(self, parent, config, **kw):<br>        super().__init__(parent, **kw)<br>        self.b = [[], [], []]<br>        self.config = config<br>        self.draw_grid()<br>        tk.Label(parent, text=config[&quot;text&quot;], font=(&#39;Verdana&#39;, 20, &#39;bold&#39;), pady=5).pack()<br>        self.score = tk.Label(parent, text=&quot;&quot;, font=(&#39;Verdana&#39;, 10, &#39;bold&#39;), pady=2)<br>        self.score.pack()<br>        self.pack(pady=15)<br>        self.set_algo()</pre><pre>def draw_grid(self):  <br>        # draws the grid inside the main frame<br>        for i in range(3):<br>            for j in range(3):<br>                self.b[i].append(self.button())<br>                self.b[i][j].config(command=lambda row=i, col=j: self.fill(row, col))<br>                self.b[i][j].grid(row=i, column=j)</pre><pre>def button(self):<br>        return tk.Button(self, bd=5, width=2, font=(&#39;arial&#39;, 50, &#39;bold&#39;))</pre><p><strong>It looks like this :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1KH4Iu3LCfFmvUuEyK_d7Q.png" /><figcaption>GUI Layout</figcaption></figure><p>Once the move is played it is handled as follows in the <em>fill method :</em></p><pre>def fill(self, i, j):<br>    self.b[i][j].config(text=get_symbol(self.turn),    state=tk.DISABLED, bg=<strong>&quot;black&quot;</strong>, fg=<strong>&quot;white&quot;</strong>)<br>    self.algo_value[i * 3 + j] = get_symbol(self.turn)<br>    status  = self.check_if_game_ended(<strong>&quot;Player&quot;</strong>)<br>    if status: return<br>    self.turn = update_state(self.algo_value, i, j, self.turn)<br>    self.ai_move()</pre><p>It can be noticed that the <em>ai_move</em> is called here which will use the <em>minimax</em> algorithm in its method as follows :</p><pre>def ai_move(self, start=None):<br>        if start:<br>            move, s = start, 0<br>        else:<br>            move, s = find_best_move(self.algo_value, True, self.turn) # applies minmax <br>        self.score.config(text=&quot;current minimax score {}&quot;.format(s))<br>        index = 0<br>        for i in range(9):<br>            if self.algo_value[i] != move[i]:<br>                index = i<br>                break<br>        self.algo_value = move<br>        self.b[index // 3][index % 3].config(text=get_symbol(self.turn), state=tk.DISABLED, fg=&quot;white&quot;, bg=&quot;red&quot;)<br>        self.turn = not self.turn<br>        self.check_if_game_ended(&quot;Computer&quot;)</pre><p>The method call <em>find_best_move </em>implements <em>minimax</em> algorithm as follows :</p><pre>def find_best_move(curr, is_ai, v):<br>    if is_won(curr): return curr, 1 + final_score(curr) if not is_ai else -final_score(curr) - 1  # invert the flag<br>    if is_draw(curr): return curr, 0<br>    poss_moves = gen_moves(curr, v)<br>    b = -10 if is_ai else 10<br>    next_move = None<br>    for move in poss_moves:<br>        _, score = find_best_move(move, not is_ai, not v)<br>        if (score &gt; b and is_ai) or (score &lt; b and not is_ai):<br>            next_move, b = move, score<br>    return next_move, b</pre><p>This logic is same as the pseudocode discussed above. The game is found out to be won or drawn as follows :</p><pre>def has_won(self):<br>    curr = self.algo_value<br>    for i in range(3):<br>        if curr[3 * i] == curr[3 * i + 1] == curr[3 * i + 2] != -1:<br>            return True, (3 * i, 3 * i + 1, 3 * i + 2)<br>        if curr[0 + i] == curr[3 + i] == curr[6 + i] != -1:<br>            return True, (0 + i, 3 + i, 6 + i)<br>    if curr[0] == curr[4] == curr[8] != -1:<br>        return True, (0, 4, 8)<br>    if curr[2] == curr[4] == curr[6] != -1:<br>        return True, (2, 4, 6)<br>    return False, None</pre><pre>def is_draw(curr: list):<br>    return -1 not in curr</pre><p>The user can also decide to let the AI play first by selecting in a prompt defined as :</p><pre>def set_algo(self):<br>    val = messagebox.askquestion(<strong>&quot;Info&quot;</strong>, <strong>&quot;Do you want me to start ?&quot;</strong>)<br>    self.algo_value = [-1] * 9<br>    self.turn = True<br>    if val == <strong>&quot;yes&quot;</strong>:<br>        i = r.choice([2, 0, 6, 8, 1, 3, 5, 7])<br>        m = self.algo_value[:]<br>        m[i] = <strong>&#39;X&#39;<br>        </strong>self.ai_move(m)</pre><p>Lastly, the winner’s cells must get highlighted which is implemented as :</p><pre>def highlight(self, v):<br>        for x in v:<br>            self.b[x // 3][x % 3].config(fg=&quot;black&quot;, bg=&quot;blue&quot;)<br>        self.disable_or_reset()</pre><pre># disable the grid after the game is own or lost by ai<br>def disable_or_reset(self, disable=True):<br>    for i in range(3):<br>        for j in range(3):<br>            if disable:<br>                self.b[i][j].config(state=tk.DISABLED)<br>            else:<br>                self.b[i][j].config(text=<strong>&quot;&quot;</strong>, bg=self.cget(<strong>&#39;bg&#39;</strong>), fg=<strong>&quot;black&quot;</strong>, state=tk.NORMAL)<br>    if not disable: self.set_algo()</pre><p><strong>Finally, Let’s see it in action</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*l-UAosdHiYqcHfd9j8cfYA.gif" /><figcaption>play tic-tac-toe with AI</figcaption></figure><blockquote>Thanks for going through, Have a nice Day :)</blockquote><h4>References</h4><ul><li><a href="https://en.wikipedia.org/wiki/Tic-tac-toe">Tic-tac-toe - Wikipedia</a></li><li><a href="https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/">Minimax Algorithm in Game Theory | Set 1 (Introduction) - GeeksforGeeks</a></li><li><a href="https://github.com/praguna/ai-puzzels/tree/master/tic_tac_toe">praguna/ai-puzzels</a></li><li><a href="https://en.wikipedia.org/wiki/Minimax">Minimax - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac14d85e52d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/tic-tac-toe-ai-ac14d85e52d7">Tic-Tac-Toe AI</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Eight Puzzle Problem]]></title>
            <link>https://medium.com/swlh/solving-eight-puzzle-problem-and-its-visualization-in-tkinter-8b90f80ba178?source=rss-1d2721e632bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b90f80ba178</guid>
            <category><![CDATA[tkinter]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Praguna Manvi]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 15:08:33 GMT</pubDate>
            <atom:updated>2021-07-20T12:14:05.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving The Eight Puzzle Problem And Its Visualization withTkinter</h3><h3>Introduction</h3><p>The Eight puzzle problem is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing. It was invented and popularized by Noyes Palmer Chapman in the 1870s. It is a smaller version of n puzzle problem which is a classical problem for modeling algorithms involving heuristics. If the square frame size is 3×3 tiles, the puzzle is called the 8-puzzle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*X28ygtzjp45fAA3NHlrDdQ.png" /><figcaption>Eight Puzzle Square tile</figcaption></figure><h3>Problem Background</h3><p>The goal of the problem is to attain the destination configuration from source configuration by sliding the empty tile vertically or horizontally in each move. This is aimed to be done in minimum number of moves possible.</p><p>The destination state exists as a reachable or unreachable state from the source state. No matter how many moves are made some states can be unreachable from the source state.</p><p>Finding the shortest solution is a NP-Hard problem, so an exhaustive search is employed along with heuristics for better efficiency.</p><p>Initially source and destination states are passed as input and the list of steps to reach to destination is returned.</p><h3>Approaches</h3><p>The following are the possible approaches to solve the puzzle :</p><h4>Depth first Search (DFS)</h4><p>It is a recursive technique exploring all possible states until it finds the destination state. The visiting of child nodes occur before adjacent nodes.</p><pre>// pseudocode<br>func dfs (src , dest):<br> if src is dest: return all the visited states <br> add src to visited states<br> for move in all_possible_moves_from(src):<br>  if move not in visited states :<br>    return dfs(move ,dest)<br> return Not found</pre><h4>Iterative Deepening DFS</h4><p>The disadvantage of DFS is that it explores all the levels starting from the root without exploring all adjacent nodes of the previous levels. This can lead to stack overflow problems or a slower solution if the destination is in one of the other nodes of the current level. Hence, in iterative deepening, DFS is performed through increments of maximum level threshold.</p><pre>// pseudocode<br>func iterdfs(max_depth):<br>    while i &lt; max_depth:<br> res = dfs(src , dest, i) // performs dfs only till level i<br> if res != Not found: <br>  return res<br>     i = i + 1<br>      return Not Found</pre><h4>Breadth First Search (BFS)</h4><p>Though Iterative deepening can solve the problems of DFS, but it is inefficient as it takes multiple iterations of DFS. The Breadth first search is an iterative approach exploring all the adjacent positions before exploring the next level moves. It makes use of a queue which might add too much memory while solving in a large search space.</p><pre>// pseudocode<br>func bfs(src, dest)<br> create a queue q<br> q.push(src)<br> while q is not empty:<br>    c = q.pop()<br>    if c is dest: return all visited states<br>    add c to visited states<br>    for move in all_possible_moves_from(c):<br>      if move not in visited states :<br>        q.push(c)<br> return Not found</pre><h4>A* Algorithm</h4><p>This approach may use either BFS or DFS but only some moves are selected that minimize the following cost function :</p><pre>f(n) = h(n) + g(n) (h(n) is the heuristic function and g(n) is the distance from source state)</pre><p>The definition of the heuristic h(n) makes the search intelligent. This function in the current approach sums up all the mismatching tiles. The distance g(n) from source is just the number of steps taken. The below is the pseudocode for DFS and BFS:</p><pre>// pseudocode<br>func  A*dfs (src , dest):<br> if src is dest: return all the visited states <br> add src to visited states<br> possible_moves =   all_possible_moves_from(src):<br> scores =  h(possible_moves, target) + g<br> selected_moves  =  possible_moves with min(scores) <br> for move in selected_moves:<br>  if move not in visited states :<br>    return dfs(move ,dest)<br> return Not Found</pre><pre>func A*bfs(src, dest)<br> create a queue q<br> q.push(src)<br> while q is not empty:<br>    c = q.pop()<br>    if c is dest: return all visited states<br>    add c to visited states<br>    possible_moves =   all_possible_moves_from(c):<br>    scores =  h(possible_moves, target) + g<br>    selected_moves  =  possible_moves with min(scores) <br>    for move in selected_moves :<br>     if move not in visited states :<br>       q.push(c)<br> return Not found</pre><p>The cost function parameters are computed as follows:</p><pre>// pseudocode<br>def h(move,target): //heuristic function<br>   for e1,e2 in zip(move, target):<br>        if e1!=e2: sum+=1<br>   return sum </pre><pre>and g is the current_depth in DFS or BFS search</pre><pre>f = h(move,target) + g</pre><p>with the given details the implementation of the algorithm is straight forward.</p><h3>Building GUI with TKinter</h3><p>Tkinter is Python’s de-facto standard GUI (Graphical User Interface) package. It is a thin object-oriented layer on top of Tcl/Tk. It provides various configurable GUI widgets and utilities.</p><p>The complete coding approach of A* algorithm is already discussed above which is integrated with the Tkinter UI, built as follows:</p><h4>Setting up the Frame</h4><p>Inside the root a frame widget is defined with all the other widgets. The label , reset button and speed control buttons are placed, along with the puzzle objects.</p><pre>self.label = tk.Label(self, text=<strong>&quot;Let&#39;s solve the eight puzzle Problem&quot;</strong>, font=(<strong>&#39;Verdana&#39;</strong>, 15, <strong>&#39;bold&#39;</strong>))<br>self.label.pack(side=tk.TOP)<br>self.score = tk.Label(self, text=<strong>&quot; &quot;</strong>, font=(<strong>&#39;Verdana&#39;</strong>, 10, <strong>&#39;bold&#39;</strong>))<br>self.score.pack(side=tk.TOP, anchor=tk.NE)<br>self.reset = tk.Button(self, text=<strong>&quot;Reset&quot;</strong>, bg=<strong>&quot;grey&quot;</strong>, fg=<strong>&quot;white&quot;</strong>, command=self.stop_animation)<br>self.reset.pack(side=tk.LEFT, anchor=tk.N)<br>self.increase_speed = tk.Button(self, text=<strong>&quot;inc_speed&quot;</strong>, bg=<strong>&quot;grey&quot;</strong>, fg=<strong>&quot;white&quot;</strong>, command=self.inc_speed)<br>self.increase_speed.pack(side=tk.RIGHT, anchor=tk.N)<br>self.decrease_speed = tk.Button(self, text=<strong>&quot;dec_speed&quot;</strong>, bg=<strong>&quot;grey&quot;</strong>, fg=<strong>&quot;white&quot;</strong>, command=self.dec_speed)<br>self.decrease_speed.pack(side=tk.RIGHT, anchor=tk.N)</pre><pre>// in init function<br>self.puzzle_src = Puzzle(self, {<strong>&quot;tile_color&quot;</strong>: <strong>&quot;red&quot;</strong>, <strong>&quot;text&quot;</strong>: <strong>&quot;Start Configuration&quot;</strong>})<br>self.puzzle_dest = Puzzle(self, {<strong>&quot;tile_color&quot;</strong>: <strong>&quot;blue&quot;</strong>, <strong>&quot;text&quot;</strong>: <strong>&quot;Destination Configuration&quot;</strong>})</pre><p>The puzzle widget is created by arranging buttons in a two-dimensional grid in a separate Puzzle class inheriting the frame widget.</p><pre>def draw_puzzle(self):<br>    for i in range(3):<br>        for j in range(3):<br>            self.b[i].append(self.button())<br>            self.b[i][j].config(command=lambda row=i, col=j: self.fill(row, col))<br>            self.b[i][j].grid(row=i, column=j)</pre><pre>def fill(self, i, j):<br>    self.b[i][j].config(text=self.index, state=tk.DISABLED, bg=<strong>&quot;black&quot;</strong>, fg=<strong>&quot;white&quot;</strong>)<br>    self.algo_value[i * 3 + j] = self.index<br>    self.index += 1<br>    if self.index == 9:<br>        self.mark_tile()<br>        self.val.config(text=str(self.algo_value))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2ScvbibIsOMilvJ2RyLsxw.png" /><figcaption>Layout GUI using TKinter</figcaption></figure><h4>Integrating with the Algorithm</h4><p>Recursive A* implementation is used as follows :</p><pre>def gui_search(self, src, target, visited_states, g=0):<br>    if src == target or self.stop:<br>        self.puzzle_src.set_state(target, self.speed) //update state<br>        return True<br>    visited_states.append(src)<br>    adj = possible_moves(src, visited_states)<br>    scores = []<br>    selected_moves = []<br>    for move in adj: scores.append(h(move) + g)<br>    if len(scores) == 0:<br>        min_score = 0<br>    else:<br>        min_score = min(scores)<br>    for i in range(len(adj)):<br>        if scores[i] == min_score: selected_moves.append(adj[i])<br>    for move in selected_moves:<br>        self.set_score(min_score, g + 1)<br>        self.puzzle_src.set_state(move, self.speed) //update state<br>        if self.gui_search(move, target, visited_states, g + 1): return True<br>    return False</pre><pre>// the stop flag is set by the reset button to stop algorithm execution<br>// the speed variable is used to control the rate of display by //calling python sleep</pre><pre>// in puzzle&#39;s set_state</pre><pre>def set_state(self, move: list, speed: float):<br>    curr_row, curr_col = self.get_corr(self.algo_value.index(-1))<br>    new_row, new_col = self.get_corr(move.index(-1))<br>    b1, b2 = self.b[curr_row][curr_col], self.b[new_row][new_col]<br>    prop1, prop2 = self.get_prop(b1), self.get_prop(b2)<br>    self.set_prop(prop2, b1)<br>    self.set_prop(prop1, b2)<br>    self.algo_value = move[:]<br>    self.update()<br>    sleep(speed)</pre><p>The algorithm runs in parallel in a separate thread which is initialized as follows :</p><pre>// called in init function<br>def start_background_task(self):<br>    self.t1 = Thread(target=self.algo_update)<br>    self.t1.setDaemon(True)<br>    self.t1.start()</pre><pre>// function that executes the algorithm in parallel<br>def algo_update(self):<br>    while True:<br>        while not (self.puzzle_src.is_set() and self.puzzle_dest.is_set()) or self.done:<br>            if self.stop is True: self.done = False<br>        self.stop = False<br>        visited_states = []<br>        res = self.gui_search(self.puzzle_src.algo_value, self.puzzle_dest.algo_value, visited_states)<br>        if self.stop is True:<br>            messagebox.showinfo(<strong>&quot;Debug&quot;</strong>, <strong>&quot;Resetting Widgets&quot;</strong>)<br>            self.reset_puzzle()<br>        elif res is True:<br>            messagebox.showinfo(<strong>&quot;Debug&quot;</strong>, <strong>&quot;solution is reached !!&quot;</strong>)<br>        elif not res:<br>            messagebox.showinfo(<strong>&quot;Debug&quot;</strong>, <strong>&quot;solution does not exist&quot;</strong>)<br>        self.done = True</pre><p>The speed of the algorithm in controlled by setting the speed variable to a value used in the python sleep function. The implementation of the remaining helper and handler functions are simple and can be found here.</p><blockquote>check out the full code here in python : <a href="https://github.com/praguna/ai-puzzels/tree/master/eight_puzzle">https://github.com/praguna/ai-puzzels/tree/master/eight_puzzle</a><br>clone this repository and run the main function</blockquote><h4>Verifying it Works</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*sJ-LKKj7xF32i9I8MvBh2w.gif" /><figcaption>Visualization of Eight Puzzle</figcaption></figure><blockquote>THANKS FOR GOING THROUGH, HAVE A NICE DAY :)</blockquote><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/A*_search_algorithm">A* search algorithm - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/15_puzzle#Solvability">15 puzzle</a></li><li><a href="https://wiki.python.org/moin/TkInter">TkInter - Python Wiki</a></li><li><a href="https://www.geeksforgeeks.org/difference-between-bfs-and-dfs/">Difference between BFS and DFS - GeeksforGeeks</a></li><li><a href="https://github.com/praguna/ai-puzzels/">praguna/ai-puzzels</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b90f80ba178" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/solving-eight-puzzle-problem-and-its-visualization-in-tkinter-8b90f80ba178">The Eight Puzzle Problem</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka-Redis-Go]]></title>
            <link>https://medium.com/@praguna/simple-kafka-redis-go-application-d97e6f80afd4?source=rss-1d2721e632bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d97e6f80afd4</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Praguna Manvi]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 15:10:11 GMT</pubDate>
            <atom:updated>2020-08-27T10:39:01.939Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Simple Kafka-Redis-Go Application</strong></h3><h3><strong>Introduction</strong></h3><p>This article focuses on the development of kafka-redis integrated application in Go for starters. The application pushes like event of video meta data into a kafka-topic which is consumed by a kafka-consumer performing redis updates. The go-clients for kafka and redis used here are confluent-kafka-go and redigo/redis. The application can easily be extended by adding more functionalities on top of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*bhUtNMhWzCnKPybcFUYwYg.jpeg" /><figcaption>Kafka-Redis-Go</figcaption></figure><blockquote><strong>Setting up the requirements</strong></blockquote><h3><strong>Kafka</strong></h3><p>Kafka is a distributed streaming platform that can publish and subscribe to streams of records and fault tolerant storage. Here a real-time streaming application shall be built transforming the streams of data captured.</p><p>Setting up of a single node kafka-local-cluster is as follows :</p><p>0. <a href="https://linuxize.com/post/install-java-on-ubuntu-18-04/">Download and Install java</a><br> 1. Download the latest code and un-tar it<br> &gt; tar -xzf kafka_2.13–2.6.0.tgz<br> &gt; cd kafka_2.13–2.6.0<br> 2. Start the zookeeper server, which is used by kafka for configuration and synchronization<br> &gt; bin/zookeeper-server-start.sh config/zookeeper.properties<br> 3. Start the kafka server.<br> &gt; bin/kafka-server-start.sh config/server.properties</p><h3>Redis</h3><p>Redis is an in-memory data structure store, used as a database, cache and message broker. It provides supports for various data structures such as strings, hashes, lists, sets, sorted sets with range queries etc. It also allows various levels of disk-persistence and has in-built replication.</p><p>Setting up of a single node local-redis-server is as follows:</p><p>1.Install dependencies<br> &gt; sudo apt-get update &amp;&amp; sudo apt-get upgrade<br> &gt; sudo apt install make gcc libc6-dev tcl<br> 2. Download and extract stable redis code<br> &gt; wget <a href="http://download.redis.io/redis-stable.tar.gz">http://download.redis.io/redis-stable.tar.gz</a><br> &gt; tar xvzf redis-stable.tar.gz<br> &gt; cd redis-stable<br> &gt; sudo make install<br> 3. Ensure installation is successful<br> &gt; make test<br> 4. Start the Redis server<br> &gt; src/redis-server</p><h3><strong>Application</strong></h3><p>1. Golang can be installed and configured by <a href="https://www.linode.com/docs/development/go/install-go-on-ubuntu/">following this page</a>. <br> 2. Installing librdkafka required by confluent-kafka-go <br> &gt; sudo apt-get install -y librdkafka-dev<br> 3. Clone the application repository and inside the GOPATH <br> &gt; cd $GOPATH/src/<br> &gt; git clone <a href="https://github.com/praguna/video-feed.git">https://github.com/praguna/video-feed.git</a><br> &gt; go mod vendor &amp;&amp; go mod tidy<br> 4. Start the Server<br> &gt; go run .</p><blockquote><strong>Let us look in detail</strong></blockquote><h3><strong>File Structure</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*vSE1o0IakIgIvGsnP1tnXA.png" /><figcaption>Project File Structure</figcaption></figure><p>The file structure follows three packages :<br> 1. redis : contains redis handlers and data models are defined.<br> 2. kafka : contains producer and consumer utilities.<br> 3. main : contains the main function and route handlers.</p><h3><strong>Populating Redis</strong></h3><p>A utility function is written in redis package that randomly populates redis with some video meta data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*f3Ka_AEWXRiGvyuVt1p7aA.png" /><figcaption>populate-video.go</figcaption></figure><p>Run it as follows.<br> &gt; go run . populate 5 ( creates 5 entries)</p><h3>Kafka Producer</h3><p>The producer is defined in the kafka package which uses produce method to push the message into kafka stream asynchronously using delivery channels. Topic and partitions are defined along with byte array payload.</p><p>kafka.NewProducer(&amp;kafka.ConfigMap{“bootstrap.servers”: broker}) <br> // is used to initialize the producer globally with broker being comma // separated port addresses</p><p>Below is the producer method.</p><pre>// producer.go<br>func Produce(topic string, value string){<br> deliveryChan := make(chan kafka.Event)<br> err := producer.Produce(&amp;kafka.Message{<br>  TopicPartition: kafka.TopicPartition{Topic: &amp;topic, Partition: kafka.PartitionAny},<br>  Value:          []byte(value),<br>  Headers:        []kafka.Header{{Key: &quot;videoFeed&quot;, Value: []byte(&quot;video feed header value&quot;)}},<br> }, deliveryChan)</pre><pre>e := &lt;-deliveryChan<br> m := e.(*kafka.Message)</pre><pre>if m.TopicPartition.Error != nil {<br>  log.Printf(&quot;Delivery failed: %v\n&quot;, m.TopicPartition.Error)<br> } else {<br>  log.Printf(&quot;Delivered message to topic %s [%d] at offset %v\n&quot;,<br>   *m.TopicPartition.Topic, m.TopicPartition.Partition, m.TopicPartition.Offset)<br> }<br> if err!=nil{<br>  log.Printf(&quot;Error in writing value : %v \n&quot;,err)<br> }<br> close(deliveryChan)<br>}</pre><h3>Kafka Consumer</h3><p>In the consumer package consumer is defined by configuring the brokers, group-id and other standard configurations in confluent-kafka-go. It then subscribes to topic and starts listening for events in an infinite loop.</p><pre>// consumer.go<br>func Consumer(topics []string){<br> group := &quot;videoFeed&quot;<br> sigchan := make(chan os.Signal, 1)<br> signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)<br> broker := &quot;localhost:9092,localhost:9093&quot;<br> c, err := kafka.NewConsumer(&amp;kafka.ConfigMap{<br>  &quot;bootstrap.servers&quot;:               broker,<br>  &quot;group.id&quot;:                        group,<br>  &quot;session.timeout.ms&quot;:              6000,<br>  &quot;go.events.channel.enable&quot;:        true,<br>  &quot;go.application.rebalance.enable&quot;: true,<br> })<br> if err != nil {<br>  log.Panicf(&quot;Failed to create consumer: %s\n&quot;, err)<br> }<br> log.Printf(&quot;Created Consumer %v\n&quot;, c)<br> err = c.SubscribeTopics(topics, nil)<br> for {<br>  select {<br>  case sig := &lt;-sigchan:<br>   log.Printf(&quot;Caught signal %v: terminating\n&quot;, sig)<br>   _ = c.Close()<br>   os.Exit(1)</pre><pre>case ev := &lt;-c.Events():<br>   switch e := ev.(type) {<br>   case kafka.AssignedPartitions:<br>    c.Assign(e.Partitions)<br>   case kafka.RevokedPartitions:<br>    c.Unassign()<br>   case *kafka.Message:<br>    handleRedis(*e.TopicPartition.Topic, string(e.Value))<br>   case kafka.PartitionEOF:<br>    log.Printf(&quot;%% Reached %v\n&quot;, e)<br>   case kafka.Error:<br>    log.Printf(&quot;%% Error: %v\n&quot;, e)<br>   }<br>  }<br> }<br>}</pre><p>Handle redis method updates redis based on the event. Here, it is done for likes topic.</p><pre>// consumer.go<br>func handleRedis(topic string, value string){<br>   switch topic {<br>   case &quot;likes&quot;:<br>      err := redis.AddLike(value)<br>      if err == redis.VideoNoError{<br>         log.Printf(&quot;Video Id Invalid : %v, topic : %v, id : %v&quot;,err,topic,value)<br>      }else if err!= nil{<br>         log.Println(err)<br>      }else {<br>         log.Printf(&quot;redis updated for topic %v : %v&quot;,topic,value)<br>      }<br>   }<br>}</pre><h3>Redis Connection Pool</h3><p>Instead of dialing out each connection. It is better to reserve a pool of connections and use them in the application. Video Structure is defined to map redis entries in handlers.</p><pre>var Pool *redis.Pool<br><br>type Video struct{<br>   Title string `redis:&quot;title&quot;`<br>   Category string `redis:&quot;category&quot;`<br>   Likes int `redis:&quot;likes&quot;`<br>}<br><br>func Init(){<br>   Pool = &amp;redis.Pool{<br>      MaxIdle:     10,<br>      IdleTimeout: 240 * time.Second,<br>      Dial: func() (redis.Conn, error) {<br>         return redis.Dial(&quot;tcp&quot;, &quot;localhost:6379&quot;)<br>      },<br>   }<br>}</pre><h3>Redis Handlers</h3><p>Redis handler perform updates on the likes in a sorted set and also in video meta data.</p><pre>// redis/goHandlers.go<br>func AddLike(id string) error{<br> conn := Pool.Get()<br> defer conn.Close()<br> exists, err := redis.Int(conn.Do(&quot;EXISTS&quot;, &quot;video:&quot;+id))<br> if err != nil {<br>  return err<br> } else if exists == 0 {<br>  return VideoNoError<br> }<br> err = conn.Send(&quot;MULTI&quot;)<br> if err != nil {<br>  return err<br> }<br> err = conn.Send(&quot;HINCRBY&quot;, &quot;video:&quot;+id, &quot;likes&quot;, 1)<br> if err != nil {<br>  return err<br> }<br> err = conn.Send(&quot;ZINCRBY&quot;, &quot;likes&quot;, 1, id)<br> if err != nil {<br>  return err<br> }<br> _, err = conn.Do(&quot;EXEC&quot;)<br> if err != nil {<br>  return err<br> }<br> return nil<br>}</pre><p>Also returns the video data on get request.</p><pre>// redis/goHandlers.go<br>func VideoDisplay(id string) (*Video,error){<br>conn := Pool.Get()<br> defer conn.Close()<br> values, err := redis.Values(conn.Do(&quot;HGETALL&quot;, &quot;video:&quot;+id))<br> if err != nil {<br>  return nil, err<br> } else if len(values) == 0 {<br>  return nil, VideoNoError<br> }<br> var video Video<br> err = redis.ScanStruct(values,&amp;video)<br> if err != nil {<br>  return nil, err<br> }<br> return &amp;video,nil<br>}</pre><p>The popular videos are returned by selecting the ids with most likes using ‘zrevrange’ called by their limit.</p><pre>// redis/goHandlers.go<br>func GetPopular(x int) ([]*Video , error){<br> conn := Pool.Get()<br> defer conn.Close()<br> for {<br>  _, err := conn.Do(&quot;WATCH&quot;, &quot;likes&quot;)<br>  if err != nil {<br>   return nil, err<br>  }<br>  ids, err := redis.Strings(conn.Do(&quot;ZREVRANGE&quot;, &quot;likes&quot;, 0, x))<br>  if err != nil {<br>   return nil, err<br>  }<br>  err = conn.Send(&quot;MULTI&quot;)<br>  if err != nil {<br>   return nil, err<br>  }<br>  for _, id := range ids {<br>   err := conn.Send(&quot;HGETALL&quot;, &quot;video:&quot;+id)<br>   if err != nil {<br>    return nil, err<br>   }<br>  }<br>  replies, err := redis.Values(conn.Do(&quot;EXEC&quot;))<br>  if err == redis.ErrNil {<br>   log.Println(&quot;trying again&quot;)<br>   continue<br>  } else if err != nil {<br>   return nil, err<br>  }<br>  videos := make([]*Video, x)<br>  for i, reply := range replies {<br>   var video Video<br>   if i == x{<br>    break<br>   }<br>   err = redis.ScanStruct(reply.([]interface{}), &amp;video)<br>   if err != nil {<br>    return nil, err<br>   }<br>   videos[i] = &amp;video<br>  }<br>  return videos, nil<br> }<br>}</pre><h3>Route Handlers</h3><p>The application basically has three route handlers : <br> 1. VideoHandler : displays the video meta data fetched from redis.<br> 2. LikeHandler : puts a topic on kafka, which results in redis updates once it is consumed.<br> 3. PopularHandler : displays the video meta data in descending order of likes.</p><p>The implementation is LikeHandler requires a call to the producer.</p><pre>// main/goHandlers.go<br>func LikeHandler(w http.ResponseWriter, r *http.Request){<br>   if r.Method != http.MethodGet {<br>      w.Header().Set(&quot;Allow&quot;, http.MethodGet)<br>      http.Error(w, http.StatusText(405), 405)<br>      return<br>   }<br>   id := mux.Vars(r)[&quot;id&quot;]<br>   if id == &quot;&quot; {<br>      http.Error(w, http.StatusText(400), 400)<br>      return<br>   }<br>   go kafka.Produce(&quot;likes&quot;,id)<br>}</pre><p>The video handler is a simple get request service.</p><pre>func VideoHandler(w http.ResponseWriter, r *http.Request){<br>   if r.Method != http.MethodGet {<br>      w.Header().Set(&quot;Allow&quot;, http.MethodGet)<br>      http.Error(w, http.StatusText(405), 405)<br>      return<br>   }<br>   id := mux.Vars(r)[&quot;id&quot;]<br>   if id == &quot;&quot; {<br>      http.Error(w, http.StatusText(400), 400)<br>      return<br>   }<br>   vd, err := redis.VideoDisplay(id)<br>   if err == redis.VideoNoError {<br>      http.Error(w, http.StatusText(400),400)<br>      return<br>   } else if err != nil {<br>      http.Error(w, http.StatusText(500), 500)<br>      return<br>   }<br>   _, err = fmt.Fprintf(w, &quot;Id-&gt;%s\n&quot; +<br>      &quot;Title-&gt;%s\n&quot;+<br>      &quot;category-&gt;%s\n&quot;+<br>      &quot;likes-&gt;%d\n&quot;,id, vd.Title, vd.Category, vd.Likes)<br>   if err !=nil{<br>      http.Error(w,http.StatusText(500),500)<br>   }<br>}</pre><p>The popular videos are returned with similar implementation as above</p><pre>func PopularHandler(w http.ResponseWriter, r *http.Request){<br> if r.Method != http.MethodGet {<br>  w.Header().Set(&quot;Allow&quot;, http.MethodGet)<br>  http.Error(w, http.StatusText(405), 405)<br>  return<br> }<br> x := mux.Vars(r)[&quot;num&quot;]<br> if x == &quot;&quot; {<br>  x = &quot;3&quot;<br> }<br> xInt,err := strconv.Atoi(x)<br> if err != nil {<br>  http.Error(w, http.StatusText(400), 400)<br>  return<br> }<br> vds, err := redis.GetPopular(xInt)<br> if err != nil {<br>  http.Error(w, http.StatusText(500), 500)<br>  return<br> }<br> c:=0<br> for i, vd := range vds{<br>  if vd == nil{<br>   break<br>  }<br>  _, err = fmt.Fprintf(w, &quot;No-&gt;%d\n&quot; +<br>   &quot;Title-&gt;%s\n&quot;+<br>   &quot;category-&gt;%s\n&quot;+<br>   &quot;likes-&gt;%d\n\n&quot;,i,vd.Title, vd.Category, vd.Likes)<br>  c = c + 1<br> }<br> if c == 0{<br>  fmt.Fprintln(w,&quot;No video liked yet&quot;)<br> }<br>}</pre><h3>Configuring Routes</h3><blockquote>gorilla/mux library is used for route configuration.</blockquote><p>The count of number of popular videos to display is passed as url variable num in <em>popular</em> route and id in <em>video</em>, <em>like</em> routes.</p><pre>router.HandleFunc(&quot;/detail/{id}&quot;, VideoHandler)<br><br>router.HandleFunc(&quot;/like/{id}&quot;, LikeHandler)<br><br>router.HandleFunc(&quot;/popular/{num[0-9]+}&quot;, PopularHandler)</pre><h3>Initializing redis, producer and consumer</h3><p>Before starting the server :<br> 1. The producer variable is initialized using go routine.<br> 2. The consumer is initialized starting its event listening using go routine and subscribes to the topics supplied.<br> 3. Redis pool is initialized.<br> 4. Finally, the server is asked to serve at port 4000.</p><pre>redis.Init()<br>go kafka.InitProducer()<br>go kafka.Consumer([]string{&quot;likes&quot;, &quot;upload&quot;})<br>http.Handle(&quot;/&quot;, router)<br>http.ListenAndServe(&quot;:4000&quot;, nil)</pre><h3>Verifying that everything Works</h3><blockquote>checkout the full code here — <a href="https://github.com/praguna/video-feed">https://github.com/praguna/video-feed</a></blockquote><pre>&gt; go run . populate 5<br>Adding ids : <br>video:BpLnfgD<br>video:3qNfHK6<br>video:wzDkh9h<br>video:S9jZ8uV<br>Finished Populating Redis with 5 entries</pre><pre>// after starting the servers</pre><pre>&gt; curl localhost:4000/detail/wzDkh9h<br>Id-&gt;wzDkh9h<br>Title-&gt;3fhfUVu<br>category-&gt;news<br>likes-&gt;0</pre><pre>&gt; curl localhost:4000/like/wzDkh9h<br>&gt; curl localhost:4000/detail/wzDkh9h<br>Id-&gt;wzDkh9h<br>Title-&gt;3fhfUVu<br>category-&gt;news<br>likes-&gt;1</pre><pre>// getting popular videos</pre><pre>&gt; curl localhost:4000/popular/3<br>No-&gt;0<br>Title-&gt;Smok3s8<br>category-&gt;music<br>likes-&gt;3</pre><pre>No-&gt;1<br>Title-&gt;3fhfUVu<br>category-&gt;news<br>likes-&gt;1</pre><pre>No-&gt;2<br>Title-&gt;EqLb3dl<br>category-&gt;news<br>likes-&gt;1</pre><blockquote><strong><em>Thanks for going through !! Have a nice day :)</em></strong></blockquote><h4><em>References</em></h4><ul><li><a href="https://www.linode.com/docs/applications/big-data/how-to-install-and-configure-a-redis-cluster-on-ubuntu-1604/">How to Install and Configure a Redis Cluster on Ubuntu 16.04</a></li><li><a href="https://kafka.apache.org/documentation/#quickstart">Apache Kafka</a></li><li><a href="https://redis.io/">Redis - The Real-time Data Platform</a></li><li><a href="https://www.alexedwards.net/blog/working-with-redis">Working with Redis in Go</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d97e6f80afd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>