<?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 Sujan Chhetri on Medium]]></title>
        <description><![CDATA[Stories by Sujan Chhetri on Medium]]></description>
        <link>https://medium.com/@sujanxchhetri?source=rss-8ef79296f97c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xDyGiustjtk9pPq5XSC9kQ.jpeg</url>
            <title>Stories by Sujan Chhetri on Medium</title>
            <link>https://medium.com/@sujanxchhetri?source=rss-8ef79296f97c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:02:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sujanxchhetri/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[Nepali NAATI CCL Test Info & Practice Materials]]></title>
            <link>https://medium.com/@sujanxchhetri/nepali-naati-ccl-test-info-practice-materials-ce26233e1a32?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce26233e1a32</guid>
            <category><![CDATA[naati]]></category>
            <category><![CDATA[naati-nepali]]></category>
            <category><![CDATA[naati-ccl-test]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 03:50:08 GMT</pubDate>
            <atom:updated>2024-08-20T03:54:33.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5tV-qkRCaw1bRTyzuuM2Ig.png" /></figure><p>The NAATI (National Accreditation Authority for Translators and Interpreters) Credentialed Community Language (CCL) test assesses a candidate’s ability to interpret conversations between English and a Language Other Than English (LOTE). Successfully passing the NAATI CCL test can earn candidates five points towards their Australian immigration points test. Read Full post at our Blog post <a href="https://blogue.tech/feeds/nepali-naati-ccl-test-info-and-practice-materials">Nepali NAATI CCL Test Info &amp; Practice Materials</a></p><p>Here is a tailored material for <a href="https://sujanchhetri.gumroad.com/l/edstqd">Mastering the NAATI CCL Test: A Comprehensive Guide for Nepali Candidates</a></p><h3>Test Format</h3><p>The NAATI CCL test consists of two dialogues, each representing real-life scenarios involving conversations between an English speaker and a LOTE speaker. Each dialogue is approximately 300 words long, divided into segments of up to 35 words. Candidates are required to interpret each segment accurately and fluently.</p><h3>Scoring</h3><p>Each dialogue is worth 45 marks, making a total of 90 marks for the entire test. To pass, candidates must score at least 29 out of 45 in each dialogue and have a total score of at least 63 out of 90. The test uses a mark deduction system, where errors in accuracy, language quality, and delivery result in deductions from the starting score of 90​ (<a href="https://ccltutorials.online/test-format">CCL Tutorials</a>)​​ (<a href="https://www.naati.com.au/migration-assessments/ccl/">NAATI</a>)​.</p><h3>Taking the Test</h3><p>Candidates can apply for the NAATI CCL test through the myNAATI portal. The test can be taken online or at designated test centres. The process involves:</p><ol><li><strong>Creating a myNAATI Account</strong>: Candidates must create an account and submit their application online.</li><li><strong>Selecting a Test Date</strong>: After the application is approved, candidates can select a test date and pay the test fee.</li><li><strong>Taking the Test</strong>: On the test day, candidates will interpret the dialogues and their responses will be recorded and assessed by NAATI examiners.</li></ol><h3>Tips and Tricks for Nepali Candidates</h3><ol><li><strong>Language Immersion</strong>: Surround yourself with both Nepali and English languages. Read newspapers, watch news, and listen to podcasts in both languages to enhance your comprehension and fluency.</li><li><strong>Practice Interpreting</strong>: Regularly practice interpreting conversations from English to Nepali and vice versa. Use real-life scenarios and common dialogue topics such as health, legal, and community services.</li><li><strong>Expand Vocabulary</strong>: Build a glossary of common terms and phrases used in various contexts. Focus on medical, legal, and administrative terminologies, which are often part of the test.</li><li><strong>Mock Tests</strong>: Take as many mock tests as possible to simulate the actual test environment. This helps in time management and identifying areas that need improvement.</li><li><strong>Note-taking</strong>: Develop efficient note-taking skills to help remember key points during the dialogues. Use symbols and abbreviations to save time.</li><li><strong>Stay Calm and Focused</strong>: Practice relaxation techniques like deep breathing and meditation to stay calm during the test. Avoid rushing through the segments and focus on accuracy.</li><li><strong>Review and Correct</strong>: If you make a mistake, calmly correct yourself and proceed. Avoid excessive repetitions as they can lead to mark deductions.</li></ol><p>The NAATI CCL (Credentialed Community Language) test covers a range of topics relevant to real-life scenarios in Australian society. These topics include:</p><ol><li><strong>Business</strong></li><li><strong>Community</strong></li><li><strong>Consumer Affairs</strong></li><li><strong>Education</strong></li><li><strong>Employment</strong></li><li><strong>Financial</strong></li><li><strong>Health</strong></li><li><strong>Housing</strong></li><li><strong>Immigration/Settlement</strong></li><li><strong>Insurance</strong></li><li><strong>Legal</strong></li><li><strong>Social Services</strong>​</li></ol><p>Get the limited material <a href="https://sujanchhetri.gumroad.com/l/edstqd">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP2z7BDfebfo2vEJh4VRfQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQO4OO3sry9KuLBdBpD3XQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qXg6u5n2pgjNoIMuWQjMA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VFo09QMc5cSmf3BcycNJA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0I6bgBFek5OoM5pvlH8Hg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAkNZFhOWFCOR4hrrPmwlA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyO0VW2tluOuB5yt0TbEvA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwAgtIFDXFIZOZo_G_30Vg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yWxuOtyxYCkfbjQkF-i2g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*It-25Kc3Z9lTDeymDomnHw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lla_BDRrqHIMFzv3mF6d8A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RFnT97COmYd7sR5QSRpPBg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9laC5kcfhOR75JNhfA_yig.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHmDn-KtbgT81nXqe6JUug.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqjZy8e7uObXoxNxPcxguw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gISMuVC2OZppSie2XYfs_g.jpeg" /><figcaption>free samples</figcaption></figure><p>Hope you like the sample for part A .</p><p>Happy Learning …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce26233e1a32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to extract and login with Cookies from a site with Puppeteer ?]]></title>
            <link>https://medium.com/@sujanxchhetri/how-to-extract-and-login-with-cookies-from-a-site-with-puppeteer-23fbfc3b4ebf?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23fbfc3b4ebf</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 04:28:16 GMT</pubDate>
            <atom:updated>2023-04-11T04:28:16.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to extract and login with Cookies from a site with Puppeteer ?</h3><p>Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium. Learn more about puppeteer <a href="https://github.com/puppeteer/puppeteer/blob/main/CONTRIBUTING.md">here</a>.In this article, we will write a script that will automatically logs you in from the google oauth form and scrape the cookie data from the site. Checkout <a href="https://blogue.tech/">Blogue.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kl71N_dRrsSRxQFQ" /></figure><p>Below are the use cases of it:</p><ol><li><strong>Test automation in modern web applications</strong>: verifying that the features we are exposing our users/customers to are actually behaving as expected.</li><li><strong>Taking screenshots of web pages</strong>: useful for a variety of different uses going from simple archiving to automated comparison for e.g. visual testing.</li><li><strong>Scraping web sites for data</strong>: extracting data from websites for later retrieval or analysis.</li><li><strong>Automating interaction of web pages</strong>: speed up and scale any sort of sequence of actions we would like to perform on a website automatically.</li></ol><p>Let’s scrape a site,shall we?</p><p>Create a Project Folder and structure it as below:</p><pre>root------------ script.js----- cookies.json----- config.json</pre><p>In cookie,json file.Add a { } as below:</p><pre>{ }</pre><p>In config.json. Add mail and password as below:</p><pre>{</pre><pre>&quot;mail&quot;:&quot;your email&quot;,</pre><pre>&quot;password&quot;:&quot;your password&quot;</pre><pre>}</pre><p>Now lets install puppeteer:</p><pre>npm i puppeteer</pre><p>Start writing the script in script.js file.copy the below code:</p><pre>const puppeteer = require(&quot;puppeteer&quot;);</pre><pre>const fs = require(&quot;fs&quot;);</pre><pre>const cookies = require(&quot;./cookies.json&quot;);</pre><pre>const config = require(&quot;./config.json&quot;);</pre><pre>(async () =&gt; {</pre><pre>  try {</pre><pre>    //* start puppeteer and creates a new pagelet browser = await puppeteer.launch({ headless: false });</pre><pre>    let page = await browser.newPage();</pre><pre>    //* check for any saved sessionif (Object.keys(cookies).length) {</pre><pre>      //* set the saved cookies in the pageawait page.setCookie(...cookies);</pre><pre>      //* go to sentinalawait page.goto(&quot;https://sentinel.zerodha.com/&quot;, {</pre><pre>        waitUntil: &quot;networkidle2&quot;,</pre><pre>      });</pre><pre>    } else {</pre><pre>      await page.goto(&quot;https://sentinel.zerodha.com/login&quot;, {</pre><pre>        waitUntil: &quot;networkidle0&quot;,</pre><pre>      });</pre><pre>      //* brings login pageawait page.click(&#39;a[href=&quot;/api/accounts/google/login/&quot;]&#39;, { delay: 30 });</pre><pre>      //* adds emailawait page.waitForSelector(&#39;input[id=&quot;identifierId&quot;]&#39;);</pre><pre>      await page.type(&#39;input[id=&quot;identifierId&quot;]&#39;, config.mail, {</pre><pre>        delay: 30,</pre><pre>      });</pre><pre>      await page.click(&quot;#identifierNext&quot;);</pre><pre>      //* adds passwordawait page.waitForSelector(&#39;input[type=&quot;password&quot;]&#39;, { visible: true });</pre><pre>      await page.type(&#39;input[type=&quot;password&quot;]&#39;, config.password);</pre><pre>      await page.waitForSelector(&quot;#passwordNext&quot;, { visible: true });</pre><pre>      await page.click(&quot;#passwordNext&quot;);</pre><pre>      //* get the current browser page sessionlet currentCookies = await page._client.send(&quot;Network.getAllCookies&quot;);</pre><pre>      //* creates a cookie file to store the session</pre><pre>      fs.writeFileSync(&quot;./cookies.json&quot;, JSON.stringify(currentCookies));</pre><pre>      await browser.close();</pre><pre>    }</pre><pre>  } catch (e) {</pre><pre>    console.log(e);</pre><pre>  }</pre><pre>})();</pre><p>To run the script:</p><pre>node script.js</pre><p>Check the cookie.json file. The file gets the cookie from the site.</p><p>More Scraping <a href="https://blogue.tech/">Here</a>.</p><p>Happy coding…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23fbfc3b4ebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mindfulness and Meditation: The Power of Mind-Body Connection]]></title>
            <link>https://medium.com/@sujanxchhetri/mindfulness-and-meditation-the-power-of-mind-body-connection-e546366e26d5?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e546366e26d5</guid>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[mindfulness-meditation]]></category>
            <category><![CDATA[mindfulness-practice]]></category>
            <category><![CDATA[yoga-and-meditation]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 04:23:26 GMT</pubDate>
            <atom:updated>2023-03-14T04:23:26.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ozRs5jh5IBeTzu9T.jpg" /></figure><p>In our busy and often stressful lives, it’s easy to lose connection with our bodies and minds. Mindfulness and meditation are practices that help us reconnect and strengthen the mind-body connection. In this blog post, we’ll explore the power of mindfulness and meditation and how they can improve our health and well-being.</p><blockquote><em>Checkout this amazing </em><a href="https://blogue.tech/"><em>platform</em></a><em>:</em></blockquote><h3>What is Mindfulness?</h3><p>Mindfulness is the practice of paying attention to the present moment, without judgment. It involves observing our thoughts, feelings, and sensations without reacting to them or getting caught up in them. By practicing mindfulness, we can become more aware of our thoughts and emotions, and develop a greater sense of calm and clarity.</p><h3>What is Meditation?</h3><p>Meditation is a practice that involves focusing the mind on a specific object or activity, such as the breath or a mantra. It helps calm the mind and reduce stress and anxiety, promoting a greater sense of inner peace and well-being.</p><h3>The Power of Mind-Body Connection</h3><p>The mind-body connection refers to the relationship between our thoughts, emotions, and physical sensations. When we’re stressed or anxious, for example, our body responds by releasing stress hormones that can cause physical symptoms such as a racing heart, tense muscles, and shallow breathing. By practicing mindfulness and meditation, we can learn to recognize and regulate our body’s response to stress, improving our overall health and well-being.</p><h3>Benefits of Mindfulness and Meditation</h3><h4>Reduced Stress and Anxiety</h4><p>Mindfulness and meditation can help reduce stress and anxiety by calming the mind and regulating the body’s response to stress.</p><h4>Improved Mood</h4><p>By promoting a greater sense of calm and inner peace, mindfulness and meditation can improve our overall mood and well-being.</p><h4>Enhanced Self-Awareness</h4><p>Mindfulness and meditation can help us become more aware of our thoughts and emotions, enabling us to respond more effectively to difficult situations.</p><h4>Better Sleep</h4><p>By promoting relaxation and reducing stress, mindfulness and meditation can improve our sleep quality and quantity.</p><h4>Improved Cognitive Function</h4><p>Mindfulness and meditation have been shown to improve cognitive function, including memory, attention, and decision-making.</p><h4>Reduced Pain and Inflammation</h4><p>By regulating the body’s response to stress, mindfulness, and meditation can help reduce pain and inflammation in the body.</p><p>In conclusion, mindfulness and meditation are powerful practices that can improve our mind-body connection and promote overall health and well-being. By incorporating these practices into our daily routine, we can reduce stress and anxiety, improve our mood, enhance self-awareness, improve our sleep, boost cognitive function, and reduce pain and inflammation. Start small, set aside a few minutes each day to practice mindfulness and meditation, and over time, you’ll notice the positive impact it has on your health and well-being.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e546366e26d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Compound Interest: Investing for the Long Term]]></title>
            <link>https://medium.com/@sujanxchhetri/the-power-of-compound-interest-investing-for-the-long-term-c5603bb4d7e0?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5603bb4d7e0</guid>
            <category><![CDATA[compound-interest]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[personal-finance]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 10:19:27 GMT</pubDate>
            <atom:updated>2023-03-12T10:19:27.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NSG-IT1J6CQXrac_.png" /></figure><p>Albert Einstein famously said, “Compound interest is the eighth wonder of the world. He who understands it earns it; he who doesn’t pays it.” This quote highlights the power of compound interest, which can turn a small amount of money into a large sum over time. In this post, we will explore the concept of compound interest and how it can help you build wealth through long-term investing.</p><blockquote>Checkout this amazing <a href="https://blogue.tech/">platform</a>:</blockquote><h3>What is Compound Interest?</h3><p>Compound interest is the interest that is earned not only on the initial investment but also on the interest earned over time. This means that the interest you earn in one period is added to the principal, and then the interest for the next period is calculated based on the new total. Over time, the interest earned can grow exponentially, resulting in significant gains.</p><p>For example, let’s say you invest $1,000 at a 5% annual interest rate. After the first year, you will earn $50 in interest, bringing your total investment to $1,050. In the second year, you will earn interest not only on your initial $1,000 investment but also on the $50 in interest from the first year. Assuming you continue to earn 5% annually, your investment will be worth $1,276 after five years, $1,628 after ten years, and $2,653 after twenty years.</p><h3>The Benefits of Long-Term Investing</h3><p>The power of compound interest is most significant over the long term. By investing early and consistently, you can take advantage of this concept and watch your investments grow over time. Long-term investing can also help you weather short-term market fluctuations, as you are investing for the long-term potential of your investments, rather than trying to time the market or make short-term gains.</p><p>Investing for the long term can also help you achieve your financial goals, such as retirement. By starting early and contributing regularly to your investments, you can build a substantial nest egg over time, even if you start with small amounts.</p><h3>Tips for Investing for the Long-Term</h3><p>Investing for the long term requires patience, discipline, and a plan. Here are some tips to help you get started:</p><ol><li>Start early: The earlier you start investing, the more time your money has to compound and grow.</li><li>Be consistent: Regular contributions to your investments can help you take advantage of dollar-cost averaging and reduce the impact of market volatility.</li><li>Diversify your portfolio: Diversification can help you spread your risk and increase your chances of long-term success.</li><li>Avoid emotional decisions: Trying to time the market or make short-term gains can lead to emotional decisions and may harm your long-term returns.</li><li>Stay invested: Avoid the temptation to pull out of the market during downturns. Staying invested can help you take advantage of potential rebounds and continue to benefit from compound interest.</li></ol><p>In conclusion, the power of compound interest can help you build wealth over time through long-term investing. By starting early, being consistent, diversifying your portfolio, avoiding emotional decisions, and staying invested, you can take advantage of this concept and achieve your long-term financial goals. Remember, investing is a journey, not a destination, so stay the course and enjoy the ride.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5603bb4d7e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping NEPSE Nepal Stock Exchange Todays Price data]]></title>
            <link>https://medium.com/@sujanxchhetri/scraping-nepse-nepal-stock-exchange-todays-price-data-4a20fcd6782e?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a20fcd6782e</guid>
            <category><![CDATA[nepse]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[nepal-stock-exchange]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 08:06:05 GMT</pubDate>
            <atom:updated>2023-03-12T10:07:42.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJVCx26-BkaAV9GW-S5hFA.png" /></figure><p>Scraping site data is a quite lot of work. It is hectic I know. But I have figured out a solution for that which is posted <a href="https://blogue.tech/">here</a> as well. In this article, we will be Scraping NEPSE Nepal Stock Exchange Today’s Price data with our favorite scraping framework puppeteer. To know more about puppeteers you can check <a href="https://scraperspace.blogue.tech/">scraperspace</a>. So let’s get started scraping google maps.</p><h3>Installation</h3><p>You need to install puppeteer and nodejs in your system. You can install a puppeteer library with the below command.</p><pre>npm install -g puppeteer</pre><p>After installation is done.</p><ul><li>go to <a href="https://www.nepalstock.com.np/today-price">this</a> page</li><li>You’ll see the NEPSE today’s data</li><li>we’ll need the URL later</li></ul><p>Let’s write the function to scrape:</p><pre>const puppeteer = require(&quot;puppeteer&quot;);</pre><pre>const fs = require(&quot;fs&quot;);</pre><pre>async function scraper(option: any) {</pre><pre>  try {</pre><pre>    //browser initiatedlet browser = await puppeteer.launch({</pre><pre>      args: [&quot;--start-maximized&quot;],</pre><pre>      headless: false,</pre><pre>    });</pre><pre>    // opens a new blank pagelet page = await browser.newPage();</pre><pre>    // resize the browserawait page.setViewport({ width: 1366, height: 768 });</pre><pre>await page.goto(`http://www.nepalstock.com.np/main/todays_price/index/${option.code} `, {</pre><pre>      waitUntil: &quot;networkidle0&quot;,</pre><pre>    });</pre><pre>    // waits until page loads completelyawait page.waitForSelector(&quot;.container&quot;, { visible: true });</pre><pre>    const content = await page.evaluate(() =&gt; {</pre><pre> let rowList: any[] = [];</pre><pre> let rows = document.querySelectorAll(&quot;table tbody tr&quot;);</pre><pre>      rows.forEach((row) =&gt; {</pre><pre>        `  `;</pre><pre>        // Declares the data we want to scrapelet record: {</pre><pre>          Sn: string;</pre><pre>          Traded_Companies: string;</pre><pre>          No_Of_Transaction: string;</pre><pre>          Max_Price: string;</pre><pre>          Min_Price: string;</pre><pre>          Closing_Price: string;</pre><pre>          Traded_Shares: string;</pre><pre>          Amount: string;</pre><pre>          Previous_Closing: string;</pre><pre>          Difference_Rs: string;</pre><pre>        } = {</pre><pre>          Sn: &quot;&quot;,</pre><pre>          Traded_Companies: &quot;&quot;,</pre><pre>          No_Of_Transaction: &quot;&quot;,</pre><pre>          Max_Price: &quot;&quot;,</pre><pre>          Min_Price: &quot;&quot;,</pre><pre>          Closing_Price: &quot;&quot;,</pre><pre>          Traded_Shares: &quot;&quot;,</pre><pre>          Amount:&quot;&quot;,</pre><pre>          Previous_Closing:&quot;&quot;,</pre><pre>          Difference_Rs: &quot;&quot;</pre><pre>        };</pre><pre>// getting textvalue of each column of a row and adding them to a listconst tdList = Array.from(</pre><pre>          row.querySelectorAll(&quot;td&quot;),</pre><pre>          (column) =&gt; column.innerText,</pre><pre>        );</pre><pre>        if (tdList.length &gt;= 9) {</pre><pre>          // push the data</pre><pre>          rowList.push({</pre><pre>            Sn: tdList[0],</pre><pre>            Traded_Companies: tdList[1],</pre><pre>            No_Of_Transaction: tdList[2],</pre><pre>            Max_Price: tdList[3],</pre><pre>            Min_Price: tdList[4],</pre><pre>            Closing_Price: tdList[5],</pre><pre>            Traded_Shares: tdList[6],</pre><pre>            Amount: tdList[],</pre><pre>            Previous_Closing: tdList[8],</pre><pre>            Difference_Rs:tdList[9]</pre><pre>          });</pre><pre>        }</pre><pre>      });</pre><pre>      return rowList;</pre><pre>    });</pre><pre>    // Store output by creating json file for each index</pre><pre>    fs.writeFile(</pre><pre>      `./ShareData/ShareData-${option.index}.json`,</pre><pre>      JSON.stringify(content, null, 2),</pre><pre>      (err: any) =&gt; {</pre><pre>        if (err) {</pre><pre>          console.log(err);</pre><pre>        } else {</pre><pre>          console.log(`Data  of Stock Page-${option.index} Scraped`);</pre><pre>        }</pre><pre>      },</pre><pre>    );</pre><pre>    // close the browserawait browser.close();</pre><pre>  } catch (e) {</pre><pre>    console.log(e);</pre><pre>  }</pre><pre>}</pre><pre>let main = async () =&gt; {</pre><pre>  // Loop through the stock pagefor (let i = 1; i &lt;= 11; ++i) {</pre><pre>    await Promise.all([</pre><pre>      scraper({</pre><pre>        code: i,</pre><pre>        index: i,</pre><pre>      }),</pre><pre>    ]);</pre><pre>  }</pre><pre>};</pre><pre>main()</pre><pre>  .then(() =&gt; {</pre><pre>    console.log(&quot;Scraping Completed!&quot;);</pre><pre>  })</pre><pre>  .catch(class=&quot;hljs-function&quot;&gt;() =&gt; {</pre><pre>    console.log(`Failed due to exception - ${e}`);</pre><pre>  });</pre><h3>Steps to run</h3><ul><li>‘’ npm install ‘’ in the terminal in the root folder to install all the required packages</li><li>‘’ npm start ‘’ to run the script</li><li>To view the scraped data, run the ‘’ index.html ‘’ file from the views folder</li></ul><p>You can get the source code from <a href="https://github.com/sujanchhetri/NEPSE_scraper">here</a>.</p><p>Checkout my <a href="https://blogue.tech/@/sujanchhetri">blog</a>.</p><p>Happy Coding …</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a20fcd6782e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A walkthrough to Blockchain]]></title>
            <link>https://medium.com/@sujanxchhetri/a-walkthrough-to-blockchain-72449e0131e?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/72449e0131e</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 13:25:46 GMT</pubDate>
            <atom:updated>2023-03-12T10:11:27.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvMIi7XIPoPOqoG-5AZf7Q.jpeg" /></figure><p>Blockchain is a distributed &amp; decentralized ledger that stores data and is publicly shared across all the node of its network. Blockchain is almost always used instead of the terms Bitcoin and cryptocurrency. And there are many other places this technology can be used. We are beginning to barely scratch the surface of it.With all the popularity around, we know that the Blockchain Technology is going to be huge. But what makes it unique?</p><blockquote><strong>Checkout this amazing </strong><a href="https://blogue.tech/"><strong>platform</strong></a><strong>:</strong></blockquote><ul><li>Decentralized System</li><li>Distributed Ledger</li><li>Secure Ecosystem</li><li>Mining</li><li>Chronological and Time stamped</li><li>Consensus Based</li></ul><p>Let’s look into these in more detail.</p><h3>1. Decentralized System</h3><p>Blockchain is a Decentralized Technology, by design.When something is controlled by a central authority, where the power to make decision lies in the hands of the apex of the management, such system is called a Centralized System. Banks, for example, are a centralized system, where it’s the responsibility of the Governor to make decisions.</p><p>On the contrary, when the power is vested in the hands of the people or the users, such system is said to be a Decentralized System. The peer to peer network, Torrent, for example is a decentralised system, where the user has complete control.</p><h3>2. Distributed Ledger</h3><p>Blockchains use distributed Ledger Technology (DLT) to store and access the data around.When something is stored on a Distributed Ledger, multiple copies of it are made across the network at the same time. Unlike traditional databases, distributed ledger do not have a central database or administration functionality.When applied in a decentralized system like Blockchain, each user has a copy of the ledger and participates in the transaction verification. This gives Blockchain the property of Immutability and ensures security. Since, the data is distributed, there is no centralized version of the data for the hackers to corrupt. The data and the records are public and easily verifiable. This also eliminates single point of Failure.</p><h3>3. Secure Ecosystem</h3><p>BlockTech uses the concepts like Proof of Work and Hash encryption to ensure security and immutability. Proof of work involves several people around the world using computational algorithm to try and find the appropriate hash value that satisfies a predefined condition regarding the hash value.</p><h3>4. Mining</h3><p>Torrent is a peer-to-peer decentralised network used to share files. BlockTech uses similar technology. What differentiates the users is that, in Torrent, the system relies on the honor code of the users to seed the files. Whereas, in blockchain, the users who are involved in the transaction have economic incentives. These users are called “Miners.” The Miners spend their computing resources to solve the cryptographic hashes and ensure immutability and reliability of the transaction. Every successful solution (decryption) ensures some economic benefit.</p><h3>5. Chronological and Time stamped</h3><p>Blockchains, ideally, are just very sophisticated linked lists where each block is a repository that stores information pertaining to a transaction and also links to the previous block in the same transaction. These blocks are arranged in an order and are time-stamped during creation to ensure a fair record.</p><h3>6. Consensus Based</h3><p>Consensus Based is an approach to decision making. It is a creative and dynamic way of reaching agreement between all members of a group. A transaction on Blockchain can be executed only if all the parties on the network unanimously approve it. It is however, subjected to alterations to suit various circumstances.</p><h3>Why use blockchain?</h3><p>What happens if you and your friend <em>independently and separately</em> conduct the same petition campaign? Let’s say it’s for the “save the planet” cause.</p><p>Let’s say you conduct it in an identical sequence across the same continent, but come up with different sets of signatures on the petition. Which version of the signed petition is the “source of truth”?</p><p>You would need to trace back your separate trails, one signature at a time, to locate the <em>last</em> discrepancy. And then you’d have to work further back to identify the first result that diverged between your signature sheets. Prior to that root divergence, all other signatures on the two lists should match up.</p><p>You then know that prior to that divergence. Both lists are in accord, so those signatures represent the minimum number of people who signed to support saving the planet.</p><p>While that may work well for planet and continental surveys, it doesn’t work so well in the digital world. or voting, banking, financial transactions, transferring land title, discharging contractual obligations etc. You need independent and “trusted third parties” to verify a chain of events, and solemnly reassure you that the “chain of custody” was unbroken.</p><p>A “chain of custody” can sometimes also be called the “provenance” — they both mean the same thing: the sequence of historical events concerning the data in question.</p><p>That’s why you have governments having the final say on your identity, and votes need to be physically counted and recounted by hundreds of volunteers, and clerks in dingy offices maintain ledgers and certificates to confirm whether or not you own your farm/white picket-fenced bungalow.</p><p>That is why you need financial intermediaries to ensure that when you buy your CR7 Jersey, using a credit card, the money (value) is “removed” from your account and “added into” to the seller’s account.</p><p>This is technically called the “<a href="https://en.wikipedia.org/wiki/Double-spending">double spending problem</a>” — how do you ensure that you’re not spending the same money twice? Without someone to do this, you could spend money and at the same time continue to hold on to that money.</p><p>So it’s a big problem really — modern life requires that we rely on, trust in and pay for “trusted” third party intermediaries to ensure that value (money) does actually digitally “change hands”. That is why Visa and MasterCard exist, and why PayPal and others link with your bank accounts.</p><h3>How Blockchain works?</h3><p>It is essential to remember that the blockchain is a technology — mathematically complex software code to be specific. And Bitcoin (or Ethereum or any of the other cryptos on offer) are just applications of that technology.</p><p>So the key principles are:</p><ul><li>Blockchains are ‘mined” (produced through the expenditure of effort, like in gold mining) by powerful and resource-hungry computers — called nodes, that are on the same network.</li><li>Chains of digitally encrypted and timestamped records of transactions are lumped into “blocks”, which are maintained on a “ledger” by each node. As transactions are added to a block, and blocks are linked together linearly and chronologically as “chains”. Then the entire record/ledger gets synchronised across the network of nodes such that all the block “chains” on the nodes should tell an identical story of the history of any given transaction. Thus we get “block + chain = blockchain”. It’s a long, complicated linked list.</li><li>Each block in a chain has its own id — a cryptographic hash that is unique and specific to each block. That hash is also stored in the <em>next</em> block in the chain, causing a link. A block can store thousands of transactions and the tiniest change in that block’s data would result in a new hash. So if a hash changes but the next block has a different hash, then we know some data in the previous block was tampered with.</li><li>As hundreds become thousands of nodes (and more are added all the time), each node has to “agree” on the history of the blocks/ledger — this is called “critical consensus”. One of the ways in which consensus is achieved is through the cryptographic hash we talked about earlier.</li><li>Where there are discrepancies in the ledger (for example the hash of a block doesn’t match with the next block’s reference to the previous block’s hash), the ledger with the longest chain of valid transactions embedded will be the “correct” one — the source of truth. Any nodes working on other (shorter versions) of the chain switch to the longer one. This maintains the critical consensus (this bit is hugely oversimplified, but sufficient for now).</li><li>Any naughty interception or change to one ledger (again, for example, where a block’s hash doesn’t tally) would immediately create a discrepancy with all the other versions. It would also have a shorter block “history” to corroborate it, which makes that tampered version a suspicious character in the blockchain network where length matters .</li><li>Replicating that discrepancy across <em>all </em>the versions of the ledger — the entire blockchain network — is such a huge task that it is computationally impractical, and would only happen if the bad guys suddenly had control over the <em>majority </em>of the nodes mining blockchain and changed them all rather rapidly. This sort of coordinated attack on the majority of the nodes on the network is often called the <a href="https://en.bitcoin.it/wiki/Majority_attack">51% attack</a>.</li></ul><h3>Let’s Code a Simple blockchain:</h3><p>Create a file name index.js and paste the code below:</p><pre><strong>const</strong> simpleHash = (<strong>data</strong>) =&gt; {<br>    <em>//simple hash function(not a cryptographic algorithm);</em><br>    <strong>return</strong> <strong>data</strong> + &#39;*&#39;;<br>}<br></pre><pre><strong>class</strong> <strong>Block</strong> {<br>    <strong>constructor</strong> (<strong>data</strong> , hash , lastHash){<br>        <em>//data:what the block is storing</em><br>        <strong>this</strong>.<strong>data</strong> = <strong>data</strong>;<br>        <em>//hash:generates unique string everytime with some cryptographic algorithm</em><br>        <strong>this</strong>.hash = hash;<br>        <em>//lastHash:creates a link between new block and last block</em><br>        <strong>this</strong>.lastHash = lastHash;<br>    }<br>}<br></pre><pre><strong>class</strong> <strong>Blockchain</strong> {<br>    <strong>constructor</strong>() {<br>        <em>//initial block for the chain</em><br>        <strong>const</strong> genesis = new Block(&#39;gen-data&#39; , &#39;gen-hash&#39; , &#39;gen-lastHash&#39;);<br>        <strong>this</strong>.chain = [genesis];<br>    }<br><em>//incoming blocks links to initial block</em><br>    addBlock(<strong>data</strong>) {<br>        <strong>const</strong> lastHash = <strong>this</strong>.chain[<strong>this</strong>.chain.length-1].hash;<br></pre><pre>        <strong>const</strong> hash = simpleHash(<strong>data</strong> + lastHash);<br></pre><pre>        <strong>const</strong> block = new Block(<strong>data</strong> ,hash , lastHash);<br></pre><pre>        <strong>this</strong>.chain.push(block);<br>    }<br>}<br></pre><pre><strong>const</strong> theBlockChain = new Blockchain();<br>theBlockChain.addBlock(&#39;one&#39;);<br>theBlockChain.addBlock(&#39;two&#39;);<br>theBlockChain.addBlock(&#39;three&#39;);<br>theBlockChain.addBlock(&#39;four&#39;);<br>theBlockChain.addBlock(&#39;five&#39;);<br>theBlockChain.addBlock(&#39;six&#39;);<br>theBlockChain.addBlock(&#39;seven&#39;);<br></pre><pre>console.log(theBlockChain);</pre><p>If you execute this file you’ll get the following output:</p><pre>Blockchain {<br>  chain: [<br>    Block {<br>      data: &#39;gen-data&#39;,<br>      hash: &#39;gen-hash&#39;,<br>      lastHash: &#39;gen-lastHash&#39;<br>    },<br>    Block { data: &#39;one&#39;, hash: &#39;onegen-hash*&#39;, lastHash: &#39;gen-hash&#39; },<br>    Block {<br>      data: &#39;two&#39;,<br>      hash: &#39;twoonegen-hash**&#39;,<br>      lastHash: &#39;onegen-hash*&#39;<br>    },<br>    Block {<br>      data: &#39;three&#39;,<br>      hash: &#39;threetwoonegen-hash***&#39;,<br>      lastHash: &#39;twoonegen-hash**&#39;<br>    },<br>    Block {<br>      data: &#39;four&#39;,<br>      hash: &#39;fourthreetwoonegen-hash****&#39;,<br>      lastHash: &#39;threetwoonegen-hash***&#39;<br>    },<br>    Block {<br>      data: &#39;five&#39;,<br>      hash: &#39;fivefourthreetwoonegen-hash*****&#39;,<br>      lastHash: &#39;fourthreetwoonegen-hash****&#39;<br>    },<br>    Block {<br>      data: &#39;six&#39;,<br>      hash: &#39;sixfivefourthreetwoonegen-hash******&#39;,<br>      lastHash: &#39;fivefourthreetwoonegen-hash*****&#39;<br>    },<br>    Block {<br>      data: &#39;seven&#39;,<br>      hash: &#39;sevensixfivefourthreetwoonegen-hash*******&#39;,<br>      lastHash: &#39;sixfivefourthreetwoonegen-hash******&#39;<br>    }<br>  ]<br>}</pre><p>Happy Coding …</p><p>Published on <a href="https://blogue.tech/blogs/a-walkthrough-to-blockchain">blogue</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72449e0131e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter bot with Node.js and Deploy to Heroku]]></title>
            <link>https://medium.com/@sujanxchhetri/twitter-bot-with-node-js-and-deploy-to-heroku-4003a2e6617e?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4003a2e6617e</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[twitterbots]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[twit]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 13:16:00 GMT</pubDate>
            <atom:updated>2023-03-12T10:10:49.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FeNX1YE3IH9cHUpTnKQmmQ.jpeg" /></figure><p>Most of us are familiar with Twitter. But we are not much familiar that we can automate the activities like status posting,retweeting,liking,commenting and so on. So,here I’ll show you how we can automate some of the activities like getting the twitter data,posting the status and retweeting with <a href="https://nodejs.org/en/docs/">Node.js</a> and a npm package called <a href="https://www.npmjs.com/package/twit">Twit</a> .And we ll deploy the project to github and heroku and keep it running…</p><blockquote><strong><em>Checkout this amazing </em></strong><a href="https://blogue.tech/"><strong><em>platform</em></strong></a></blockquote><p>Let’s start by signing in to a<a href="https://developer.twitter.com/en/docs/basics/apps/overview"> twitter developer section</a>,You’ll get insight of creating a developer account and will be able to Create an app where you will get the following keys:</p><pre>consumer_key : &#39;key&#39;,<br>consumer_secret : &#39;key&#39;,<br>access_token : &#39;key&#39;,<br>access_token_secret : &#39;key&#39;</pre><h3>Project structure:</h3><pre>project---| <br>          |--config<br>             --config.env<br>             --config.js<br>          |--botget.js //not needed for deployment<br>          |--botpost.js //not needed for deployment<br>          |--botretweet.js<br>          |--Procfile</pre><h3>Installation:</h3><p>Node.js must be installed on your system.</p><p>In the project folder,In terminal enter the following commands:</p><pre>$ git init -y<br>$ npm i twit</pre><h3>Setting up the environment variables:</h3><p>Let’s install dotenv to hide the keys when uploading to github and heroku</p><pre>$ npm i dotenv</pre><p>Create a folder config in the project directory.And inside that create a file called config.env:</p><pre>API_KEY=key<br>API_SECRET_KEY=key<br>ACCESS_TOKEN=key<br>ACCESS_TOKEN_SECRET=key</pre><p>Create another file inside project directory as config.js:</p><pre><strong>const</strong> path = require(&#39;path&#39;)<br><strong>const</strong> dotenv = require(&#39;dotenv&#39;)<br>require(&#39;dotenv&#39;).config();<br>// Load config<br>dotenv.config({ path: &#39;./config/config.env&#39; })</pre><pre>//exports the keys<br>module.exports = {<br>    consumer_key : process.env.API_KEY,<br>    consumer_secret : process.env.API_SECRET_KEY,<br>    access_token : process.env.ACCESS_TOKEN,<br>    access_token_secret : process.env.ACCESS_TOKEN_SECRET<br>}</pre><p>Now we are ready to work on the bot scripts.</p><p>You might want to look Sample <a href="https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets">JSON</a> data from twitter and <a href="https://www.npmjs.com/package/twit">twit </a>before going on further.</p><p>Create a file as botget.js in the root of the project:</p><pre>console.log(&quot;Bot is starting&quot;)<br><strong>var</strong> config = require(&#39;./config/config&#39;)//imports keys <br><strong>var</strong> Twit = require(&#39;twit&#39;);<br></pre><pre><strong>var</strong> T = <strong>new</strong> Twit(config);<br></pre><pre><strong>var</strong> parameters = {<br>    q : &#39;node&#39;,//query to search the twitter,can be any thing <br>    count : 2 //no. of data to fetch<br>}<br></pre><pre>//  search twitter for all tweets containing the word &#39;suJJJan&#39; <br>T.get(&#39;search/tweets&#39;,parameters,fetchData); <br></pre><pre><strong>function</strong> <strong>fetchData</strong> (err, data, response) {<br>    <strong>var</strong> tweets = data.statuses; <br>    <strong>for</strong>(<strong>var</strong> i=0;i&lt; tweets.length;i++){ // checks the statuses twice<br>        console.log(tweets[i].text);//prints the text<br>    }<br>    console.log(data)<br>}</pre><p>To run the script.Use:</p><pre>$ node  botget.js</pre><p>Sample Output:</p><pre>Bot is startingRT @Hello2: @random twitter is best<br>@random twitter is best<br>{<br>  statuses: [<br>    {<br>      created_at: &#39;Thu Aug 06 10:38:09 +0000 2020&#39;,<br>      id: 1291311562636183600,<br>      id_str: &#39;129110210662636183559&#39;,<br>      text: &quot;RT @Hello2: @random twitter is best&quot;,<br>      truncated: false,<br>      entities: [Object],<br>      metadata: [Object],<br>      source: &#39;&#39;,<br>      in_reply_to_status_id: null,<br>      in_reply_to_status_id_str: null,<br>      in_reply_to_user_id: null,<br>      in_reply_to_user_id_str: null,<br>      in_reply_to_screen_name: null,<br>      user: [Object],<br>      geo: null,<br>      coordinates: null,<br>      place: null,<br>      contributors: null,<br>      retweeted_status: [Object],<br>      is_quote_status: false,<br>      retweet_count: 1,<br>      favorite_count: 0,<br>      favorited: false,<br>      retweeted: false,<br>      lang: &#39;en&#39;<br>    },<br>    {<br>      created_at: &#39;Sat Aug 01 02:24:27 +0000 2020&#39;,<br>      id: 1289386479903371300,<br>      id_str: &#39;1289386479903371265&#39;,<br>      text: &quot;@ randomtwitter is best&quot;,<br>      truncated: false,<br>      entities: [Object],<br>      metadata: [Object],<br>      source: &#39;&lt;a href=&quot;http://twitter.com/download/android&quot; rel=&quot;nofollow&quot;&gt;Twitter for Android&lt;/a&gt;&#39;,<br>      in_reply_to_status_id: 128921230498288600,<br>      in_reply_to_status_id_str: &#39;1289469260498288640&#39;,<br>      in_reply_to_user_id: 832773717648143900,<br>      in_reply_to_user_id_str: &#39;832773417688143873&#39;,<br>      in_reply_to_screen_name: &#39;random&#39;,<br>      user: [Object],<br>      geo: null,<br>      coordinates: null,<br>      place: null,<br>      contributors: null,<br>      is_quote_status: false,<br>      retweet_count: 1,<br>      favorite_count: 0,<br>      favorited: false,<br>      retweeted: false,<br>      lang: &#39;en&#39;<br>    }<br>  ],<br>  search_metadata: {<br>    completed_in: 0.027,<br>    max_id: 1291322662436183600,<br>    max_id_str: &#39;1291322662636183559&#39;,<br>    next_results: &#39;?max_id=1289386479904371264&amp;q=random&amp;count=2&amp;include_entities=1&#39;,<br>    query: &#39;node&#39;,<br>    refresh_url: &#39;?since_id=1291322662646183559&amp;q=random&amp;include_entities=1&#39;,<br>    count: 2,<br>    since_id: 0,<br>    since_id_str: &#39;0&#39;<br>  }<br>}</pre><p>Create a file as botpost.js in the root of the project:</p><pre>console.log(&quot;Bot is starting&quot;)<br><strong>var</strong> config = require(&#39;./config/config&#39;)<br><strong>var</strong> Twit = require(&#39;twit&#39;);<br></pre><pre><strong>var</strong> T = <strong>new</strong> Twit(config);<br></pre><pre>tweetThis();</pre><pre>//uncomment this if u want to run the event in certain interval<br>//setInterval(tweetThis,3600000)//every 1 hour(time is in ms)</pre><pre><strong>function</strong> <strong>tweetThis</strong>() {<br>    <strong>var</strong> statsArray = [&quot;hello&quot;,&quot;How ya doin&quot;,&quot;I love node&quot;];<br>    //selects random tweets from the array<br>    <strong>var</strong> stat = statsArray[Math.floor(Math.random()*statsArray.length)]<br></pre><pre>    <strong>var</strong> tweet = {<br>    status: stat<br>    }<br></pre><pre>T.post(&#39;statuses/update&#39;,tweet,tweeted); //posts tweets<br></pre><pre><strong>function</strong> <strong>tweeted</strong> (err, data, response) {<br>    <strong>if</strong>(err){<br>        console.log(&quot;Something is wrong&quot;)<br>    }<strong>else</strong>{<br>        console.log(&quot;Works fine&quot;)<br>    }<br>} <br>}</pre><p>Now we will create a bot which retweets and deploy it to heroku.</p><p>Create a file as botretweet.js in the root of the project:</p><pre>console.log(&quot;Bot is started&quot;);<br></pre><pre><strong>var</strong> twit = require(&#39;twit&#39;);<br><strong>var</strong> config = require(&#39;./config/config&#39;);<br></pre><pre><strong>var</strong> T = <strong>new</strong> twit(config);<br></pre><pre>reTweet();<br></pre><pre>setInterval(reTweet, 3600000);//runs every hour<br></pre><pre>// find latest tweet according the query &#39;q&#39; in parameters<br>//set q as # or @ for hashtags and username.Can keep both as &#39;@tag,#hash&#39;<br><strong>function</strong> <strong>reTweet</strong>() {<br>    <strong>var</strong> parameters = {<br>        q: &#39;@suJJJan&#39;, <br>        result_type: &#39;recent&#39;,<br>        lang: &#39;en&#39;<br>    }<br></pre><pre>    T.get(&#39;search/tweets&#39;, parameters, <strong>function</strong>(err, data) {<br>        <strong>if</strong> (!err) {<br>//gets the tweetid<br>            <strong>var</strong> retweetId = data.statuses[0].id_str;<br>//retweets the status in which the &#39;q&#39; is mentioned<br>            T.post(&#39;statuses/retweet/:id&#39;,{ id : retweetId },tweeted);<br>            <strong>function</strong> <strong>tweeted</strong>(err, response) {<br>                <strong>if</strong> (response) {<br>                    console.log(&#39;Retweeted successfully&#39;);<br>                }<br>                // if there was an error while tweeting <br>                <strong>if</strong> (err) {<br>                    console.log(&#39;Duplicate tweet or Something went wrong&#39;);<br>                }<br>            }<br>        }<br>        <strong>else</strong> {<br>        console.log(&#39;Nothing found&#39;);<br>        }<br>    });<br>}</pre><p>Create Procfile in the root of the project folder:</p><p>Add the code below and save the file.</p><pre>worker:node botretweet.js</pre><h3>Pushing Code to Github:</h3><ul><li>Create a <a href="https://github.com/">github</a> account</li><li>Create a new repository</li><li>install <a href="https://git-scm.com/downloads">git</a> if u are familiar with it or else you can directly upload from the Github site</li><li>create a file called .gitignore,inside that:</li></ul><pre>node_modules<br>config/config.env</pre><p>save the file.</p><p>Now use the following commands to push code to github.</p><pre>$ git init<br>$ git add .<br>$ git commit -m &quot;initial commit&quot;<br>$ git remote add origin <a href="https://github.com/username/project.git">https://github.com/username/project.git</a><br>$ git push -u origin master</pre><p>This will deploy the project to github.</p><p>Now we will deploy the code to heroku and keep the script running forever.</p><h3>Pushing Code to Heroku:</h3><ul><li>Create a <a href="https://www.heroku.com/">heroku</a> account</li><li>You’ll see new,create new app.. <a href="https://devcenter.heroku.com/articles/github-integration">read th</a>e docs to deploy from browser</li><li>Install <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">heroku cli</a></li><li>Follow the commands</li><li>we ll have to add the keys as below:</li></ul><pre>$  heroku create appname<br>$  heroku config:set API_KEY=yourkeyhere API_SECRET_KEY=yourkeyhere ACCESS_TOKEN=yourkeyhere   ACCESS_TOKEN_SECRET=yourkeyhere<br>$ git remote set-url heroku <a href="https://git.heroku.com/appname.git">https://git.heroku.com/appname.git</a><br>$ git push heroku master</pre><p>The code will be deployed to heroku.</p><p>Then goto heroku dashboard:</p><ul><li>you will see the app which you have created</li><li>select the app</li><li>select ‘resource’</li><li>In ‘free dynos section’, you ll see ‘web npm start’ (for webapps only)</li><li>click on edit and turn if off</li><li>you ll see ‘worker node botretweet.js’ (worker are typically used for background jobs, queueing systems, and timed jobs)</li><li>click on edit and turn it on.</li><li>On adds-on section search ‘Heroku-Scheduler’</li><li>Select it and you ll reach to another dash board</li><li>Select create job.Set time as you like and in ‘Run Command’ add node botretweet.js and save job</li></ul><p>You are all set. Your bot will run and retweet every hour or so on as per the time duration you have set.</p><p>Check the full code <a href="https://github.com/sujanchhetri/twitterbotscript">here</a>. Originally posted on <a href="https://blogue.tech/blogs/twitter-bot-with-node.js-and-deploy-to-heroku">blogue</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4003a2e6617e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching Algorithms in JavaScript]]></title>
            <link>https://medium.com/@sujanxchhetri/searching-algorithms-in-javascript-ecb880f70e07?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb880f70e07</guid>
            <category><![CDATA[searching-algorithm]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 21:11:01 GMT</pubDate>
            <atom:updated>2023-03-12T10:11:50.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TbnHzMb6XEYWWuHF" /></figure><p>The Searching Algorithm can be implemented with other languages as well. But here we will work with JavaScript to solve the Searching Algorithms. These algorithms are used to handle or work with the search related task in our projects or any applications that require searching. Searching is made easier by these algorithms. Searching is fundamental to any programming language. It would be a waste to have data structures, and no way of searching through them.The two searching algorithms we will be looking at are Linear search, and Binary search.When data items are random or not sorted, we use sequential or linear search. When data is already sorted, we use binary search. Binary search only works when your data is sorted, and we must take into account the cost of sorting the data before we even begin searching through it. When writing code, performance is everything so we need to think through before we execute them. Let’s look at each algorithm.</p><blockquote><strong>Checkout this amazing </strong><a href="https://blogue.tech/"><strong>platform</strong></a><strong>:</strong></blockquote><h3>1. Linear Search</h3><p>This is the basic kind of search. Here, given a list of data, we start from the beginning of the collection and iterate through each item until we find what we are looking for. Suppose we had a dataset with 1000 items. Using Linear search it is actually possible that the item we are looking for is the 1000th item. So the worse case scenario is that we search 1000 items in order to find what we are looking for. The runtime complexity for linear search is O(n), which is a Big O notation representing the worst runtime for a given algorithm. The “n” you see stands for number of operations for a given search. Yes its possible that the item you are looking for could be the 1st item, but the truth is we really don’t know (its not sorted). If we find the item early then that’s awesome. But there is a possibility that its located at the last spot (or closer to the end), in which case we would have to go through all items before we find what we are looking for. It is also possible that we don’t find the item at all. In which case we would have also gone through 1000 items for nothing. This way of searching is the brute-force technique, because we could potentially visit all items.</p><p><strong>Pseudocode</strong></p><ul><li>Function accepts an array and a value.</li><li>Loop through the array and check if the current array element is equal to the value.</li><li>If it is,return the index at which the element is found.</li><li>If the value is never found,return -1.</li></ul><p>O(1) best,O(n) average</p><pre><strong>var</strong> linearSearch = <strong>function</strong>(city,value) {<strong>for</strong>(<strong>var</strong> i = 0;i &lt; city.length;i++){<br>        <strong>if</strong>(city[i] === value) <strong>return</strong> i;<br>    }<br>    <strong>return</strong> -1;<br>}<br></pre><pre><strong>var</strong> city = [&quot;kathmandu&quot;,&quot;pokhara&quot;,&quot;butwal&quot;,&quot;birgunj&quot;,&quot;mahendranagar&quot;,&quot;janakpur&quot;,&quot;dharan&quot;,&quot;narangadh&quot;,&quot;bhairawa&quot;]<br></pre><pre>console.log(linearSearch(city,&quot;butwal&quot;)) </pre><pre>Output:2</pre><h3>2. Binary Search</h3><p>If we have a data set that is sorted, then binary search is a better way to search.You could find any item in a collection with 1000 records much faster. This algorithm is pretty impressive, however you can only use it if the data has already been sorted. Binary search works like how humans would do search if they were looking in a dictionary for example. If i asked you to search for the CODE in a dictionary, you wouldn’t turn to the ‘A‘ section and start your search there. You would start more towards the middle of the book (say around letter M). Based on whether the alphabet you land on is high or lower, you know which direction to search (higher or lower). Alphabets B and above are higher that N, you could simply ignore all those other alphabets (narrows you collection from 26 to 13. if the collection was 1 billion, you would have narrowed it down to 500 million). This is very powerful. You can almost reduce your data list in half just because you know which direction to search. In a number guess game (where you guess a number between 1–100), if you guessed a number 60 and that final number we are looking for is higher, then you know for sure that numbers 1 to 60 can be ignored. And you only guess higher number. This is similar to how binary search works. In a worst case scenario, it would take log2 n. This is logarithmic time or O(log n). Runtime for linear search was linear time O(n).</p><p><strong>Pseudocode</strong></p><ul><li>Function accepts a sorted array and a value</li><li>Create a left pointer at the start of the array and a right pointer at the end of the array</li><li>While the left pointer comes before the right pointer:</li><li>Create a pointer in the middle.</li><li>If you find the value you want,return the index.</li><li>If the value is too small,move the left pointer up.</li><li>If the value is too large,move the right pointer down.</li><li>If you never find the value,return -1.</li></ul><pre><strong>var</strong> binarySearch = <strong>function</strong>(arr,elem){<br>    <strong>var</strong> start = 0;<br>    <strong>var</strong> end = arr.length - 1;<br>    <strong>var</strong> middle = Math.floor(start + end / 2);<br>    <strong>while</strong>(arr[middle] !== elem &amp;&amp; start &lt;= end){<br>        <strong>if</strong>(elem&lt;arr[middle]){<br>            end=middle-1;<br>        }<strong>else</strong>{<br>            start = middle+1;<br>        }<br>        middle = Math.floor((start+end)/2)<br>    }<br>    // if(arr[middle] === elem){<br>   //     return middle;<br>   // }<br>   // return -1;<br>return arr[middle] === elem ? middle : -1;<br>}<br></pre><pre>console.log(binarySearch([2,4,6,9,11,14,20,25,28,40],11)) </pre><pre>output: 4</pre><h3>3.String Search</h3><p>This not totally related to linear search or Binary search. I just wanted to add it here as it is very much important for searching string. A very simple way to search strings is given below:</p><p><strong>Pseudocode:</strong></p><ul><li>Loop Over the longer string.</li><li>Loop Over the shorter string.</li><li>If the characters don’t match,break out of the inner loop.</li><li>If the characters match,Keep going.</li><li>If you complete the inner loop and find a match, increment the count of matches.</li><li>Return the count</li></ul><pre><strong>function</strong> <strong>naiveSearch</strong>(str, word){<br>    var count = 0;<br>    <strong>for</strong>(var i = 0; i &lt; str.length; i++){<br>        <strong>for</strong>(var j = 0; j &lt; word.length; j++){<br>            <strong>if</strong>(word[j] !== str[i+j]) <strong>break</strong>;<br>            <strong>if</strong>(j === word.length - 1) count++;<br>        }<br>    }<br>    <strong>return</strong> count;<br>}<br></pre><pre>console.log(naiveSearch(&quot;search and find&quot;, &quot;an&quot;))</pre><pre>output: [7]</pre><p>But this way we have to search each and every word from the begining in case of multiple data to search.The <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm">Knuth-Morris-Pratt string search algorithm</a> or KMP algorithm is an algorithm for finding a substring within another string that uses information calculated about the substring to speed up the search process.Before looking through the text to be searched, a table of jump lengths is calculated from the search string. Rather than iterating through the whole string, you can determine how many characters to skip over based on the structure of the word being searched for. As you scan through the search text and you find a mismatch, you can start comparing characters again from the last matching substring between the search term and the search text.E.g. if you are searching through “Hello world how ya doin?” for the words “old world new”, every time you find an instance of ”old world new” that isn’t followed by a line-break, you can skip the characters of checking the string and restart from the beginning of your words, because you know that they can’t occur again within that span because you have already checked those and they don’t match the begging of the search words. Basically you already know that index is the next occurence of world, so you can start again from there.</p><pre>// Construct a table with table[i] as the length of the longest prefix of the substring 0..i<br>// create a table of size equal to the length of `str`<br>// table[i] will store the prefix of the longest prefix of the substring str[0..i]<br>// the longest prefix of the substring str[0] has length<br>// for the substrings the following substrings, we have two cases<br>// case 1. the current character doesn&#39;t match the last character of the longest prefix<br>// if that is the case, we have to backtrack, and try find a character  that will be equal to the current character<br>// if we reach 0, then we couldn&#39;t find a chracter<br>// case 2. The last character of the longest prefix matches the current character in `str`<br>// if that is the case, we know that the longest prefix at position i has one more character.<br>// for example consider `.` be any character not contained in the set [a.c]<br>// str = abc....abc<br>// consider `i` to be the last character `c` in `str`<br>// maxPrefix = will be 2 (the first `c` in `str`)<br>// maxPrefix now will be 3<br>// so the max prefix for table[9] is 3<br><strong>function</strong> <strong>makeTable</strong>(str) {<br>  <br>    <br>    <strong>var</strong> table = <strong>new</strong> Array(str.length);<br>    <strong>var</strong> maxPrefix = 0;<br>    <br>    table[0] = 0;<br>  <br>    <br>    <strong>for</strong> (<strong>var</strong> i = 1; i &lt; str.length; i++) {<br>      <strong>while</strong> (maxPrefix &gt; 0 &amp;&amp; str.charAt(i) !== str.charAt(maxPrefix)) {<br>        <br>        maxPrefix = table[maxPrefix - 1];<br>      }<br>      <br>      <strong>if</strong> (str.charAt(maxPrefix) === str.charAt(i)) {<br>        maxPrefix++;<br>      }<br>      table[i] = maxPrefix;<br>    }<br>    <strong>return</strong> table;<br>  }<br>  <br>// Find all the words that matches in a given string `str`<br>// this algorithm is based on the Knuth–Morris–Pratt algorithm. Its beauty consists in that it performs the matching in O(n)<br>// find the prefix table in O(n)<br>// `j` is the index in `word(P)`<br>// `i` is the index in `str(S)`<br>// Case 1.  S[i] == P[j] so we move to the next index in `S` and `P`<br>// Case 2.  `j` is equal to the length of `P`<br>// that means that we reached the end of `P` and thus we found a match<br>// Next we have to update `j` because we want to save some time<br>// instead of updating to j = 0 , we can jump to the last character of the longest prefix well known so far.<br>// j-1 means the last character of `P` because j is actually `P.length`<br>// e.g.<br>// S =  a b a b d e<br>// P = `a b`a b<br>// we will jump to `a b` and we will compare d and a in the next iteration<br>// a b a b `d` e<br>//  a b `a` b<br>// Case 3.<br>// S[i] != P[j] There&#39;s a mismatch!<br>// if we have found at least a character in common, do the same thing as in case 2<br>// otherwise, j = 0, and we can move to the next character S[i+1]function kmpMatching(str, word) {<br>   <br>    <strong>var</strong> prefixes = makeTable(word);<br>    <strong>var</strong> matches = [];<br>    <br>    <br>    <strong>var</strong> j = 0;<br>    <strong>var</strong> i = 0;<br>    <strong>while</strong> (i &lt; str.length) {<br>      <br>      <strong>if</strong> (str.charAt(i) === word.charAt(j)) {<br>        i++;<br>        j++;<br>      }<br>      <br>      <strong>if</strong> (j === word.length) {<br>        matches.push(i-j);<br>        <br>        j = prefixes[j-1];<br>      }<br>      <br>      <strong>else</strong> <strong>if</strong> (str.charAt(i) !== word.charAt(j)) {<br>          <br>          <strong>if</strong> (j !== 0) {<br>              j = prefixes[j-1];<br>          } <strong>else</strong> {<br>              <br>              i++;<br>          }<br>      }<br>    }<br>  <br>    <strong>return</strong> matches;<br>  }</pre><pre>console.log(kmpMatching(&quot;it implies that it is very important&quot;,&quot;impo&quot;))</pre><pre>output: [27]</pre><p>We can implement these algorithms in real world applications.Hope it helps.There are many other algorithms to use. But for a start these might help.</p><p>Happy coding…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb880f70e07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to code?]]></title>
            <link>https://medium.com/@sujanxchhetri/how-to-code-e46f6a2ce753?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e46f6a2ce753</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 20:11:00 GMT</pubDate>
            <atom:updated>2023-03-12T10:12:33.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vXJlJvzprBm0zirh" /></figure><p>Every programming problem involves some kind of algorithm. Algorithm is a process or set of steps to accomplish a certain tasks or a step by step way to solve a problem. There are about 700 programming languages. Here is a <a href="https://en.wikipedia.org/wiki/List_of_programming_languages">list</a>. So what to learn and why to learn that’s most of the people stuck on. In my perspective You can learn any. Learning basics of some on-demand programming language is not a harm. But you must select a language that becomes your magic spell and you should always be ready to create something out of it. Learning varieties of languages and not being able to do anything is like a curse. So,that’s all about leaning and selecting.Now I will mention the steps which I follow to solve a problem. I have broken it into 5 steps. Here I go then.</p><blockquote><strong>Checkout this amazing </strong><a href="https://blogue.tech/"><strong>platform</strong></a><strong>:</strong></blockquote><ul><li>Understand the problem</li><li>Explore Examples</li><li>Break it Down</li><li>Solve / Simplify</li><li>Look Back and Refactor</li></ul><p>Let’s look the steps into more detail with examples. As I am deeply in love with JavaScript I will be using that. Feel free to use your own magic spell.</p><p>Example question: Count the value of only numbers and alphabets from a given string “Hello There Blogue IS A BEauTIFUL %^$##@123451112231144 !!!!!$%#”</p><h3>1. Understand the problem</h3><ul><li>Can I restate the problem in own word?</li><li>What are the inputs that go into the problem?</li><li>What are the outputs that should come from the solution to the problem?</li><li>Can the outputs be determined from the input?</li><li>Do I have enough information to solve the problem?</li><li>How should I label the important pieces of data that are a part of the problem?</li></ul><pre>Input:<br><strong>integer</strong>?<br><strong>float</strong>?<br><strong>string</strong>?<br>str(&quot;Hello There Blogue IS A BEauTIFUL %^$##@123451112231144 !!!!!$%#&quot;)<br>Output:<br><strong>integer</strong>?<br><strong>float</strong>?<br><strong>string</strong>?<br>result: { h: 2, e: 3, l: 2, o: 2, t: 1, r: 1, f: 1, u: 2, c: 1, k: 1, y: 1 }</pre><h3>2. Explore Examples</h3><ul><li>Which can help understand the problem better.</li><li>Provides sanity checks that your eventual solution works how it should.</li><li>Start with simple examples.</li><li>Move to complex example.</li><li>Explore examples with empty inputs.</li><li>Explore examples with Invalid inputs.</li></ul><pre>//example1<br><strong>let</strong> str = &#39;&#39;;<br></pre><pre><strong>for</strong> (<strong>let</strong> i = 0; i &lt; 9; i++) {<br>  str = str + i;<br>}<br>console.log(str);</pre><pre>//example2<br><strong>const</strong> sentence = &#39;The quick brown fox jumps over the lazy dog.&#39;;</pre><pre>console.log(sentence.toLowerCase());</pre><pre>//example3<br><strong>function</strong> <strong>testNum</strong>(a) {<br>  <strong>let</strong> result;<br>  <strong>if</strong> (a &gt; 0) {<br>    result = &#39;positive&#39;;<br>  } <strong>else</strong> {<br>    result = &#39;NOT positive&#39;;<br>  }<br>  <strong>return</strong> result;<br>}</pre><h3>3.Break it Down</h3><ul><li>Explicitly write out the steps you need to take.</li><li>Comment out steps to be used</li></ul><pre><strong>function</strong> <strong>countValues</strong>(str){<br>                                   <strong>var</strong> result = {};<br>                                  <strong>for</strong>(<strong>var</strong> i=0;i&lt;str.length;i++)<br>                                 {<br>                                   <strong>var</strong> chara = str[i].toLowerCase();<br>     //conversion of string to lowercase as the same letter is in small and in capital,we don&#39; want that<br>                                         <strong>if</strong>(result[chara]&gt;0){   <br>                                            result[chara]++;<br>     //increments the count if condition is grater than 0;<br>                                           }<strong>else</strong>{<br>     //else makes it 1<br>                                                  result[chara] = 1;<br>                                           }<br>                                           }<br>        }<br>                                           console.log(result) ;<br>        }<br>countValues(&quot;Hello There Blogue IS A BEauTIFUL %^$##@123451112231144 !!!!!$%#&quot;)</pre><p>We are near to the solution but its not totally correct. We still need to eliminate the spaces and the symbols.</p><h3>4.Solve / Simplify</h3><ul><li><strong>Solve</strong> a simpler problem.</li><li><strong>Find</strong> the core difficulty in what you are trying to do.</li><li>Temporarily skip the difficulty.</li><li><strong>Write</strong> a simplified solution.</li><li>Then incorporate that difficulty back in the code.</li></ul><pre><strong>function</strong> <strong>countValues</strong>(str){<br>                                   <strong>var</strong> result = {};<br>                                   //for(var i=0;i&lt;str.length;i++)<br>                                   <strong>for</strong>(<strong>var</strong> chara <strong>of</strong> str)<br>                                   {<br>                                   //var chara = str[i].toLowerCase();<br>                                   chara = chara.toLowerCase();<br>                                   <br>                                   //R.E to check lowercase and number<br>                                   <strong>if</strong>(/[a-z0-9]/.test(chara)){<br>                                   result[chara] = ++result[chara] || 1;<br>                                   <br>                                   // if(result[chara]&gt;0){<br>                                   <br>                                   // result[chara]++;<br>                                   // }else{<br>                                   //                   result[chara] = 1;<br>                                   // }<br>                                   }<br>}<br>                                   console.log(result) ;<br>}<br>countValues(&quot;Hello There Blogue IS A BEauTIFUL %^$##@123451112231144 !!!!!$%#&quot;)</pre><p>Now our solution is complete. But In real life application we check the speed of the approach,how fast the code executes to give output.So, we follow step 5.</p><h3>5.Look Back and Refactor</h3><ul><li>Can you derive the result differently?</li><li>Can you understand it at a glance?</li><li>Can you use the result or method for other problem?</li><li>Can you improve the performance of your solution?</li><li>Can you think of other ways to refactor the code?</li><li>How have other people solved the same problem?</li></ul><pre><strong>function</strong> <strong>countValues</strong>(str){<br>                                   <strong>var</strong> result = {};<br>                                   <strong>for</strong>(<strong>var</strong> chara <strong>of</strong> str){<br>                                   <br>                                   <strong>if</strong>(isAlphaNumeric(chara)){<br>                                   chara = chara.toLowerCase();<br>                                   result[chara] = ++result[chara] || 1;<br>}<br>}<br>console.log(result) ;<br>}<br></pre><pre><strong>function</strong> <strong>isAlphaNumeric</strong>(chara){<br>                                   <strong>var</strong> code = chara.charCodeAt(0);<br><strong>if</strong>(!(code &gt; 47 &amp;&amp; code &lt; 58)&amp;&amp; !(code &gt; 64 &amp;&amp; code &lt; 91)&amp;&amp; !(code &gt; 96 &amp;&amp; code &lt; 123))<br>{<br><strong>return</strong> false; <br>}<br><strong>return</strong> true;<br>}<br>countValues(&quot;Hello There Blogue IS A BEauTIFUL %^$##@123451112231144 !!!!!$%#&quot;)</pre><p>When we compare the speed of the code in step 4 (55% slower) . This code is pretty much faster in execution.</p><p>That’s all I do for solving problems .Different people have their own perspective. You can try these steps and see the result.</p><p>Learn, Code , Create repeat…..(^ _ ^)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e46f6a2ce753" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node Authentication using Passport.js]]></title>
            <link>https://medium.com/@sujanxchhetri/node-authentication-using-passport-js-760f7b52ce14?source=rss-8ef79296f97c------2</link>
            <guid isPermaLink="false">https://medium.com/p/760f7b52ce14</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[passportjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sujan Chhetri]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 18:07:55 GMT</pubDate>
            <atom:updated>2023-03-12T10:13:21.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QN_3BQBxB56FY88Z.jpg" /></figure><p>While building any web app people get confused or feel difficulty in authentication process. Creating a registration form and sign in process is a hectic process if we don’t follow proper method.</p><blockquote><strong>Checkout this amazing </strong><a href="https://blogue.tech/"><strong>platform</strong></a><strong>:</strong></blockquote><p>In this tutorial we will see how we can register and login using passport-local.</p><h3>Setting Up Our Application:</h3><p>To set up our base Node application, we’ll need a few things. We’ll set up our npm packages, node application, configuration files, models, and routes.</p><h3>Application Structure:</h3><pre>- app<br>------ models<br>---------- user.js  // our user model --&gt;<br>------ routes.js    // all the routes for our application --&gt;<br>- config<br>------ auth.js      // will hold all our client secret keys (facebook, twitter, google) --&gt;<br>------ database.js  // will hold our database connection settings --&gt;<br>------ passport.js  // configuring the strategies for passport --&gt;<br>- views<br>------ index.ejs    // show our home page with login links --&gt;<br>------ login.ejs    // show our login form --&gt;<br>------ signup.ejs   // show our signup form --&gt;<br>------ profile.ejs  // after a user logs in, they will see their profile --&gt;<br>- <strong>package</strong>.json   <br>   // handle our npm packages --&gt;<br>- server.js  // setup our application --&gt;</pre><p>Create all those files and folders and we’ll fill them in as we go along.</p><h3>Packages / package.json:</h3><p>We are going to install all the packages needed for the entire tutorial series. This means we’ll install all the packages needed for passport local and the other things we need.</p><pre>&quot;dependencies&quot;: {<br>&quot;bcrypt-nodejs&quot;: &quot;0.0.3&quot;,<br>&quot;body-parser&quot;: &quot;^1.19.0&quot;,<br>&quot;connect-flash&quot;: &quot;^0.1.1&quot;,<br>&quot;cookie-parser&quot;: &quot;^1.4.5&quot;,<br>&quot;ejs&quot;: &quot;^3.0.1&quot;,<br>&quot;express&quot;: &quot;^4.17.1&quot;,<br>&quot;express-session&quot;: &quot;^1.17.0&quot;,<br>&quot;method-override&quot;: &quot;^3.0.0&quot;,<br>&quot;mongoose&quot;: &quot;^5.9.6&quot;,<br>&quot;morgan&quot;: &quot;^1.10.0&quot;,<br>&quot;passport&quot;: &quot;^0.4.1&quot;,<br>&quot;passport-local&quot;: &quot;^1.0.0&quot;,<br>}</pre><p>Most of the packages are self-explanatory.</p><ul><li>Express is the framework.</li><li>Ejs is the templating engine.</li><li>Mongoose is object modeling for our MongoDB database.</li><li>Passport stuff will help us authenticating with different methods.</li><li>Connect-flash allows for passing session flashdata messages.</li><li>Bcrypt-nodejs gives us the ability to hash the password.</li></ul><p>npm i With all of our packages ready to go, let’s set up our application in server.js.</p><h3>Setting up server.js:</h3><p>Let’s make all our packages work together nicely. Our goal is to set up this file and try to have it bootstrap our entire application. We’d like to not go back into this file if it can be helped. This file will be the glue for our entire application.</p><pre><strong>var</strong> express  = <strong>require</strong>(&#39;express&#39;);<br><strong>var</strong> app      = express();<br><strong>var</strong> port     = process.env.PORT || 8000;<br><strong>var</strong> mongoose = <strong>require</strong>(&#39;mongoose&#39;);<br><strong>var</strong> passport = <strong>require</strong>(&#39;passport&#39;);<br><strong>var</strong> flash    = <strong>require</strong>(&#39;connect-flash&#39;);</pre><pre><strong>var</strong> morgan= <strong>require</strong>(&#39;morgan&#39;);<br><strong>var</strong> cookieParser = <strong>require</strong>(&#39;cookie-parser&#39;);<br><strong>var</strong> bodyParser   = <strong>require</strong>(&#39;body-parser&#39;);<br><strong>var</strong> session      = <strong>require</strong>(&#39;express-session&#39;);</pre><pre> // connect to our database<br>mongoose.connect(&#39;mongodb://localhost/blog&#39;, {<br>useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true<br>})<br>// pass passport for configuration</pre><pre>// set up our express application<br>app.<strong>use</strong>(morgan(&#39;dev&#39;)); // log every request to the console<br>app.<strong>use</strong>(cookieParser()); // read cookies (needed <strong>for</strong> auth)<br>app.<strong>use</strong>(bodyParser()); // get information <strong>from</strong> html forms</pre><pre>app.set(&#39;view engine&#39;, &#39;ejs&#39;); // set up ejs</pre><pre>// required for passport<br>app.<strong>use</strong>(session({ secret: &#39;ilovenodejs&#39; })); // session secret<br>app.<strong>use</strong>(passport.initialize());<br>app.<strong>use</strong>(passport.session()); // persistent login sessions<br>app.<strong>use</strong>(flash()); // <strong>use</strong> connect-flash <strong>for</strong> flash messages stored in session</pre><pre>// routes <br><strong>require</strong>(&#39;./app/routes.js&#39;)(app, passport); <br><strong>require</strong>(&#39;./config/passport&#39;)(passport); <br></pre><pre>app.listen(port);</pre><p>The path of our passport object is important to note here. We will create it at the very beginning of the file with var passport = require(‘passport’);. Then we pass it into our config/passport.js file for it to be configured. Then we pass it to the app/routes.js file for it to be used in our routes.</p><p>Now with this file, we have our application listening on port 8000. All we have to do to start up our server is:</p><pre>npm i nodemon</pre><pre>&quot;scripts&quot;: {<br>&quot;on&quot;: &quot;nodemon server.js&quot;,<br>&quot;start&quot;: &quot;node server.js&quot;</pre><p>}</p><p>In json file edit as above.</p><p>To start the node server,In terminal.Our server will start.</p><pre>nodemon</pre><h3>Routes app/routes.js:</h3><p>We will have the following routes:</p><ul><li>Home Page (/)</li><li>Login Page (/login)</li><li>Signup Page (/signup)</li><li>Profile Page (/profile)</li></ul><pre>module.exports = <strong>function</strong>(app, passport) {<br>// =======================HOME-PAGE ===============================<br>app.get(&#39;/&#39;, <strong>function</strong>(req, res) {<br>res.render(&#39;index.ejs&#39;); // load the index.ejs file<br>});<br>// ==========================LOGIN ===============================<br>app.get(&#39;/login&#39;, <strong>function</strong>(req, res) {<br>res.render(&#39;login.ejs&#39;, { message: req.flash(&#39;loginMessage&#39;) }); <br>});</pre><pre>// =====================SIGNUP ==============================<br>app.get(&#39;/signup&#39;, <strong>function</strong>(req, res) {<br>res.render(&#39;signup.ejs&#39;, <br>{ message: req.flash(&#39;signupMessage&#39;) });<br>});</pre><pre>//==========================profile =====================      <br>app.get(&#39;/profile&#39;, isLoggedIn, <strong>function</strong>(req, res) {<br>res.render(&#39;profile.ejs&#39;, {<br>user : req.user<br>});<br>});<br>// LOGOUT <br>app.get(&#39;/logout&#39;, <strong>function</strong>(req, res) {<br>req.logout();<br>res.redirect(&#39;/&#39;);<br>});</pre><pre>// process the signup form<br>app.post(&#39;/signup&#39;, passport.authenticate(&#39;local-signup&#39;, {<br>successRedirect : &#39;/profile&#39;, //redirect to the secure profile section<br>failureRedirect : &#39;/signup&#39;, // redirect back to the signup page if there is an error<br>failureFlash : true // allow flash messages<br>}));</pre><pre> // process the login form<br>app.post(&#39;/login&#39;, passport.authenticate(&#39;local-login&#39;,{<br>successRedirect : &#39;/profile&#39;, //redirect to the secure profile section<br>failureRedirect : &#39;/login&#39;, // redirect back to the signup page if there is an error<br>failureFlash : true // allow flash messages<br>}));<br>};</pre><pre>// makes sure a user is logged in<br><strong>function</strong> <strong>isLoggedIn</strong>(req, res, next){<br>// if user is authenticated in the session, carry on <br><strong>if</strong> (req.isAuthenticated())<br><strong>return</strong> next();</pre><pre>// if they aren&#39;t redirect them to the home page<br>res.redirect(&#39;/&#39;);<br>}</pre><p>This is our app/routes.js file</p><h3>Home Page views/index.ejs:</h3><p>Our home page will just show links to all our forms of authentication.</p><pre>&lt;!doctype html&gt;<br>&lt;<strong>html</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>&lt;<strong>title</strong>&gt;Authentication &lt;/<strong>title</strong>&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&quot;&gt;  &lt;!-- load bootstrap css --&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css&quot;&gt;  &lt;!-- load fontawesome --&gt;<br>&lt;<strong>style</strong>&gt;<br>body     { <strong>padding-top</strong>:80px; }<br>&lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;container&quot;&gt;<br>&lt;<strong>div</strong> class=&quot;jumbotron text-center&quot;&gt;<br>&lt;<strong>p</strong>&gt;Login or Register with: &lt;/<strong>p</strong>&gt;<br>&lt;<strong>a</strong> href=&quot;/login&quot; class=&quot;btn btn-default&quot;&gt;<br>&lt;<strong>span</strong> class=&quot;fa fa-user&quot;&gt; &lt;/<strong>span</strong>&gt; Local Login &lt;/<strong>a</strong>&gt;<br>&lt;<strong>a</strong> href=&quot;/signup&quot; class=&quot;btn btn-default&quot;&gt; <br>&lt;<strong>span</strong> class=&quot;fa fa-user&quot;&gt; &lt;/<strong>span</strong>&gt; Local Signup &lt;/<strong>a</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><p>This is our /view/index.ejs file.</p><h3>Login Form views/login.ejs:</h3><pre>&lt;!doctype html&gt;<br>&lt;<strong>html</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>&lt;<strong>title</strong>&gt;Node Authentication&lt;/<strong>title</strong>&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&quot;&gt; &lt;!-- load bootstrap css --&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css&quot;&gt; &lt;!-- load fontawesome --&gt;<br>&lt;<strong>style</strong>&gt;<br>body { <strong>padding-top</strong>:80px; }<br>&lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;container&quot;&gt;</pre><pre>&lt;<strong>div</strong> class=&quot;col-sm-6 col-sm-offset-3&quot;&gt;</pre><pre>&lt;<strong>h1</strong>&gt;&lt;<strong>span</strong> class=&quot;fa fa-sign-in&quot;&gt;&lt;/<strong>span</strong>&gt; Login&lt;/<strong>h1</strong>&gt;</pre><pre>&lt;!-- show any messages that come back with authentication --&gt;<br>&lt;<strong>%</strong> if (message.length &gt; 0) { %&gt;<br>&lt;<strong>div</strong> class=&quot;alert alert-danger&quot;&gt;&lt;<strong>%=</strong> message %&gt;&lt;/<strong>div</strong>&gt;<br>&lt;<strong>%</strong> } %&gt;</pre><pre>&lt;!-- LOGIN FORM --&gt;<br>&lt;<strong>form</strong> action=&quot;/login&quot; method=&quot;post&quot;&gt;<br>&lt;<strong>div</strong> class=&quot;form-group&quot;&gt;<br>&lt;<strong>label</strong>&gt;Email&lt;/<strong>label</strong>&gt;<br>&lt;<strong>input</strong> required type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;email&quot;&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;form-group&quot;&gt;<br>&lt;<strong>label</strong>&gt;Password&lt;/<strong>label</strong>&gt;<br>&lt;<strong>input</strong> required type=&quot;password&quot; class=&quot;form-control&quot; name=&quot;password&quot;&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>button</strong> type=&quot;submit&quot; class=&quot;btn btn-warning btn-lg&quot;&gt;Login&lt;/<strong>button</strong>&gt;<br>&lt;/<strong>form</strong>&gt;</pre><pre>&lt;<strong>hr</strong>&gt;</pre><pre>&lt;<strong>p</strong>&gt;Need an account? &lt;<strong>a</strong> href=&quot;/signup&quot;&gt;Signup&lt;/<strong>a</strong>&gt;&lt;/<strong>p</strong>&gt;<br>&lt;<strong>p</strong>&gt;Or go &lt;<strong>a</strong> href=&quot;/&quot;&gt;home&lt;/<strong>a</strong>&gt;.&lt;/<strong>p</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><p>This is our /view/login.ejs file.</p><h3>Signup Form views/signup.ejs:</h3><pre>&lt;!doctype html&gt;<br>&lt;<strong>html</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>&lt;<strong>title</strong>&gt;Signup&lt;/<strong>title</strong>&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&quot;&gt; &lt;!-- load bootstrap css --&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css&quot;&gt; &lt;!-- load fontawesome --&gt;<br>&lt;<strong>style</strong>&gt;<br>body { <strong>padding-top</strong>:80px; }<br>&lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;container&quot;&gt;</pre><pre>&lt;<strong>div</strong> class=&quot;col-sm-6 col-sm-offset-3&quot;&gt;</pre><pre>&lt;<strong>h1</strong>&gt;&lt;<strong>span</strong> class=&quot;fa fa-sign-in&quot;&gt;&lt;/<strong>span</strong>&gt; Signup&lt;/<strong>h1</strong>&gt;</pre><pre>&lt;!-- show any messages that come back with authentication --&gt;<br>&lt;<strong>%</strong> if (message.length &gt; 0) { %&gt;<br>&lt;<strong>div</strong> class=&quot;alert alert-danger&quot;&gt;&lt;<strong>%=</strong> message %&gt;&lt;/<strong>div</strong>&gt;<br>&lt;<strong>%</strong> } %&gt;<br>&lt;!-- LOGIN FORM --&gt;<br>&lt;<strong>form</strong> action=&quot;/signup&quot; method=&quot;post&quot;&gt;<br>&lt;<strong>div</strong> class=&quot;form-group&quot;&gt;<br>&lt;<strong>label</strong>&gt;Email&lt;/<strong>label</strong>&gt;<br>&lt;<strong>input</strong> required type=&quot;text&quot; class=&quot;form-control&quot; name=&quot;email&quot;&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;form-group&quot;&gt;<br>&lt;<strong>label</strong>&gt;Password&lt;/<strong>label</strong>&gt;<br>&lt;<strong>input</strong> required type=&quot;password&quot; class=&quot;form-control&quot; name=&quot;password&quot;&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>button</strong> type=&quot;submit&quot; class=&quot;btn btn-warning btn-lg&quot;&gt;Signup&lt;/<strong>button</strong>&gt;<br>&lt;/<strong>form</strong>&gt;<br>&lt;<strong>hr</strong>&gt;<br>&lt;<strong>p</strong>&gt;Already have an account? &lt;<strong>a</strong> href=&quot;/login&quot;&gt;Login&lt;/<strong>a</strong>&gt;&lt;/<strong>p</strong>&gt;<br>&lt;<strong>p</strong>&gt;Or go &lt;<strong>a</strong> href=&quot;/&quot;&gt;home&lt;/<strong>a</strong>&gt;.&lt;/<strong>p</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><p>This is our /view/signup.ejs file.</p><h3>Authenticating With Passport Locally:</h3><p>Finally! We have finally set up our application and have gotten to the authentication part. So far we have installed our packages, set up our application, connected to our database, created our routes, and created our views.</p><p>Now we will create our user model, configure passport for local authentication, and use our configured passport to process our login/signup forms.</p><h3>User Model:</h3><p>For local accounts, we will be keeping email and password. You can change these fields out to be whatever you want. You can authenticate locally using username and password (passport-local actually uses username by default but we’ll change that to email).</p><pre><strong>var</strong> mongoose = require(&#39;mongoose&#39;);<br><strong>var</strong> bcrypt   = require(&#39;bcrypt-nodejs&#39;);</pre><pre>// define the schema for our user model<br><strong>var</strong> userSchema = mongoose.Schema({</pre><pre>    local     : {<br> email : String,<br> password     : String,<br>    },<br>    facebook  : {<br> id    : String,<br> token : String,<br> name  : String,<br> email : String<br>    },<br>    twitter   : {<br> id    : String,<br> token : String,<br> displayName  : String,<br> username     : String<br>    },<br>    google    : {<br> id    : String,<br> token : String,<br> email : String,<br> name  : String<br>    }</pre><pre>});</pre><pre>// generating a hash<br>userSchema.methods.generateHash = <strong>function</strong>(password) {<br>    <strong>return</strong> bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);<br>};</pre><pre>// checks if password is valid<br>userSchema.methods.validPassword = <strong>function</strong>(password) {<br>    <strong>return</strong> bcrypt.compareSync(password, this.local.password);<br>};</pre><pre>// create the model for users and expose it to our app<br>module.exports = mongoose.model(&#39;User&#39;, userSchema);</pre><p>This is our app/models/user.js file.</p><p>Our model is done. We will be hashing our password within our user model before it saves to the database. This means we don’t have to deal with generating the hash ourselves. It is all handled nicely and neatly inside our user model.</p><h3>Configuring Passport for Local Accounts:</h3><p>All the configuration for passport will be handled in config/passport.js. We want to keep this code in its own file away from our other main files like routes or the server file. I have seen some implementations where passport will be configured in random places. I believe having it in this config file will keep your overall application clean and concise.</p><pre><strong>var</strong> LocalStrategy = <strong>require</strong>(&#39;passport-local&#39;).Strategy;<br><strong>var</strong> User= <strong>require</strong>(&#39;../app/models/user&#39;);</pre><pre>module.exports = <strong>function</strong>(passport) {<br>//passport  serialize and unserialize users out of session<br>passport.serializeUser(<strong>function</strong>(user, done) {<br>done(null, user.id);<br>});</pre><pre>passport.deserializeUser(<strong>function</strong>(id, done) {<br>User.findById(id, <strong>function</strong>(err, user) {<br>done(err, user);<br>});<br>});</pre><pre>// ======================SIGNUP ===========================<br>passport.<strong>use</strong>(&#39;local-signup&#39;, <strong>new</strong> LocalStrategy({<br>// by default, local strategy uses username and password, we will override with email<br>usernameField : &#39;email&#39;,<br>passwordField : &#39;password&#39;,<br>passReqToCallback : true <br>// allows us to pass back the entire request to the callback<br>},<br><strong>function</strong>(req, email, password, done) {<br> // User.findOne won&#39;t fire unless data is sent back<br>process.nextTick(<strong>function</strong>() {</pre><pre>// find a user whose email is the same as the forms email<br>User.findOne({ &#39;local.email&#39; :  email }, <strong>function</strong>(err, user) {<br><strong>if</strong> (err)<br><strong>return</strong> done(err);</pre><pre><strong>if</strong> (user) {<br><strong>return</strong> done(null, false, req.flash(&#39;signupMessage&#39;, &#39;That email is already taken.&#39;));<br>} <strong>else</strong> {</pre><pre>// if there is no user with that email -create the user<br><strong>var</strong> newUser = <strong>new</strong> User();</pre><pre>// set the user&#39;s local credentials<br>newUser.local.email    = email;<br>newUser.local.password = newUser.generateHash(password);</pre><pre>// save the user<br>newUser.save(<strong>function</strong>(err) {<br><strong>if</strong> (err)<br><strong>throw</strong> err;<br><strong>return</strong> done(null, newUser);<br>});<br>}<br>});    <br>});<br>}));<br>// =================LOCAL LOGIN ======================================<br>passport.<strong>use</strong>(&#39;local-login&#39;, <strong>new</strong> LocalStrategy({<br>usernameField : &#39;email&#39;,<br>passwordField : &#39;password&#39;,<br>passReqToCallback : true <br>},<br><strong>function</strong>(req, email, password, done) { <br>// find a user whose email is the same as the forms email<br>User.findOne({ &#39;local.email&#39; :  email }, <strong>function</strong>(err, user) {<br><strong>if</strong> (err)<br><strong>return</strong> done(err);<br><strong>if</strong> (!user)<br><strong>return</strong> done(null, false, req.flash(&#39;loginMessage&#39;, &#39;No user found.&#39;)); // req.flash is the way to set flashdata using connect-flash<br><strong>if</strong> (!user.validPassword(password))<br><strong>return</strong> done(null, false, req.flash(&#39;loginMessage&#39;, &#39;Oops! Wrong password.&#39;)); // create the loginMessage and save it to session as flashdata<br>// all is well, return successful user<br><strong>return</strong> done(null, user);<br>});<br>}));</pre><pre>};</pre><p>So far, we created our passport object in server.js, and then we pass it to our config/passport.js file. This is where we configure our Strategy for local.</p><p>This is also the file where we create the serializeUser and deserializeUser functions to store our user in session.</p><p>We have now provided a strategy to passport called local-signup. We will use this strategy to process our signup form. Let’s open up our app/routes.js and handle the POST for our signup form.</p><p>// app/routes.js</p><pre>...</pre><pre>    // process the signup form<br>    app.post(&#39;/signup&#39;, passport.authenticate(&#39;local-signup&#39;, {<br> successRedirect : &#39;/profile&#39;, // redirect to the secure profile section<br> failureRedirect : &#39;/signup&#39;, // redirect back to the signup page if there is an error<br> failureFlash : true // allow flash messages<br>    }));</pre><pre>...</pre><p>With users able to sign up, let’s give them a way to login.We have provided a strategy to passport called local-login. We will use this strategy to process our login form. We can check if a user exists, if the password is wrong, and set flash data to show error messages. Let’s open up our app/routes.js and handle the POST for our login form.</p><pre>// app/routes.js<br>...</pre><pre>    // process the login form<br>    app.post(&#39;/login&#39;, passport.authenticate(&#39;local-login&#39;, {<br> successRedirect : &#39;/profile&#39;, // redirect to the secure profile section<br> failureRedirect : &#39;/login&#39;, // redirect back to the signup page if there is an error<br> failureFlash : true // allow flash messages<br>    }));<br>...</pre><p>If you try to login with a user email that doesn’t exist in our database, you will see the error. Same goes for if your password is wrong.</p><h3>Displaying User and Secure Profile Page views/profile:</h3><p>Now we have functional signup and login forms. If a user is successful in authenticating they will be redirected to the profile page. If they are not successful, they will go home. The last thing we need to do is make our profile page.</p><pre>&lt;!doctype html&gt;<br>&lt;<strong>html</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>&lt;<strong>title</strong>&gt;Profile&lt;/<strong>title</strong>&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css&quot;&gt;<br>&lt;<strong>link</strong> rel=&quot;stylesheet&quot; href=&quot;//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css&quot;&gt;<br>&lt;<strong>style</strong>&gt;<br>body{ <strong>padding-top</strong>:80px; <strong>word-wrap</strong>:break-word; }<br>&lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;container&quot;&gt;<br>&lt;<strong>div</strong> class=&quot;page-header text-center&quot;&gt;<br>&lt;<strong>h1</strong>&gt;&lt;<strong>span</strong> class=&quot;fa fa-anchor&quot;&gt;&lt;/<strong>span</strong>&gt; Profile Page&lt;/<strong>h1</strong>&gt;<br>&lt;<strong>a</strong> href=&quot;/logout&quot; class=&quot;btn btn-default btn-sm&quot;&gt;Logout&lt;/<strong>a</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>div</strong> class=&quot;row&quot;&gt;<br> &lt;!-- INFORMATION --&gt;<br>&lt;<strong>div</strong> class=&quot;col-sm-6&quot;&gt;<br>&lt;<strong>div</strong> class=&quot;well&quot;&gt;<br>&lt;<strong>h3</strong>&gt;&lt;<strong>span</strong> class=&quot;fa fa-user&quot;&gt;&lt;/<strong>span</strong>&gt; Local&lt;/<strong>h3</strong>&gt;<br>&lt;<strong>p</strong>&gt;<br>&lt;<strong>strong</strong>&gt;id&lt;/<strong>strong</strong>&gt;: &lt;<strong>%=</strong> user._id %&gt;&lt;<strong>br</strong>&gt;<br>&lt;<strong>strong</strong>&gt;email&lt;/<strong>strong</strong>&gt;: &lt;<strong>%=</strong> user.local.email %&gt;&lt;<strong>br</strong>&gt;<br>&lt;<strong>strong</strong>&gt;password&lt;/<strong>strong</strong>&gt;: &lt;<strong>%=</strong> user.local.password %&gt;<br>&lt;/<strong>p</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><h3>Conclusion:</h3><p>We’ve built a brand new application from scratch and have the ability to let users signup/register and login. We even have support for flash messages, hashing passwords, and requiring login for some sections of our site using route middleware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760f7b52ce14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>