<?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 Abhiram R Pai on Medium]]></title>
        <description><![CDATA[Stories by Abhiram R Pai on Medium]]></description>
        <link>https://medium.com/@abhirampai?source=rss-a8ddc8e58b9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*noNoraQlXqVek4YuiU50ww.jpeg</url>
            <title>Stories by Abhiram R Pai on Medium</title>
            <link>https://medium.com/@abhirampai?source=rss-a8ddc8e58b9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:17:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhirampai/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[Enhance Your Rails App with Class-Level Callbacks]]></title>
            <link>https://medium.com/geekculture/how-to-use-callback-directly-on-the-class-3887af3d1e88?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3887af3d1e88</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rubygems]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 02:42:57 GMT</pubDate>
            <atom:updated>2024-06-19T12:49:14.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*4xp8ubw9bEGJc3Tm.png" /></figure><h3>Introduction</h3><p>Last week, I worked on a feature requiring the result of an ActiveJob to perform some processing. The job resided within a gem, and I needed to modify the gem to call a method on the class in the host application. This situation necessitated a class-level callback, as the result had to be processed independently of any class instances.</p><h3>Understanding Callbacks in Rails</h3><p><strong>Callbacks</strong> are methods that get called at certain points of an object’s lifecycle. They are widely used in Rails to run code automatically during the creation, updating, and deletion of objects. To learn more about callbacks, you can refer to the <a href="https://guides.rubyonrails.org/active_record_callbacks.html">Rails Guide on Callbacks</a>.</p><h3>Example Code</h3><h4>ActiveJob in the Gem</h4><p>Here is the job in the gem that needs to call a method on the host application’s class:</p><pre># ActiveJob in the gem<br>class MyJob &lt; ActiveJob::Base<br>  def perform<br>    result = # perform the job and get the result<br>    if ModelName.respond_to?(:after_result, true)<br>      ModelName.after_result { result }<br>    end<br>  end<br>end</pre><p>In this snippet, we check if the class ModelName in the host application has a class method after_result. If it does, we pass the job result to this method using a block.</p><h4>Host Application Class Method</h4><p>In the host application, we define the after_result method on the class:</p><pre># Class in host application<br>class ModelName<br>  def self.after_result<br>    result = yield if block_given?<br>    process(result) if result.present?<br>  end<br><br>  def self.process(result)<br>    # process the result<br>  end<br>end</pre><p>Here, yield passes the job result to the after_result method, which then processes it if it&#39;s present.</p><h4>Instance Method Callbacks</h4><p>If we were to use instance methods and Rails callbacks, it would look slightly different. Callbacks can be defined on class instances using define_callbacks and set_callback.</p><pre># Class in host application<br>class ModelName<br>  define_callbacks :result<br>  set_callback :result, :after, :after_result, if: -&gt; { respond_to?(:after_result, true) }<br><br>  def after_result<br>    result = yield if block_given?<br>    process(result) if result.present?<br>  end<br><br>  def process(result)<br>    # process the result<br>  end<br>end</pre><p>In this example, after_result is an instance method. We define a :result callback and specify that the after_resultmethod should run after the :result callback is triggered.</p><h4>Modified ActiveJob in the Gem</h4><p>To use instance method callbacks, modify the job as follows:</p><pre># ActiveJob in the gem<br>class MyJob &lt; ActiveJob::Base<br>  def perform(instance)<br>    result = # perform the job and get the result<br>    if instance.respond_to?(:after_result, true)<br>      instance.run_callbacks(:result) { result }<br>    end<br>  end<br>end</pre><p>Here, instance is an instance of ModelName from the host application. We check if it responds to after_result and run the :result callbacks.</p><h3>Conclusion</h3><p>We’ve covered how to use a class method as a callback and how to utilize Rails’ set_callback for instance methods. Depending on whether your use case requires class-level or instance-level methods, you can implement the appropriate callback mechanism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3887af3d1e88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-use-callback-directly-on-the-class-3887af3d1e88">Enhance Your Rails App with Class-Level Callbacks</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going ballistic with Rails upgrade]]></title>
            <link>https://abhirampai.medium.com/going-ballistic-with-rails-upgrade-75bce23af84e?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/75bce23af84e</guid>
            <category><![CDATA[ruby-on-rails-gems]]></category>
            <category><![CDATA[ruby-on-rails-developers]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails-gems]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Fri, 24 May 2024 02:45:12 GMT</pubDate>
            <atom:updated>2024-05-24T02:45:12.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lv8BtCkLhYssGREi.png" /></figure><p>The journey of moving from Rails 4.2 to Rails 5 was nothing short of a rollercoaster ride. This blog is all about what were the steps taken in order to achieve the changes faster and effectively so that you won’t have to face the challenges in future rails upgrades.</p><p><strong>Always have a better code coverage ( &gt; 85% atleast )</strong></p><p>Code coverage ensures that we have tested most parts of our code and this would help in the rails upgrade. So what we followed is to increase the code coverage step by step.</p><p>First we went ahead and checked out which all files didn’t have any specs and added those first. This step alone helped us to increase code coverage to more than 80%.</p><p>Secondly we checked into the rcov report to find which all files had the least coverage and increased their coverage.</p><p>Thirdly we looked into any unused methods and legacy files that could be removed.</p><p>Finally we managed to cross the magic 90% code coverage.</p><p><strong>Fix all deprecations warnings</strong></p><p>This step is related to the previous step because when we run the test we could get a lot of deprecations warnings meaning those could fail in the future upgrade of rails.</p><p>IMO we need to do this step after upgrading to a new rails version too since we don’t have to tackle them in future upgrade.</p><p><strong>Upgrading Rails</strong></p><p>Now we are ready to upgrade our app’s rails version. We need to add the rails version to the gemfile and hit bundle upgrade rails , then we can use the task rails app:update to update the config files. We could skip that step and go with our old config if we feel like but its worth checking the changes.</p><p><strong>Upgrading Gems</strong></p><p>Next step is to find the compatible gem for the updated version of rails. For this I used <a href="https://railsbump.org/">RailsBump</a>. This step is a little tricky if you are using a patched version for any gem since you would manually have to update the patched version also to support the new rails version. Same with in-house gems.</p><p><strong>Final Steps</strong></p><p>Now we have to repeat step 2 i.e, fixing the deprecation warnings and that would also give us any failure we have to fix in our test files or the app logic. And finally we have to test our App and deploy the new version of rails .</p><p>Following these above steps helped us to move faster from Rails 4 to Rails 5 to now to Rails 6 and we are hoping to keep up the momentum.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75bce23af84e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How ChatGPT helped me to build a ruby gem]]></title>
            <link>https://abhirampai.medium.com/how-chatgpt-helped-me-to-build-a-ruby-gem-0835573540c0?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0835573540c0</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[rails-gems]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 05:39:42 GMT</pubDate>
            <atom:updated>2024-03-22T05:40:02.698Z</atom:updated>
            <content:encoded><![CDATA[<p>In my free time, I wanted to learn to create something that would benefit not only my productivity but also help in my work so I decided to create a gem that can list all deprecated methods in a ruby on rails application. And that is how I approached ChatGPT to create a gem.</p><p>Initially I went on and asked ChatGPT on how to create a rails gem and its reply contained the steps to setup the ruby gem repo and also tips document, license, install and publish the gem.</p><p>After setting up the gem repo I went over and asked it how to parse over all the rb files in a host application and return methods that are not used in the application any more.</p><p>It suggested using the parser gem to parse the files to ast(Abstract Syntax Tree) format and traverse the tree and initially find the defined methods and then find the invoked methods.</p><p>Finally we just have to remove invoked methods from defined methods.</p><p>ChatGPT initially didn’t return the code on how to traverse the ast tree and find the methods, then I had to specifically ask it to return the logic for it.</p><p>And finally it was time to do some final adjustments like adding a cli class to run the gem in cli.</p><p>Also added a file that would list the methods that are deprecated and also show the exact line number in the file in which the method is defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*d2Fu8fsIRXrnWyBj1YL2Yg.gif" /></figure><p>The gem is still in very early stage and doesn’t look into all the edge cases.</p><p>Here is the link to the gem in Github -&gt; <a href="https://github.com/abhirampai/deprecated_methods">https://github.com/abhirampai/deprecated_methods</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0835573540c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using stimulus with rails engine]]></title>
            <link>https://medium.com/geekculture/using-stimulus-with-rails-engine-93310d038079?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/93310d038079</guid>
            <category><![CDATA[rails-engine]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[stimulus]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 15:26:33 GMT</pubDate>
            <atom:updated>2023-11-03T15:26:33.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kt_9EBKdrCs4108TcAKOxg.png" /></figure><p>During my exploration with ruby on rails, I stumbled upon rails engine and how we can use it to encapsulate or make a ruby on rails application modular by splitting some functionality into smaller manageable sizes. So to learn more about rails engine I started off with creating a mountable rails engine.</p><pre>rails plugin test_rails_engine --mountable</pre><p>Now we have the basic rails engine layout in place which looks similar to the rails application but without the javascript side of things.</p><p>Now to add stimulus to the rails engine we can go ahead and create a javascripts/test_rails_engine folder under assets folder.</p><p>Inside the javascripts/test_rails_engine folder we will add the application.js file with the following content:</p><pre>//= require ./stimulus/init<br>//= require ./controllers/hello_controller</pre><p>Now create a folder stimulus inside the javascripts/test_rails_engine folder and an init.js file inside of stimulus folder with the following content:</p><pre>import {<br>  Application,<br>  Controller,<br>} from &quot;https://unpkg.com/@hotwired/stimulus/dist/stimulus.js&quot;;<br>window.Stimulus = Application.start();</pre><p>Now lets have a hello_controller.js file inside of controllers folder inside of javascripts/test_rails_engine folder with the following content:</p><pre>Stimulus.register(<br>  &quot;hello&quot;,<br>  class extends Controller {<br>    connect () {<br>      console.log(&quot;hello&quot;)<br>    }<br>);</pre><p>Now we have to add the application.js to the manifest so lets add the following to test_rails_engine.manifest.js:</p><pre><br>//= link_directory ../stylesheets/test_rails_engine .css<br>//= link_directory ../javascripts/test_rails_engine .js</pre><p>Now lets add the javascript tag into the application.html.erb file under views/layouts/test_rails_engine:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Test rails engine&lt;/title&gt;<br>  &lt;%= csrf_meta_tags %&gt;<br>  &lt;%= csp_meta_tag %&gt;<br><br>  &lt;%= stylesheet_link_tag    &quot;test_rails_engine/application&quot;, media: &quot;all&quot; %&gt;<br>  &lt;%= javascript_include_tag &quot;test_rails_engine/application&quot;, &quot;data-turoblinks-track&quot;: &quot;reload&quot;, type: &quot;module&quot; %&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;%= yield %&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now lets create a root route by adding the following to the routes.rb:</p><pre>TestRailsEngine::Engine.routes.draw do<br>  resource :hello, only: :show<br>  root &quot;hello#show&quot;<br>end</pre><p>Then lets create hello_controller.rb inside of controller:</p><pre>module TestRailsEngine<br>  class HelloController &lt; ApplicationController<br>    def show; end<br>  end<br>end</pre><p>Then a simple view under views/test_rails_engine/hello/show.html.erb:</p><pre>&lt;p data-controller=&quot;hello&quot;&gt;hello&lt;/p&gt;</pre><p>Now lets go ahead and test if its working as expected by connecting the engine with rails application, add the following to the rails application gemfile:</p><pre>gem &quot;test_rails_engine&quot;, path: &quot;path to the gem&quot;</pre><p>Then mount the rails engine in routes.rb</p><pre>mount TestRailsEngine::Engine =&gt; &quot;/test_rails_engine&quot;</pre><p>Then we have to add the javascript and css files into the main application’s manifest file:</p><pre>//= link test_rails_engine/application.css<br>//= link test_rails_engine/application.js</pre><p>And once we visit localhost:3000/test_rails_engine in the console we will see the hello world printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rxOTjxRebst5HJngQnamLA.png" /></figure><p>And thats how we can use stimulus inside of rails engine, attaching the github repo for the rails engine example shown above <a href="https://github.com/abhirampai/test_stimulus_rails_engine">https://github.com/abhirampai/test_stimulus_rails_engine</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93310d038079" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/using-stimulus-with-rails-engine-93310d038079">Using stimulus with rails engine</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodeBoost where you can run and refactor your code]]></title>
            <link>https://medium.com/geekculture/codeboost-where-you-can-run-and-refactor-your-code-abe449cc1063?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/abe449cc1063</guid>
            <category><![CDATA[code-runners]]></category>
            <category><![CDATA[judge0]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code-refactoring]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 07:03:47 GMT</pubDate>
            <atom:updated>2023-04-03T17:27:15.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9iOcDhYUSRVeEm77Gnvadw.png" /><figcaption>CodeBoost Logo</figcaption></figure><p>It’s been a while since I have written a blog on medium. This blog is about <a href="https://codeboost.vercel.app/">CodeBoost</a>.</p><p>CodeBoost is a code runner that allows you to refactor and run your code in one convenient location. With CodeBoost, you can improve the quality and readability of your code and then run it to see the results instantly.</p><p>So the main 2 features that CodeBoost provides are:</p><ul><li><strong>Code refactoring</strong>: CodeBoost makes it easy to refactor your code by suggesting changes that will improve its quality, readability, and performance. You can choose to refactor the whole code or part of the code by selecting the code snippet and refactoring that part.</li><li><strong>Code running</strong>: CodeBoost allows you to run your code directly from the editor, without having to switch to a different tool or environment. You can run your code as many times as you like, with different input values, and see the output and any errors or exceptions that occur. You can choose between 9 different languages which are mentioned under-supported languages.</li></ul><p><strong>Supported Languages</strong></p><ul><li>Bash</li><li>C</li><li>C++</li><li>Python</li><li>Java</li><li>Rust</li><li>Go</li><li>Ruby</li><li>JavaScript</li></ul><p>Now that we know the features of CodeBoost let&#39;s look into how each feature was built.</p><ol><li><strong>CodeRunner</strong></li></ol><p>As in my discord bot, this application also has the ability to run code but this time it&#39;s using Judge0CE API. You can know more about this in the <a href="https://rapidapi.com/judge0-official/api/judge0-ce/">RapidAPI</a> hub. Subscribe to any of the plans use the API key and boom you are ready to go. You can also follow the steps mentioned to make an API call. In this application two APIs from Judge0 were used, one to create a submission and the other one to get the details regarding the submission. You can also get the languages supported by Judge0 using the languages endpoint. In CodeBoost, I saved the language details in a JSON file because making a call to this API seemed useless.</p><p>Another main highlight is the code stub feature some languages like python has code stub which helps you to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuNrXjaF3rkUQuOCKNv-fA.png" /><figcaption>Code stub</figcaption></figure><p>2. <strong>Code Refactoring</strong></p><p>Code refactoring leverages the power of ChatGPT to refactor code. To know more about the APIs ChatGPT provides you can head over to their <a href="https://platform.openai.com/docs/api-reference/chat">API Reference Docs</a>. In this application, I have used their chat completion API, model: gpt-3.5-turbo.</p><p><strong>Building CodeBoost</strong></p><p>The application was built using React framework. In this section, I will take you through how to build CodeBoost,</p><ol><li>Create react application</li></ol><blockquote>npx create-react-app app-name</blockquote><p>2. I have used tailwind to style the components so you can either install tailwind from <a href="https://tailwindcss.com/docs/installation">tailwind docs</a>, in my case, I just pasted the CDN in index.html under public.</p><p>3. Create the components like CodeEditor, Input box, Output box, Language selector, etc.</p><p><strong>Code Editor</strong></p><p>I have used the code mirror package from <a href="https://github.com/uiwjs/react-codemirror">https://github.com/uiwjs/react-codemirror</a>. You can refer to their documentation for installation.</p><pre>import CodeMirror from &quot;@uiw/react-codemirror&quot;;<br>import { keymap } from &quot;@codemirror/view&quot;;<br>import { sublime } from &quot;@uiw/codemirror-theme-sublime&quot;;<br>import { defaultKeymap } from &quot;@codemirror/commands&quot;;<br>import { EditorView } from &quot;@codemirror/view&quot;;<br>import { mapLanguages } from &quot;./utils&quot;;<br><br>const CodeEditor = ({<br>  editorRef,<br>  selectedLanguage,<br>  value,<br>  onChange,<br>  editable,<br>  runCode,<br>}) =&gt; {<br>  const handleIndentTab = (cm) =&gt; {<br>    const spaces = Array(cm.getOption(&quot;indentUnit&quot;) + 1).join(&quot; &quot;);<br>    cm.replaceSelection(spaces);<br>  };<br>  const extensions = [<br>    keymap.of([<br>      {<br>        key: &quot;Mod-Enter&quot;,<br>        run: () =&gt; {<br>          if (editable) runCode();<br>          return true;<br>        },<br>      },<br>      ...defaultKeymap,<br>    ]),<br>    keymap.of([handleIndentTab]),<br>    mapLanguages(selectedLanguage)(),<br>    EditorView.lineWrapping,<br>  ];<br>  const editorHeight = &quot;calc(80vh - 165px)&quot;;<br>  return (<br>    &lt;&gt;<br>      &lt;CodeMirror<br>        ref={editorRef}<br>        value={value}<br>        extensions={extensions}<br>        theme={sublime}<br>        onChange={(instance) =&gt; onChange(instance)}<br>        height={editorHeight}<br>        editable={editable}<br>        basicSetup={{ defaultKeymap: false }}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};<br>export default CodeEditor;</pre><p>Here you might be wondering what this extension and all is about so let&#39;s dive into it,</p><p>So basically extensions are like mentioning to the code mirror package about various setup-related things for eg like language, whether the lines need to be wrapped when the width of the editor decreases, etc.</p><p>There are a lot of extensions for code mirror which you can find in the above-mentioned GitHub link.</p><p>Here as you can see I have disabled the defaultKeymap for the code mirror and have used a hotfix for enabling the ctrl + enter/cmd + enter(for mac) keybinding so that it can be used to run the code instead of moving to a new line. To know more about this you can refer to this <a href="https://github.com/uiwjs/react-codemirror/issues/356">issue</a> in GitHub.</p><p>The keymap.of([handleIndentTab]) function is to handle the indentation with space instead of tab which could be an issue when using languages like python.</p><p>The map language function maps the languages provided by judge0 to the format which the code mirror package understands.</p><pre>import { javascript } from &quot;@codemirror/lang-javascript&quot;;<br>import { python } from &quot;@codemirror/lang-python&quot;;<br>import { java } from &quot;@codemirror/lang-java&quot;;<br>import { rust } from &quot;@codemirror/lang-rust&quot;;<br>import { cpp } from &quot;@codemirror/lang-cpp&quot;;<br>import { StreamLanguage } from &quot;@codemirror/language&quot;;<br>import { go } from &quot;@codemirror/legacy-modes/mode/go&quot;;<br>import { ruby } from &quot;@codemirror/legacy-modes/mode/ruby&quot;;<br>import { shell } from &quot;@codemirror/legacy-modes/mode/shell&quot;;<br><br>export const mapLanguages = (value) =&gt; {<br>  const mappedLanguages = {<br>    javascript,<br>    python,<br>    java,<br>    rust,<br>    c: cpp,<br>    &quot;c++&quot;: cpp,<br>    go: () =&gt; StreamLanguage.define(go),<br>    ruby: () =&gt; StreamLanguage.define(ruby),<br>    bash: () =&gt; StreamLanguage.define(shell)<br>  };<br>  return mappedLanguages[value];<br>};</pre><p>The EditorView.lineWrapping extension is to wrap lines when the editor width is reduced.</p><p><strong>Input box</strong></p><pre>const CustomInput = ({ input, setInput }) =&gt; {<br>  return (<br>    &lt;textarea<br>      value={input}<br>      onChange={setInput}<br>      className=&quot;block px-1 w-full text-sm bg-gray-800 text-white border focus:ring-0 border-gray-400 mt-2&quot;<br>      rows={5}<br>    /&gt;<br>  );<br>};<br>export default CustomInput;</pre><p><strong>Output box</strong></p><pre>const OutputTerminal = ({ output, outputRef }) =&gt; {<br>  return (<br>    &lt;div<br>      ref={outputRef}<br>      className=&quot;block px-1 w-full h-36 text-sm bg-gray-800 text-white border focus:ring-0 border-gray-400 mt-2&quot;<br>    &gt;<br>      {output}<br>    &lt;/div&gt;<br>  );<br>};<br>export default OutputTerminal;</pre><p><strong>Buttons</strong></p><pre>const CodeActions = ({ runEditorCode, refactorCode, isLoading }) =&gt; {<br>  return (<br>    &lt;div className=&quot;flex md:space-x-2 w-full md:w-1/2 justify-between md:justify-end&quot;&gt;<br>      &lt;button<br>        className=&quot;disabled:opacity-75 disabled:cursor-not-allowed border border-gray-200 bg-gray-200 text-gray-700 rounded-md px-4 py-2 md:m-2 mt-2 transition duration-500 ease select-none hover:bg-gray-300 focus:outline-none focus:shadow-outline&quot;<br>        onClick={runEditorCode}<br>        disabled={isLoading}<br>      &gt;<br>        Run Code<br>      &lt;/button&gt;<br>      &lt;button<br>        className=&quot;disabled:opacity-75 disabled:cursor-not-allowed border border-gray-200 bg-gray-200 text-gray-700 rounded-md px-4 py-2 md:m-2 mt-2 transition duration-500 ease select-none hover:bg-gray-300 focus:outline-none focus:shadow-outline&quot;<br>        onClick={refactorCode}<br>        disabled={isLoading}<br>      &gt;<br>        Refactor Code<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default CodeActions;</pre><p>4. Setting up Apis</p><p><strong>Axios setup</strong></p><pre>import axios from &quot;axios&quot;;<br><br>const axiosOptions = {<br>  baseURL: &quot;https://judge0-ce.p.rapidapi.com/&quot;,<br>  params: { base64_encoded: &quot;true&quot;, fields: &quot;*&quot; },<br>  headers: {<br>    &quot;content-type&quot;: &quot;application/json&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    Authorization: `Bearer ${process.env.REACT_APP_OPEN_AI_KEY}`,<br>    &quot;X-RapidAPI-Key&quot;: process.env.REACT_APP_JUDGE0_KEY,<br>    &quot;X-RapidAPI-Host&quot;: &quot;judge0-ce.p.rapidapi.com&quot;<br>  }<br>};<br>export default axios.create(axiosOptions);</pre><p><strong>Judge0CE</strong></p><p>You can get the Judge0CE API key from the <a href="https://rapidapi.com/judge0-official/api/judge0-ce">RapidAPI</a> hub.</p><pre>import axios from &quot;./axios&quot;;<br>const createSubmission = (payload) =&gt; axios.post(&quot;submissions&quot;, payload);<br>const getSubmission = (token) =&gt; axios.get(`/submissions/${token}`);<br><br>export default { createSubmission, getSubmission };</pre><p><strong>ChatGPT</strong></p><p>You can get the ChatGPT API key from <a href="https://platform.openai.com/account/api-keys">openAI dashboard</a></p><pre>import axios from &quot;./axios&quot;;<br>const createCompletion = (payload) =&gt;<br>  axios.post(&quot;https://api.openai.com/v1/chat/completions&quot;, payload);<br>export default { createCompletion };</pre><p>5. I have used react query for optimizing the query usage this step is optional.</p><pre>import { useMutation } from &quot;react-query&quot;;<br>import runCode from &quot;../Apis/runCode&quot;;<br><br>const useCreateSubmissionsApi = () =&gt; {<br>  return useMutation((payload) =&gt; runCode.createSubmission(payload));<br>};<br>const useGetSubmissionsApi = () =&gt; {<br>  return useMutation((token) =&gt; runCode.getSubmission(token));<br>};<br>export { useCreateSubmissionsApi, useGetSubmissionsApi };</pre><pre>import { useMutation } from &quot;react-query&quot;;<br>import refactorCode from &quot;../Apis/refactorCode&quot;;<br><br>const useCreateCompletionApi = () =&gt; {<br>  return useMutation((payload) =&gt; refactorCode.createCompletion(payload));<br>};<br>export { useCreateCompletionApi };</pre><p>Now we have everything, let&#39;s put everything in one place</p><pre>import { useEffect, useRef, useState } from &quot;react&quot;;<br><br>import { assoc } from &quot;ramda&quot;;<br>import {<br>  useCreateSubmissionsApi,<br>  useGetSubmissionsApi,<br>} from &quot;../Hooks/useSubmissionsApi&quot;;<br>import CodeEditor from &quot;./CodeEditor&quot;;<br>import CustomInput from &quot;./CustomInput&quot;;<br>import LanguageSelector from &quot;./LanguageSelector&quot;;<br>import { LANGUAGE_OPTIONS } from &quot;./LanguageSelector/constants&quot;;<br>import OutputTerminal from &quot;./OutputTerminal&quot;;<br>import { decodeString, encodeString } from &quot;./utils&quot;;<br>import { OUTPUT_STATUES, DEFAULT_OUTPUT_VALUE } from &quot;./contants&quot;;<br>import CustomInputHeader from &quot;./CustomInput/Header&quot;;<br>import OutputTerminalHeader from &quot;./OutputTerminal/Header&quot;;<br>import { useCreateCompletionApi } from &quot;../Hooks/useRefactorApi&quot;;<br>import Header from &quot;./Header&quot;;<br>import CodeActions from &quot;./CodeActions&quot;;<br>const Main = () =&gt; {<br>  const outputRef = useRef(null);<br>  const editorRef = useRef(null);<br>  const [selectedLanguage, setSelectedLanguage] = useState(LANGUAGE_OPTIONS[0]);<br>  const [value, setValue] = useState(selectedLanguage?.stub);<br>  const [input, setInput] = useState();<br>  const [output, setOutput] = useState(DEFAULT_OUTPUT_VALUE);<br>  const [isLoading, setIsLoading] = useState(false);<br>  const { mutateAsync: runCode } = useCreateSubmissionsApi();<br>  const { mutateAsync: getOutput } = useGetSubmissionsApi();<br>  const { mutateAsync: getRefactoredCode } = useCreateCompletionApi();<br>  useEffect(() =&gt; {<br>    setValue(selectedLanguage?.stub);<br>  }, [selectedLanguage]);<br>  useEffect(() =&gt; {<br>    if (output?.data) {<br>      outputRef.current.scrollIntoView({ behavior: &quot;smooth&quot; });<br>    }<br>  }, [output]);<br>  const clearInput = () =&gt; {<br>    setInput(&quot;&quot;);<br>  };<br>  const handleCustomInputChange = (e) =&gt; {<br>    const { value } = e.target;<br>    setInput(value);<br>  };<br>  const runEditorCode = async () =&gt; {<br>    try {<br>      setIsLoading(true);<br>      clearOutput();<br>      const { data: submissionData } = await runCode({<br>        source_code: encodeString(value),<br>        language_id: selectedLanguage.value,<br>        stdin: encodeString(input || &quot;&quot;),<br>      });<br>      const { data: outputData } = await getOutput(submissionData?.token);<br>      if (outputData.status_id === 3) {<br>        setOutput(<br>          assoc(&quot;data&quot;, decodeString(outputData.stdout) || &quot;Empty Ouput&quot;)<br>        );<br>      } else {<br>        setOutput(assoc(&quot;data&quot;, decodeString(outputData.stderr)));<br>      }<br>      setOutput(assoc(&quot;status&quot;, OUTPUT_STATUES[outputData.status_id]));<br>    } catch (err) {<br>      console.log(err);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };<br>  const refactorCode = async () =&gt; {<br>    try {<br>      setIsLoading(true);<br>      const cursorSelection = editorRef.current.view.state.selection.main;<br>      const startRange = cursorSelection.from;<br>      const endRange = cursorSelection.to;<br>      const selectedValue =<br>        startRange !== endRange ? value.substring(startRange, endRange) : value;<br>      const { data: chatGptOutput } = await getRefactoredCode({<br>        model: &quot;gpt-3.5-turbo&quot;,<br>        messages: [{ role: &quot;user&quot;, content: `Refactor code snippet ${selectedValue}` }],<br>      });<br>      const refactoredCode = chatGptOutput.choices[0].message.content;<br>      setValue((prevValue) =&gt; prevValue.replace(selectedValue, refactoredCode));<br>    } catch (err) {<br>      console.log(err);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };<br>  const clearOutput = () =&gt; {<br>    setOutput(DEFAULT_OUTPUT_VALUE);<br>  };<br>  return (<br>    &lt;div className=&quot;flex flex-col p-4&quot;&gt;<br>      &lt;Header /&gt;<br>      &lt;div className=&quot;md:flex md:w-full mt-4 justify-between items-center&quot;&gt;<br>        &lt;LanguageSelector<br>          selectedLanguage={selectedLanguage}<br>          setSelectedLanguage={setSelectedLanguage}<br>        /&gt;<br>        &lt;CodeActions<br>          refactorCode={refactorCode}<br>          runEditorCode={runEditorCode}<br>          isLoading={isLoading}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;editor-height mt-5&quot;&gt;<br>        &lt;CodeEditor<br>          editorRef={editorRef}<br>          selectedLanguage={selectedLanguage?.title.toLowerCase()}<br>          value={value}<br>          onChange={setValue}<br>          editable={!isLoading}<br>          runCode={runEditorCode}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;flex flex-col mt-5&quot;&gt;<br>        &lt;CustomInputHeader clearInput={clearInput} /&gt;<br>        &lt;CustomInput input={input} setInput={handleCustomInputChange} /&gt;<br>      &lt;/div&gt;<br>      {output.data &amp;&amp; (<br>        &lt;&gt;<br>          &lt;div className=&quot;flex flex-col py-4&quot;&gt;<br>            &lt;OutputTerminalHeader<br>              status={output?.status}<br>              clearOutput={clearOutput}<br>            /&gt;<br>            &lt;OutputTerminal output={output?.data} outputRef={outputRef} /&gt;<br>          &lt;/div&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br>export default Main;</pre><p>Here I have used 2 refs</p><ol><li>outputRef -&gt; This one is to scroll to the output text area once the code is successfully run.</li><li>editorRef -&gt; This is to track the cursor pointer based on which we choose whether to refactor over the whole code or over a selected code snippet.</li></ol><p>Link to the website <a href="https://codeboost.vercel.app/">https://codeboost.vercel.app/</a>.</p><p>You can watch the demo of this application here on <a href="https://youtu.be/OsJIaldnClA">youtube</a>.</p><p>Also, you can refer to the source code here on <a href="https://github.com/abhirampai/CodeBoost">GitHub</a>.</p><p>If you found this project interesting please do share and star this project, also do follow me on Medium :D.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abe449cc1063" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/codeboost-where-you-can-run-and-refactor-your-code-abe449cc1063">CodeBoost where you can run and refactor your code</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run C or Python Programs Using Discord Bot]]></title>
            <link>https://medium.com/geekculture/run-c-or-python-programs-using-discord-bot-5aff7a58bcbf?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aff7a58bcbf</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[discord-bot]]></category>
            <category><![CDATA[discord-js]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 05:35:48 GMT</pubDate>
            <atom:updated>2022-01-03T07:05:11.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*pwvYVvNpX7JN_Xy_b81RmQ.png" /><figcaption>DiscordJs</figcaption></figure><p>During Lockdown I was using discord to interact with my friends while playing video games like among us. We used to play music using discord bot(groovy), while we took a break for like 5 mins. I was constantly thinking about creating a discord bot. I started off with an initial idea of creating a discord bot that would play music. Then one day my friend came up with a wild idea which was running programs written in c or python using a discord bot. I took this up as an challenge and ended up creating a bot that would run c and python program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*Qwif9dnpSLkxfBwksJhY1w.png" /><figcaption>Running Python Program using Discord Bot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*N1P8NZRvvINuu863kP9e2A.png" /><figcaption>Running C Program using Discord Bot</figcaption></figure><h3>Prerequisites</h3><p>&gt;NodeJs<br>&gt;CodeEditor (VScode,Atom,Sublime,etc..)<br>&gt;Discord Account and a Discord Server</p><h3>Lets Start Creating the bot</h3><p>First you have to register the bot in <a href="https://discord.com/login?redirect_to=%2Fdevelopers%2Fapplications">discord developer portal </a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQrgywPbrqQ2SnqRzDapng.png" /><figcaption>Developer Portal</figcaption></figure><p>After you login you will reach this screen then click on new application and you would be able to create a new application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6e7ac8q5ZgMRhmDtWneBaQ.png" /><figcaption>Creating the bot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4AHKyBEJdfXLKRAybTUJQ.png" /><figcaption>General Info of the new bot</figcaption></figure><p>On this page you can set the bot icon description about the bot etc.</p><p>Select bot option, and add a bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjaRfH4yuptV70cV2kBuoQ.png" /><figcaption>Adding bot</figcaption></figure><p>Now the bot is setup,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yojiJGU3NwCMEzjhtK1yBQ.png" /><figcaption>Bot details</figcaption></figure><h4>Now Lets Code the bot</h4><p>First lets create a directory for the bot, and also install the dependencies required for coding the bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApjKuSyoUXM7N-FiJvU6Aw.png" /><figcaption>Inital Steps</figcaption></figure><ul><li><strong>discord.js — </strong>The Discord library used to create our Discord bot.</li><li><strong>dotenv</strong> — This is going to allow us to hide certain variables, such as our bot’s client ID.</li><li><strong>request </strong>— This package is used to make http and https request.</li></ul><p>Lets start coding by opening preferred code editor, I am using <a href="https://code.visualstudio.com/Download">vscode</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr8FpjJ20FsZjndLdFoHbQ.png" /><figcaption>vscode folder structure</figcaption></figure><p>Now lets add .env and node_modules to .gitignore so that those files are not pushed to github repo in future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRz7vNNMX2am1Oq83R3SSA.png" /><figcaption>gitignore</figcaption></figure><p>Now we will get the token for our bot from the <a href="https://discord.com/developers/applications">developer portal</a>,</p><p>click on bot option and then click on copy,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w44qmGnqAfTca7Fw8EJdw.png" /><figcaption>bot token</figcaption></figure><p>Now paste the bot token in .env file</p><pre>CLIENT_TOKEN=&lt;your token&gt;</pre><p>Now in package json add a line inside script tag,</p><pre>“start”:&quot;node index.js&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*6QN3A6ActLs36zAMv5EQZw.png" /><figcaption>package.json</figcaption></figure><p>Now lets create a file index.js and add the required dependencies</p><pre>const Discord = require(“discord.js”);<br>const client = new Discord.Client();<br>var request = require(“request”);<br>require(“dotenv”).config();</pre><pre>client.login(process.env.CLIENT_TOKEN);</pre><p>Now for the compiler we would be using <a href="https://www.jdoodle.com/compiler-api/">jdoodle api</a>, <br>sign up and get the client Id and client Secret and paste it in .env file,</p><pre>CLIENT_ID=&lt;your client Id&gt;<br>CLIENT_SECRET=&lt;your client secret&gt;</pre><p>Now lets add the code to run c and python program</p><pre>const Discord = require(&quot;discord.js&quot;);<br>const client = new Discord.Client();<br>var request = require(&quot;request&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>const prefix = &quot;coder &quot;;<br><br>client.on(&quot;ready&quot;, () =&gt; {<br>    console.log(&quot;coder-BOT is online!&quot;);<br>  });<br>  <br>  client.on(&quot;message&quot;, async (message) =&gt; {<br>    try {<br>      let args = message.content.substring(prefix.length).split(&quot; &quot;);<br>      switch (args[0]) {case &quot;run&quot;:<br>      var input = &quot;&quot;;<br>      var language, index;<br>      if (args[1] == &quot;C&quot; || args[1] == &quot;c&quot;) {<br>        language = &quot;c&quot;;<br>        index = &quot;0&quot;;<br>      } else if (args[1] == &quot;python&quot;) {<br>        language = &quot;python3&quot;;<br>        index = &quot;3&quot;;<br>      }<br>      var fileName = message.attachments.array()[0];<br>      for (var i = 2; i &lt; args.length; i++) input += args[i] + &quot; &quot;;<br><br>      request.get(fileName.url, (err, response, body) =&gt; {<br>        const runRequestBody = {<br>          script: body,<br>          language: language,<br>          stdin: input,<br>          versionIndex: index,<br>          clientId: process.env.CLIENT_ID,<br>          clientSecret: process.env.CLIENT_SECRET,<br>        };<br>        request<br>          .post({<br>            url: &quot;https://api.jdoodle.com/execute&quot;,<br>            json: runRequestBody,<br>          })<br>          .on(&quot;error&quot;, (error) =&gt; {<br>            console.log(&quot;request.post error&quot;, error);<br>            return;<br>          })<br>          .on(&quot;data&quot;, (data) =&gt; {<br>            const parsedData = JSON.parse(data.toString());<br>            if (parsedData.error) {<br>              return;<br>            } else {<br>              var output = &quot;&quot;;<br>              for (var i = 0; i &lt; parsedData.output.length; i++) {<br>                if (parsedData.output[i] == &quot;\n&quot;) output += &quot;\n&quot;;<br>                else output += parsedData.output[i];<br>              }<br>              let outputOfProgram = new Discord.MessageEmbed()<br>                .setAuthor(client.user.username)<br>                .setDescription(&quot;Result!!!&quot;)<br>                .setColor(&quot;33FFB3&quot;)<br>                .setDescription(output);<br>              message.channel.send(outputOfProgram);<br>              return;<br>            }<br>          });<br>      });<br>      break;<br>    }<br>}<br>catch (Exception) {<br>    console.log(Exception);<br>    let Errorbotembed = new Discord.MessageEmbed()<br>      .setAuthor(client.user.username)<br>      .setDescription(&quot;Error!!!&quot;)<br>      .setColor(&quot;FFFFFF&quot;)<br>      .setDescription(&quot;Error Encountered\nFor Help use\nDM help&quot;);<br>    message.channel.send(Errorbotembed);<br>  }<br>});<br><br><br>client.login(process.env.CLIENT_TOKEN);</pre><p>So lets break the code,</p><p>client.on ready is when the discord bot goes online and it would just print coder-BOT is online in the command prompt.</p><p>client.on message works when someone sends a message in the channel on which the discord bot has access to.</p><p>In our case what we do here is we split the message to check whether the starting of the message contains the pattern <strong>“coder”. </strong>If a message starts with coder then we understand that the message is to the coderBot. Now here I used switch statement since we have only 1 command the coderbot address that is the run command.</p><p>Now when a message comes starting with “coder run” the first case would run and what we do in here is we check what is the argument that comes after the run command if it is c then c compiler is used and if it is python then we use the python interpreter. The index variable is set according to how the index is set in the jdoodle ide i.e, in our case we are using python 3.7.4 which is at index 3 in jdoodle python ide and gcc 5.3.0 c compiler at index 0.</p><p>Now after the language is specified we specify the inputs to the file and it is.</p><p>Now to capture the file that is uploaded along with the message we use,</p><pre>var fileName = message.attachments.array()[0];</pre><p>Now we send the request using jdoodle api and print the output accordingly.</p><h3>Adding bot to server</h3><p>Navigate to the OAuth2 option in the developer portal,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuYl1WqvnZNv1CLXY0-QCA.png" /><figcaption>Oauth2 of the application</figcaption></figure><p>In scopes select bot,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTKwAovQDxobzLzeqzWQlQ.png" /><figcaption>Bot Permssion</figcaption></figure><p>Then in bot permission select send message and manage roles.</p><p>Copy the link and then go to the link and add to the discord server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFWic2-PY98u7Un2I5eyfw.png" /><figcaption>Add Bot To Server</figcaption></figure><p>After this the bot will be added to the discord server.</p><p>Now lets try running the bot.</p><p>Use the command,</p><pre>npm start</pre><p>You will get coder-Bot online message in cmd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*KgawtU9wtfe7IZhBfnAnbQ.png" /><figcaption>cmd</figcaption></figure><p>Now lets see whether it can run c and python programs,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*QKS6WtvBPhY4mtvA19c2-A.png" /><figcaption>Running Python Program using Coder Bot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*aqV-CYBbomC6oc4iaGCprg.png" /><figcaption>Running C Program using Coder Bot</figcaption></figure><p>So we have successfully built a discord bot that can run c and python program using discord js.</p><p>You can find the full code here,</p><p><a href="https://github.com/Pai026/coderBot">https://github.com/abhirampai/coderBot</a></p><p><a href="https://gist.github.com/abhirampai/9979af5829a5854882858fcabfa6eb97">https://gist.github.com/abhirampai/9979af5829a5854882858fcabfa6eb97</a></p><p>Any queries , Mail me @ abhirampai1999@gmail.com,</p><p>or DM at,</p><p><a href="https://www.linkedin.com/in/abhiram-r-pai-bb3288170">https://www.linkedin.com/in/abhiram-r-pai-bb3288170</a></p><p><a href="https://twitter.com/pai_abhiram">Abhiram R Pai (@pai_abhiram) / Twitter</a></p><p><a href="https://www.instagram.com/abhiram_pai/">Abhiram Pai (@abhiram_pai) • Instagram photos and videos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aff7a58bcbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/run-c-or-python-programs-using-discord-bot-5aff7a58bcbf">Run C or Python Programs Using Discord Bot</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Experiments with NestJs]]></title>
            <link>https://abhirampai.medium.com/my-experiments-with-nestjs-3f2cde4619ba?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2cde4619ba</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 06:28:59 GMT</pubDate>
            <atom:updated>2021-02-08T06:32:17.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOigzaM9EhnVthDKtpkvRQ.png" /><figcaption>NestJS logo</figcaption></figure><p>During the lockdown, I was persistently trying to be as much productive as possible. That is the time when I came across an open-source disaster management platform <a href="https://coronasafe.network/">Coronasafe Network</a>. There was a project called Stay that was to be implemented for the organization. I and a few of my friends came together to build this platform. The technology stack was <a href="https://reactjs.org/">ReactJS</a>, NestJS, and Database was Postgres. First, we divided the team into frontend and backend developers, and I was part of the backend team. That is where I first came across the framework <a href="https://docs.nestjs.com/">NestJS</a>. It is a progressive <a href="https://nodejs.org/">nodejs</a> framework. Nest provides an out-of-the-box application architecture that allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications. The architecture is heavily inspired by <a href="https://angular.io/">Angular</a>.</p><h3><strong>Lets explore more on NestJS</strong></h3><p>Installation</p><pre>npm i -g @nestjs/cli</pre><p>This would install NestJS cli globally in our computer.</p><p>Now we can start a new project using the command,</p><pre>nest new project-name</pre><p>This command would create a new NestJS project with the desired project name we want.</p><blockquote>? Which package manager would you ❤️ to use?<br>npm<br>yarn</blockquote><p>I select npm you can select your desired package manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*aRO1JtEZ9Ll9fy693Kq3HQ.png" /><figcaption>Folder structure</figcaption></figure><p>After completion of the command we would get such a folder structure.</p><p>src would have the following files,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*qVT1T3vlnuOdIGTbrVimUw.png" /><figcaption>src folder</figcaption></figure><p>App module is the main module of any nestJS application.</p><p>Lets see each file in detail,</p><p>First lets go for the app.controller.spec.ts,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*sgcX2SEcWj74jGsxGxMRZQ.png" /><figcaption>app.controller.spec.ts,</figcaption></figure><p>This is a testing file for the app controller file. It tests whether the controller is working properly.</p><p>The next file is app.controller.ts,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ghbBlcT3LsfY6rJy3b6Yvg.png" /><figcaption>app.controller.ts</figcaption></figure><blockquote>Controllers are responsible for handling incoming requests and returning responses to the client.</blockquote><p>In this file we define the get, post, put, patch, delete request routes using different decorators defined in the @nestjs/common library.</p><p>The constructor of AppController class calls a private readonly object of the AppService class so that the functions defined in the AppService class is accessible within the AppController class. In this case getHello() of appService Class is available to AppController class through the private readonly object appService.</p><p>Now lets look at app.service.ts file,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*sBO8iIqv6ReT41rt3j_d5g.png" /><figcaption>app.service.ts</figcaption></figure><p>Service files are responsible for data storage and retrieval. Here in this file the getHello function called in app.controller.ts file is defined. Service files are decorated with @Injectable() decorator. This says nestJS that the class is nestJS provider.</p><blockquote>The main idea of a provider is that it can inject dependencies; this means objects can create various relationships with each other, and the function of “wiring up” instances of objects can largely be delegated to the Nest runtime system.</blockquote><p>Next lets see app.module.ts,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*Fl6g8H46ZsS57eiyfl0wxQ.png" /><figcaption>app.module.ts</figcaption></figure><blockquote>A module is a class annotated with a @Module() decorator. The @Module() decorator provides metadata that Nest makes use of to organize the application structure.</blockquote><p>In app.module.ts file we import various modules in our nestJS application. Also we can connect to the databases throught app.module.ts file.</p><p><strong>Connection with MongoDB</strong></p><p>To connect to a database we need to first install a package @nestjs/typeorm.</p><pre>npm i --save @nestjs/typeorm typeorm</pre><blockquote>Nest uses <a href="https://github.com/typeorm/typeorm">TypeORM</a> because it’s the most mature Object Relational Mapper (ORM) available for TypeScript. Since it’s written in TypeScript, it integrates well with the Nest framework.</blockquote><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;</pre><pre>require(&#39;dotenv&#39;).config();<br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot({<br>      type: &#39;mongodb&#39;,<br>      url:<br>      process.env.MONGOURL,<br>      entities: [__dirname + &#39;/**/*.entity{.ts,.js}&#39;],<br>      ssl: true,<br>      synchronize: true,<br>      logging: true,<br>      useUnifiedTopology: true,<br>      useNewUrlParser: true,<br>    }),<br>    ],<br>controllers: [AppController],<br>providers: [AppService],</pre><pre>})<br>export class AppModule {}</pre><p>Here the code above is an example for connecting nestJS application with a mongo database. TypeOrmModule is initialized with type mongodb the url of the mongo cluster is provided in as an environment variable then entities are the classes where the table structure is defined, for eg:-</p><pre>import {<br>  Column,<br>  CreateDateColumn,<br>  Entity,<br>  PrimaryGeneratedColumn,<br>  Unique,<br>} from &#39;typeorm&#39;;<br><br><br><br>@Entity(&#39;users&#39;)<br>@Unique([&#39;email&#39;])<br>export class User {<br><br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column({ length: 128 })<br>  name: string;<br><br>  @Column({ length: 128 })<br>  email: string;<br><br>  @Column({ length: 128 })<br>  password: string;<br><br>  @Column({ length:128 })<br>  type: string;<br><br>  @Column({ length: 128 })<br>  status: string;<br><br>  @Column({ nullable: true })<br>  referal: string;<br><br>  @Column({nullable: true})<br>  resetToken: string;<br><br>  @Column({ nullable: true })<br>  lastLogin: Date;<br><br>  @CreateDateColumn()<br>  createdAt: Date;<br><br>  @CreateDateColumn()<br>  updatedAt: Date;<br><br><br>}</pre><p>This is an entity file for the class user or in other words this file describes the model of the user table.</p><p><strong>Connection with Postgres</strong></p><p>For connecting with postgres, we first create a DbConfig file that exports a constant DbConfig of type TypeOrmModuleOptions,</p><pre>import { TypeOrmModuleOptions } from &#39;@nestjs/typeorm&#39;;<br>import * as config from &#39;config&#39;;<br><br>const dbConfig = config.get(&#39;db&#39;);<br><br><br>export const DbConfig: TypeOrmModuleOptions = {<br>  type: &#39;postgres&#39;,<br>  url: process.env.DATABASE_URL,//provide the database url<br>  host: dbConfig.host, //provide the host<br>  port: dbConfig.port , //provide the port number<br>  username: dbConfig.username, //provide the dbusername<br>  password: dbConfig.password , //provide the dbpassword<br>  database: dbConfig.database , //provide the databasename<br>  entities: [__dirname + &#39;/../**/*.entity.{js,ts}&#39;],<br>  migrations: [__dirname + &#39;/../**/migrations/*{.ts,.js}&#39;],<br>  synchronize: false,<br>  migrationsRun: true,<br>  cli: {<br>    migrationsDir: &#39;migrations&#39;,<br>  },<br>};</pre><p>Then the app.module.ts would be like ,</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import {DbConfig} from &#39;./config/db.config&#39;<br>import {TypeOrmModule} from &#39;@nestjs/typeorm&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;</pre><pre>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot(DbConfig),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>I have saved the db.config file inside config folder in src. Hence it is being imported from there. Now since we have completed the connection with postgres we have one more thing to look at since postgres is an sql database. We need to run migrations to add the tables in postgres database. For that first we need to create a migration folder and using cmd navigate into the migration folder and run the command</p><pre>npm i -g typeorm<br><br>typeorm migration:create -n filename</pre><p>This would create a migration file in the migration folder we created. An example file is,</p><pre>import { MigrationInterface, QueryRunner, Table } from &#39;typeorm&#39;;<br><br>export class CreateUser1234567891012 implements MigrationInterface {<br><br>  public async up(queryRunner: QueryRunner): Promise&lt;any&gt; {<br>    return await queryRunner.createTable(new Table({<br>      name: &#39;users&#39;,<br>      columns: [<br>        {<br>          name: &#39;id&#39;,<br>          type: &#39;bigint&#39;,<br>          isPrimary: true,<br>          isGenerated: true,<br>          generationStrategy: &#39;increment&#39;,<br>        },<br>        {<br>          name: &#39;name&#39;,<br>          type: &#39;varchar&#39;,<br>        },<br>        {<br>          name: &#39;email&#39;,<br>          isUnique: true,<br>          type: &#39;varchar&#39;,<br>        },<br>        {<br>          name: &#39;referal&#39;,<br>          type:&#39;varchar&#39;,<br>          isUnique: true,<br>          isNullable: true,<br>        },<br>        {<br>          name: &#39;resetToken&#39;,<br>          type:&#39;varchar&#39;,<br>          isUnique: true,<br>          isNullable: true,<br>        },<br>        {<br>          name: &#39;type&#39;,<br>          type:&#39;varchar&#39;<br>        },<br>        {<br>          name: &#39;password&#39;,<br>          type: &#39;varchar&#39;,<br>          isNullable: false,<br>        },<br>        {<br>          name: &#39;status&#39;,<br>          type: &#39;varchar&#39;,<br>          default: &#39;\&#39;ACTIVE\&#39;&#39;,<br>        },<br>        {<br>          name: &#39;lastLogin&#39;,<br>          type: &#39;timestamp&#39;,<br>          isNullable: true,<br>          default: &#39;CURRENT_TIMESTAMP&#39;,<br>        },<br>        {<br><br>          name: &#39;createdAt&#39;,<br>          type: &#39;timestamp&#39;,<br>          default: &#39;CURRENT_TIMESTAMP&#39;,<br>          isNullable: false,<br>        },<br>        {<br><br>          name: &#39;updatedAt&#39;,<br>          type: &#39;timestamp&#39;,<br>          default: &#39;CURRENT_TIMESTAMP&#39;,<br>          isNullable: false,<br>        },<br>      ],<br>    }), true);<br>  }<br><br>  public async down(queryRunner: QueryRunner): Promise&lt;any&gt; {<br>    await queryRunner.query(`DROP TABLE &quot;users&quot;`);<br>  }<br><br>}</pre><p>Now when we start the nest application using,</p><blockquote>npm run</blockquote><p>migrations will run automatically and the tables will be created in the postgres db. Up function creates the table whereas down function drops the table from the postgres db.</p><h3>Conclusion</h3><p><a href="https://docs.nestjs.com/">NestJS</a> has a content rich documentation avaliable, you can refer to that if required. For more reference of nestjs application I am attaching some of my github repos that uses nestjs,</p><p><a href="https://github.com/Pai026/tasks-manager-be">Pai026/tasks-manager-be: Backend of the todo(task) management website using nest (github.com)</a></p><p><a href="https://github.com/Pai026/stay_be">Pai026/stay_be: CoronaSafe Stay BE NestJS (github.com)</a></p><p><a href="https://github.com/Delivery-System-App/delivery-app-be">Delivery-System-App/delivery-app-be (github.com)</a></p><p>Any queries , Mail me @ abhirampai1999@gmail.com,</p><p>or DM at,</p><p><a href="https://www.linkedin.com/in/abhiram-r-pai-bb3288170">https://www.linkedin.com/in/abhiram-r-pai-bb3288170</a></p><p><a href="https://twitter.com/pai_abhiram">Abhiram R Pai (@pai_abhiram) / Twitter</a></p><p><a href="https://www.instagram.com/abhiram_pai/">Abhiram Pai (@abhiram_pai) • Instagram photos and videos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2cde4619ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Successfully Build Windows Terminal]]></title>
            <link>https://abhirampai.medium.com/how-to-successfully-build-windows-terminal-76307c53fc87?source=rss-a8ddc8e58b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/76307c53fc87</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[visual-studio]]></category>
            <category><![CDATA[terminal-windows]]></category>
            <category><![CDATA[windows-10-support]]></category>
            <dc:creator><![CDATA[Abhiram R Pai]]></dc:creator>
            <pubDate>Sun, 26 May 2019 15:54:19 GMT</pubDate>
            <atom:updated>2019-05-26T15:54:19.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0a1WbyWhfHk2b__n1-erA.png" /><figcaption>All new Windows Terminal</figcaption></figure><p><strong>Windows Terminal</strong> is a new, modern, feature-rich, productive <strong>terminal</strong> application for <strong>command-line </strong>users. It includes many of the features most frequently requested by the <strong>Windows command-line</strong> community including support for tabs, rich text, globalization, configurability, theming &amp; styling, and more.</p><h4>Requirements</h4><ol><li>Windows build 1903</li><li>Visual Studio 2017</li><li>Git</li><li>Ubuntu Terminal</li></ol><h3><strong>Installing Windows Build 1903</strong></h3><p>At first you would have to register to the windows insider program</p><ol><li>Go to settings.</li><li>Click Update and Security .</li><li>Click Windows Insider Program.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv3Bl-sg6LeTGSnYuX1__w.jpeg" /><figcaption>Windows Insider Programme</figcaption></figure><p>4. Register for the program.</p><p>5. Update your windows.</p><h3><strong>If You Get errors while updating windows</strong></h3><p>You might encounter errors like windows cannot be updated because your device or service is not updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*ub7GOrHo9E6R1F0JGC_1Lg.jpeg" /><figcaption>Error!!!</figcaption></figure><p>To fix this error you can download the windows 1903 ISO.</p><p>1.Download the ISO from <a href="https://drive.google.com/open?id=1M0NeGLfFrrE1Fo3dYVStIu6czzGdPoeT">https://drive.google.com/open?id=1M0NeGLfFrrE1Fo3dYVStIu6czzGdPoeT</a></p><p>2. Turn off the internet.</p><p>3. Click the ISO file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0NhcSwM8O7iHrLa7AKuHA.jpeg" /><figcaption>Inside the ISO File</figcaption></figure><p>4. Open Setup File.</p><p>5. Follow the steps and update windows.</p><h3><strong>Visual Studio 2017</strong></h3><p>All might ask this question,</p><p>Why Visual Studio 2017 when there is Visual Studio 2019??</p><p>The answer is simple because no one love errors.</p><p>If you try to build Windows Terminal using Visual Studio 2019 you would probably find 12 errors.</p><p>Instead without wasting further time go download Visual Studio 2017 from <a href="https://developerinsider.co/download-visual-studio-2017-web-installer-iso-community-professional-enterprise/">https://developerinsider.co/download-visual-studio-2017-web-installer-iso-community-professional-enterprise/</a></p><ol><li>After Installing open the setup.</li><li>Then you would have to tick the check boxes,</li></ol><p>1.Desktop development with c++</p><p>2. Universal Windows Platform Development</p><p>3. Windows 10 SDK (10.0.17134.0) or the latest one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sU9K0QfRZzVfHQovklPqfw.jpeg" /></figure><p>3. Install Visual Studio 2017</p><h3>Git</h3><p>You would require git commands in cmd to build the windows terminal.</p><p>For that you would have to first download git from <a href="https://git-scm.com/">https://git-scm.com/</a></p><h3><strong>Building Windows Terminal</strong></h3><ol><li>Open Command Prompt.</li><li>Now follow the commands one by one</li></ol><pre>git clone  <a href="https://github.com/microsoft/terminal">https://github.com/microsoft/terminal</a> mywindowsterminal</pre><pre>cd mywindowsterminal</pre><pre>git submodule update --init --recursive</pre><pre>dep\nuget\nuget.exe restore OpenConsole.sln </pre><p>If you have both Visual Studio 2019 as well as Visual Studio 2017 you might have to use the command</p><pre>dep\nuget\nuget.exe restore OpenConsole.sln --MSBuildVersion 15.9</pre><p>3. Now Enter start .</p><p>4. This will open the File Explorer and Open OpenConsole.sln</p><p>5. After the Visual Studio is opened you would have to just change the Processor x64 or x86 and change Debug to release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Pz1vL4-vPh1foiYMFpQMQ.jpeg" /><figcaption>Select Processor</figcaption></figure><p>To Know the type of processor</p><ol><li>Go to This PC.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WB5C91t2uvddhis5RUOokg.jpeg" /><figcaption>This PC</figcaption></figure><p>2. Right click select Properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Im5vcwFLjcEGEvcAGUAHkQ.jpeg" /><figcaption>Properties</figcaption></figure><p>3. Now go to Settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ea9Tsu15MXuPspcQRE-Fg.jpeg" /></figure><p>4. Select Update &amp; Security</p><p>5. Select For Developers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkRMJT_Qnaw4XDTOgE1iOQ.jpeg" /><figcaption>For developers</figcaption></figure><p>6. Select Developer mode.</p><p>7. Now Go back to Visual Studio and From Build Tab Select Deploy Solution.</p><p>8. Windows Terminal would be successfully Deployed.</p><h3>Adding Extra terminals in Windows Terminal</h3><p>When the windows terminal is deployed you would get something like this..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OH-x0I7IEgVmC9BZHpTSXA.jpeg" /><figcaption>Windows Terminal</figcaption></figure><p>Here I have Ubuntu and the new Power-Shell but you would actually see only old Power-Shell and CMD.</p><p>For getting Ubuntu follow the steps,</p><ol><li>Go to search and search run</li><li>Go to %localappdata%\Packages</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*RJUN_a_BnUOjMzOfuqCNsQ.jpeg" /><figcaption>Run</figcaption></figure><p>3. Then go to WindowsTerminalDev_8wekyb3d8bbwe.(folder name might be different but WindowsTerminalDev would be there)</p><p>4. Open folder RoamingState.</p><p>5. Replace the files in the folder with the files from <a href="https://github.com/Pai026/windows">https://github.com/Pai026/windows</a></p><p>6. Just Select Clone or Download in GitHub and download the zip file extract and paste in RoamingState Folder.</p><h3><strong>UBUNTU</strong></h3><ol><li>Now go to Microsoft Store and install Ubuntu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-dU8mJ2m5WiOWjZns4XOA.jpeg" /><figcaption>Microsoft Store</figcaption></figure><p>2. After installation go to control panel.</p><p>3. Select Programs And Features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaSDsMcQEB9oybkU-8WU0g.jpeg" /><figcaption>Programs and Features</figcaption></figure><p>4. Select Turn Windows Features on or off</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*QC6n9PiP1pzTYg2Hi9mcgQ.jpeg" /><figcaption>Windows Features</figcaption></figure><p>5. Tick Windows Subsytem for Linux.</p><p>6. Then Open Ubuntu from Start which would Successfully install Ubuntu terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVxrQqUJ0HMGn8EWrqGvuw.jpeg" /><figcaption>Ubuntu</figcaption></figure><h3>Additional :-</h3><p>You can add any number of terminals to the Windows Terminal by just adding the corresponding terminal to profile.json code.</p><p>For example in my Windows Terminal I have the new one and also old version of Power-Shell. I just installed the Newest version of Power-Shell (PowerShell 6) and just cloned the same PowerShell code and changed</p><p>“commandline”: “powershell.exe” to</p><p>“commandline”: “pwsh.exe”</p><p>Which is the executable file of PowerShell 6.</p><p>I failed 5 times to successfully build this Windows Terminal and I hope this blog would help everyone reduce that number to 0.</p><p>If you encounter any errors feel free to mail me at, abhirampai1999@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76307c53fc87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>