<?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 Pavan Boro on Medium]]></title>
        <description><![CDATA[Stories by Pavan Boro on Medium]]></description>
        <link>https://medium.com/@pavanboro?source=rss-1c0431ac1c8e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YpNUroVrvQ2GXYBHERub_Q.png</url>
            <title>Stories by Pavan Boro on Medium</title>
            <link>https://medium.com/@pavanboro?source=rss-1c0431ac1c8e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:38:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavanboro/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[Pytest Cheat Sheet]]></title>
            <link>https://medium.com/@pavanboro/pytest-cheat-sheet-377964bbfab1?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/377964bbfab1</guid>
            <category><![CDATA[pytest]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 08:42:49 GMT</pubDate>
            <atom:updated>2025-06-08T03:16:50.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python -m pytest VS pytest:</h3><p><strong>python -m pytest</strong> is direct — it uses the exact Python you called, whereas <strong>pytest</strong> is indirect — it runs whatever pytest binary your shell finds.</p><blockquote>💡 <strong>Tips:</strong><br> <strong>CI &amp; Scripts: </strong>use python -m pytest , it locks in exact python version you want.<br><strong>Local Quick runs:</strong> Just type pytest once your venv is active for less typing.<br><strong>No mix-ups:</strong> In environments with multiple Pythons, default to python -m pytest to stay safe.</blockquote><h3>Fixtures:</h3><ul><li>Fixtures provides reusable setup code for multiple tests.</li><li>Use them to <strong>create test data, initialise resource, or configure environment state</strong>.</li><li>The teardown process ( after yield ) ensures proper cleanup.</li></ul><pre>import pytest<br><br>@pytest.fixture<br>def sample_data():<br>  return [1,2,3]<br><br>def test_sum(sample_data):<br>  assert sum(sample_data) == 6<br><br># Setup and Teardown<br>def db_connection():<br>  # Setup: Create connection<br>  conn = create_db_connection()<br>  yield conn # yield is used for pausing the function and return conn obj<br>  <br>  # Teardown: Close connection<br>  conn.close()</pre><h3>Types of Fixtures:</h3><pre>                          Fixtures<br>                             |<br>    ---------------------------------------------------------------<br>    |                     |                     |                 |<br>  1. By Scope           2.By Usage     3.Parameterized Fixtures 4.Setup/Teardown<br>    |                     |                     |                 |<br>function, class,      Explicit,           @pytest.fixture(    setup → yield →<br>module, package,      Autouse             params=[…]         teardown<br>session</pre><pre>1. By Scope:<br>    1. function ( default )<br>        -Runs once per test function<br><br>    2. class<br>        -Runs once per TestClass, shared by all methods in that class<br><br>    3. module<br>        -Runs once per test file(module)<br><br>    4. package<br>        -Runs once per package (dir with __init__.py)  <br><br>    5. session<br>        -Runs once for the entire test session.<br><br>2. By Usage:<br>    1. Explicit:<br>        -You opt in by naming the fixture in your test signature.<br><br>    2. Autouse:<br>        -Mark @pytest.fixture(autouse=True) to have it run for every test(in its scope) without naming it.<br><br>3. Paramterized Fixtures:<br>    - Use @pytest.fixture(params=[..]) to run a test multiple times with different inputs.<br><br>4. Setup/Teardown Fixtures:<br>    - Use yield inside a fixture to separate setup(before yield) from teardown(after yield).<br></pre><pre># test_fixtures_examples.py<br><br>import pytest<br><br># -----------------------------------------------------------------------------<br># 1. By Scope<br># -----------------------------------------------------------------------------<br><br># 1.1 function (default) — Runs once per test function<br>@pytest.fixture<br>def function_fixture():<br>    &quot;&quot;&quot;Function-scoped (default) fixture.&quot;&quot;&quot;<br>    return &quot;function&quot;<br><br># 1.2 class — Runs once per TestClass, shared by all methods in that class<br>@pytest.fixture(scope=&quot;class&quot;)<br>def class_fixture():<br>    &quot;&quot;&quot;Class-scoped fixture.&quot;&quot;&quot;<br>    print(&quot;→ setup class_fixture&quot;)<br>    yield &quot;class&quot;<br>    print(&quot;→ teardown class_fixture&quot;)<br><br># 1.3 module — Runs once per test file (module)<br>@pytest.fixture(scope=&quot;module&quot;)<br>def module_fixture():<br>    &quot;&quot;&quot;Module-scoped fixture.&quot;&quot;&quot;<br>    return &quot;module&quot;<br><br># 1.4 package — Runs once per package (dir with __init__.py)<br>@pytest.fixture(scope=&quot;package&quot;)<br>def package_fixture():<br>    &quot;&quot;&quot;Package-scoped fixture.&quot;&quot;&quot;<br>    return &quot;package&quot;<br><br># 1.5 session — Runs once for the entire test session<br>@pytest.fixture(scope=&quot;session&quot;)<br>def session_fixture():<br>    &quot;&quot;&quot;Session-scoped fixture.&quot;&quot;&quot;<br>    return &quot;session&quot;<br><br>def test_function_scope(function_fixture):<br>    assert function_fixture == &quot;function&quot;<br><br>class TestClassScope:<br>    def test_class_scope_1(self, class_fixture):<br>        assert class_fixture == &quot;class&quot;<br><br>    def test_class_scope_2(self, class_fixture):<br>        assert class_fixture == &quot;class&quot;<br><br>def test_module_scope(module_fixture):<br>    assert module_fixture == &quot;module&quot;<br><br>def test_package_scope(package_fixture):<br>    assert package_fixture == &quot;package&quot;<br><br>def test_session_scope(session_fixture):<br>    assert session_fixture == &quot;session&quot;<br><br><br># -----------------------------------------------------------------------------<br># 2. By Usage<br># -----------------------------------------------------------------------------<br><br># 2.1 Explicit — You opt in by naming the fixture in your test signature<br>def test_explicit(function_fixture):<br>    &quot;&quot;&quot;Explicitly requests function_fixture.&quot;&quot;&quot;<br>    assert function_fixture == &quot;function&quot;<br><br># 2.2 Autouse — Runs for every test (in its scope) without naming it<br>@pytest.fixture(autouse=True)<br>def autouse_fixture():<br>    &quot;&quot;&quot;Autouse fixture: setup → yield → teardown for every test.&quot;&quot;&quot;<br>    print(&quot;\n[autouse setup]&quot;)<br>    yield<br>    print(&quot;\n[autouse teardown]&quot;)<br><br>def test_autouse_effect():<br>    &quot;&quot;&quot;autouse_fixture ran before and after this test automatically.&quot;&quot;&quot;<br>    assert True<br><br><br># -----------------------------------------------------------------------------<br># 3. Parameterized Fixtures<br># -----------------------------------------------------------------------------<br><br>@pytest.fixture(params=[(&quot;a&quot;, 1), (&quot;b&quot;, 2), (&quot;c&quot;, 3)])<br>def param_fixture(request):<br>    &quot;&quot;&quot;Runs the test three times with different params.&quot;&quot;&quot;<br>    return request.param<br><br>def test_parametrized(param_fixture):<br>    key, val = param_fixture<br>    assert isinstance(key, str) and isinstance(val, int)<br><br><br># -----------------------------------------------------------------------------<br># 4. Setup/Teardown Fixtures<br># -----------------------------------------------------------------------------<br><br>@pytest.fixture<br>def setup_teardown_fixture():<br>    &quot;&quot;&quot;Setup before yield; teardown after.&quot;&quot;&quot;<br>    # --- setup code ---<br>    resource = {&quot;status&quot;: &quot;initialized&quot;}<br>    yield resource<br>    # --- teardown code ---<br>    resource[&quot;status&quot;] = &quot;teardown&quot;<br><br>def test_setup_teardown(setup_teardown_fixture):<br>    assert setup_teardown_fixture[&quot;status&quot;] == &quot;initialized&quot;</pre><blockquote><strong>Conftest.py:</strong><br> - This is a file where we can store the fixtures so that we can reuse it in our test suite.</blockquote><h3>Testing for Exceptions:</h3><blockquote>- Verify that your code raises expected exceptions under invalid conditions.<br>- Use pytest.rasises() as a context manager to check exception types and messages.</blockquote><pre>def test_divide_by_zero():<br>    with pytest.raises(ZeroDivsionError):<br>        result = 1/0<br><br>def test_invalid_input():<br>    with pytest.raises(ValueError) as exc_info:<br>        int(&quot;text&quot;)<br>    assert &quot;invalid literal&quot; in str(exc_info)  </pre><h3>Marker:</h3><blockquote>— is a tag or annotation you attach to a test ( or test class/module ) to give pytest extra metadata or change how it runs that tests.<br><strong>Lets you:</strong><br> — <strong>Group Test</strong> into logical categories (eg. smoke, regression, slow)<br> — <strong>Conditionally skip or xfail</strong> tests based on runtime logic<br> — <strong>Parameterize</strong> tests with different data sets<br> — <strong>Control Fixtures</strong> without cluttering every signature</blockquote><p><strong>Running Tests by Marker:</strong></p><pre># Run only smoke tests:<br>pytest -m smoke<br><br># Run smoke and fast tests:<br>pytest -m &quot;smoke and fast&quot;</pre><p><strong>Where and How to Configure Custom Markers:</strong></p><blockquote><strong>File:</strong> pytest.ini in project root.<br><strong>Section:</strong> [pytest] → markers</blockquote><pre>[pytest]<br>markers = <br>  smoke: quick &quot;smoke&quot; sanity checks<br>  regression: full regression suite<br>  slow: tests that take longer than 1s<br>  env(name) : run only on given environment<br>  db: tests requiring database access</pre><pre>@pytest.mark.env(&quot;staging&quot;)<br>def test_feature_on_stagin():<br>    pass<br><br>@pytest.mark.db<br>def test_raw_sql_query():<br>    pass</pre><p><strong>Lets categorise Markers types:</strong></p><pre>Markers Types<br>├── 1. Selection &amp; Grouping<br>├── 2. Parameterization<br>├── 3. Fixture Control<br>├── 4. Skip &amp; XFail</pre><ol><li><strong>Selection &amp; Grouping:</strong><br>- Tag tests so you can pick subsets with -m.<br>- <strong>Use for: </strong>smoke, regression, fast, slow<br><strong>- Run:</strong> pytest -m smoke</li></ol><pre>import pytest<br><br>@pytest.mark.smoke<br>def test_login_fast():<br>  pass<br><br>@pytest.mark.regression<br>def test_checkout_end_to_end():<br>  pass</pre><p><strong>2. Parameterization:</strong><br> - Drive one test through mulitple data sets.<br> - <strong>Syntax:</strong> @pytest.mark.paramterize</p><pre>@pytest.mark.parameterize(&quot;inp, expected&quot;, [<br>  (2,4),<br>  (3,9),<br>  (4,16),<br>)]<br>def test_square(inp, expected):<br>    assert square(inp) == expected</pre><p><strong>3. Fixture Control:</strong><br> - Apply fixtures without naming them in every test.<br> - <strong>Use for</strong>: ensuring setup fixtures run for a group of tests.<br>- <strong>Syntax:</strong> @pytest.mark.usefixtures(&quot;fixture_name&quot;)</p><pre>@pytest.mark.usefixtures(&quot;db_connection&quot;)<br>class TestUserAPI:<br>    def test_create(self):<br>         pass<br><br>    def test_delete(self):<br>         pass</pre><p><strong>4. Skip &amp; XFail:</strong><br> - Mark tests to skip or expect failure.</p><pre># SKIP:<br># ------------------------------------<br>@pytest.mark.skip(reason=&quot;Not ready&quot;)<br>def test_future_feature():<br>    pass<br><br>@pytest.mark.skipif(sys.platform==&quot;win32&quot;, reason=&quot;Unix only&quot;)<br>def test_unix_only():<br>    pass<br><br># XFail(expected failure):<br># ------------------------------------<br>@pytest.mark.xfail(reason=&quot;Bug #123&quot;, strict=True)<br>def test_known_bug():<br>    pass</pre><blockquote>💡 <strong>Test Parameterization Vs Parameterized Fixtures:</strong></blockquote><blockquote>- <strong>Test Parameterization:</strong> Run the same test function with different sets of <strong>inputs</strong>.<br>- <strong>Parameterized Fixtures:</strong> Run a test with different <strong>setups</strong>, provided by a fixture.<br><br> “So its like when we want to <strong>reuse</strong> the test data or setup <strong>across</strong> the test cases then go for parameterized fixture ( @pytest.fixture(params=…) ), else we can opt for @pytest.mark.parameterize(&quot;a,b,expected&quot;,[ (2,2,4), (2,3,5)] for a single test case.”</blockquote><h3>Monkeypatch Vs Mock</h3><blockquote><strong>Monkeypatch</strong> is for patching <em>inside</em> your code (module‐level attributes, environment).<br> <strong>Mock</strong> is a powerful, ready-made fake object. When used with <strong>monkeypatch</strong>, it saves you from writing your own replacement function. Plus, it provides extra features.<br>like automatically records how it was called (number of times, arguments, etc.).</blockquote><pre># Only Monkeypatch<br>import pytest<br>import some_module<br><br>def test_process_data_with_monkeypatch(monkeypatch):<br>    def fake_get_data():<br>        return {&quot;foo&quot;:&quot;bar&quot;, &quot;count&quot;:42}<br>    <br>    # This line will replace this get_data method with fake_get_data method<br>    monkeypatch.setattr(some_module, &quot;get_data&quot; ,fake_get_data)<br>    result = module.process_data()<br>    assert result == {&quot;foo&quot;:&quot;bar&quot;, &quot;count&quot;:42}<br><br><br># Using Mock objects<br># ---------------------<br>import pytest<br>import some_module<br>from unittest.mock import Mock<br><br>def test_greet_with_monkeypatch(monkeypatch):<br>    from module import MyClass<br><br>    mock_greet = Mock(return_value=&quot;Mocked Hello&quot;)<br>    monkeypatch.setattr(MyClass,&quot;some_module&quot;,mock_greet)<br>    obj = MyClass()<br>    assert obj.greet(&quot;Pavan&quot;) == &quot;Mocked Hello&quot;</pre><blockquote>💡 <strong>Tips:</strong><br>- Use <strong>monkeypatch</strong> to inject your replacement.<br>- Use <strong>Mock</strong> if you want advanced control, introspection, or just want to avoid writing a custom fake.</blockquote><h3>Hooks:</h3><blockquote>- These are special functions that pytest calls at specific points in its run lifecycle.<br>- You implement them (usually in conftest.py) to customize collection, setup/teardown, reporting, CLI options, and more without touching pytest’s core.</blockquote><pre>Hooks<br>├── Collection<br>│     ├── pytest_ignore_collect(path, config)          <br>│     │     # Decide to skip collecting certain files/dirs<br>│     ├── pytest_collection_modifyitems(config, items)  <br>│     │     # Reorder, filter, or mark tests after collection<br>│     └── pytest_collect_file(path, parent)             <br>│           # Customize how pytest finds and collects test files<br>│<br>├── Execution<br>│     ├── pytest_runtest_setup(item)                   <br>│     │     # Run code before each test (e.g., reset state or skip)<br>│     ├── pytest_runtest_call(item)                    <br>│     │     # Wrap the actual test call (rarely used)<br>│     └── pytest_runtest_teardown(item, nextitem)      <br>│           # Run cleanup after each test, regardless of outcome<br>│<br>├── Session<br>│     ├── pytest_sessionstart(session)                  <br>│     │     # Execute once at the very start of the test session<br>│     └── pytest_sessionfinish(session, exitstatus)     <br>│           # Execute once at the very end of the test session<br>│<br>├── Reporting<br>│     ├── pytest_runtest_logreport(report)             <br>│     │     # Inspect each test’s setup/call/teardown report<br>│     └── pytest_terminal_summary(terminalreporter, exitstatus, config)<br>│           # Add custom summary or stats after all tests run<br>│<br>└── Configuration<br>      ├── pytest_addoption(parser)                     <br>      │     # Define new command-line options (e.g., --env)<br>      ├── pytest_configure(config)                     <br>      │     # Configure markers or plugin state before tests run<br>      └── pytest_unconfigure(config)                   <br>            # Clean up plugin state before pytest exits</pre><pre># conftest.py<br>import os, pytest, time<br><br># 1) Add a custom CLI option<br>def pytest_addoption(parser):<br>    parser.addoption(&quot;--env&quot;, action=&quot;store&quot;, default=&quot;dev&quot;,<br>                     help=&quot;Which environment to test against&quot;)<br><br># 2) Register its marker<br>def pytest_configure(config):<br>    config.addinivalue_line(&quot;markers&quot;,<br>        &quot;env(name): only run tests for the given environment&quot;)<br><br># 3) Filter tests by --env<br>def pytest_collection_modifyitems(config, items):<br>    selected = config.getoption(&quot;--env&quot;)<br>    skip_marker = pytest.mark.skip(reason=f&quot;not for env={selected}&quot;)<br>    for item in items:<br>        m = item.get_closest_marker(&quot;env&quot;)<br>        if m and m.args[0] != selected:<br>            item.add_marker(skip_marker)<br><br># 4) Setup/teardown around each test<br>@pytest.fixture(autouse=True)<br>def print_start_and_end():<br>    print(f&quot;\n→ STARTING {time.strftime(&#39;%H:%M:%S&#39;)}&quot;)<br>    yield<br>    print(f&quot;\n← FINISHED {time.strftime(&#39;%H:%M:%S&#39;)}&quot;)<br><br># 5) Global session setup/teardown<br>def pytest_sessionstart(session):<br>    print(&quot;\n[SESSION START] Preparing test session…&quot;)<br>    os.environ.setdefault(&quot;DATABASE_URL&quot;, &quot;sqlite:///:memory:&quot;)<br><br>def pytest_sessionfinish(session, exitstatus):<br>    print(&quot;\n[SESSION END] Cleaning up test session…&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377964bbfab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Strategy Design Pattern” Example in Test Automation Framework]]></title>
            <link>https://medium.com/@pavanboro/strategy-design-pattern-example-in-test-automation-framework-0c91adb65c4b?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c91adb65c4b</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[desgin-patterns]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[testing-framework]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 06:05:54 GMT</pubDate>
            <atom:updated>2024-11-19T06:05:54.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategy Design Pattern:</h3><p>The Strategy Design Pattern is a behavioral design pattern that allows the behavior of a class instance to be changed dynamically.</p><p><strong>When to use it?</strong><br>This pattern is useful when there are multiple ways or strategies to perform a task, and you want to switch between these strategies at runtime.</p><p><strong>Example:</strong><br>Consider a toolbox containing various tools. When repairing a car, you have several tools (or strategies) at your disposal to complete the repair. The Strategy Design Pattern allows you to choose the appropriate tool for the task at hand, enabling flexibility and adaptability in your approach.</p><h3>Now lets dive into Test Automation Framework how do we use Strategy Design Pattern:</h3><p><strong>Designing the Strategy Design pattern has 4 steps:<br></strong>Now, imagine a scenario where we are developing test scripts to validate API responses. For this task, we can employ multiple strategies, such as validating for a valid response or checking for an invalid response.</p><p>Lets implement it.</p><p><strong>Step 1:</strong> Defining strategy interface in validation_strategy.py</p><pre>class ValidationStrategy:<br>    def validate(self, response):<br>        pass</pre><p><strong>Step 2:</strong> Implement Concrete Strategy Class strategy_assertion.py</p><pre>from validation_strategy import ValidationStrategy<br><br>class ValidResponseStrategy(ValidationStrategy):<br>  def validate(self, response):<br>      expected_status_code = 200<br>      assert response.status_code == expected_status_code, (<br>          f&quot;Expected status code {expected_status_code}, but got {response.status_code}&quot;<br>      )<br><br>class InvalidResponseStrategy(ValidationStrategy):<br>  def validate(self, response):<br>      invalid_status_codes = {400, 404, 500}  # Example set of invalid status codes<br>      assert response.status_code not in invalid_status_codes, (<br>          f&quot;Did not expect status code {response.status_code}, which is considered invalid&quot;<br>      )</pre><p><strong>Step 3:</strong> Create Context Class response_validator_context.py</p><pre>from strategy_assertion import ValidResponseStrategy, InvalidResponseStrategy<br><br>class ResponseValidatorContext:<br>  def __init__(self, strategy: ValidationStrategy):<br>    self.strategy = strategy<br><br>  def set_strategy(self, strategy: ValidationStrategy):<br>    &quot;&quot;&quot;Allows changing the strategy at runtime.&quot;&quot;&quot;<br>      self._strategy = strategy<br><br>  def validate_response(self, response):<br>    &quot;&quot;&quot;Delegates the validation to the current strategy.&quot;&quot;&quot;<br>      self._strategy.validate(response)</pre><p><strong>Step 4:</strong> Utilize the Strategy Design Pattern main.py</p><pre># Assuming `response` is an object with a `status_code` attribute<br>response = type(&#39;Response&#39;, (object,), {&#39;status_code&#39;: 200})()<br><br># Using ValidResponseStrategy<br>valid_strategy = ValidResponseStrategy()<br>context = ResponseValidatorContext(valid_strategy)<br>context.validate_response(response)<br><br># Switching to InvalidResponseStrategy<br>invalid_strategy = InvalidResponseStrategy()<br>context.set_strategy(invalid_strategy)<br>context.validate_response(response)</pre><p>This setup demonstrates how the Strategy Design Pattern can be used to manage different validation strategies within a test automation framework, providing flexibility and adaptability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c91adb65c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Desing Principles]]></title>
            <link>https://medium.com/@pavanboro/solid-desing-principles-2b7b2ee92d85?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7b2ee92d85</guid>
            <category><![CDATA[solid-design-principles]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 06:54:36 GMT</pubDate>
            <atom:updated>2022-06-17T19:15:43.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUi3_ZDzHCnrpEsA9JLuig.png" /><figcaption>SOLID Design Principles</figcaption></figure><h3><strong>1. Single Responsibility:</strong></h3><blockquote>Every Class, Interface or Methods should have only <strong>Single Responsibility</strong>.</blockquote><h4><strong>Ex:</strong></h4><pre>// Without Single Responsibility:<br>interface IReport{<br>      void addEntryAt(int index);<br>      void removeEntryAt(int index);<br>      void saveToFile(string directoryPath, string fileName);      <br>} </pre><p>From the above code, we can see that the IReport interface has 2 responsibilities.<br> 1. Adding or Removing <br>2. Saving to some file</p><pre>//With Single Responsibility:</pre><pre>interface IReport{<br>    void addEntryAt(int index);<br>    void removeEntryAt(int index);<br>}</pre><pre>interface IReportSaver{<br>    void saveToFile(string directoryPath, string fileName);<br>}</pre><p><strong>Note:<br></strong><em>Here we should focus on </em><strong><em>OR</em></strong><em> i.e it can contain Adding </em><strong><em>OR</em></strong><em> Removing<br>We should avoid </em><strong><em>AND</em></strong><em> here i.e Adding or Removing </em><strong><em>AND</em></strong><em> Saving.<br>Anytime we are able to see AND then it means we have more than one responsibility.</em></p><h3>2. Open-Closed Principle:</h3><blockquote><strong>Open</strong> for <strong>Extension</strong>.<br><strong>Closed</strong> for <strong>Modification</strong>.<br><strong>i.e</strong> You should put new code in New Classes/Modules or Reuse existing code via Inheritance.<br>Existing code should be modified only for Bug fixing.</blockquote><h4><strong>Ex:</strong></h4><pre>// Without Open-Closed Principle<br>class Operation{<br>      double calculate(doulbe a1, double a2, string operationType){<br>            switch(operationType){<br>                 case &quot;+&quot;:<br>                      return a1 + a2;<br>                 case &quot;-&quot;:<br>                      return a1 - a2;<br>                 default:<br>                      // Throw some exceptions<br>             }<br>             return 0;<br>       }<br>}   </pre><p><strong>Note:</strong><br> From the above code, if you want to add the division operation in the calculate method you need to modify the class Operation.</p><pre>// With Open-Closed Principle<br>interface Operation{<br>       double calculate(double a1, double a2);<br>}</pre><pre>class AddOperation implements Operation{<br>      double calculate(double a1, double a2){<br>             return a1 + a2;<br>      }<br>}</pre><pre>class DivisionOperation implements Operation{<br>      double calculate(double a1, double a2){<br>             return a1/a2;<br>      }<br>} </pre><p><strong>Note:</strong><br> From the above code, If we want the Division operation, we just simply implement the DivisionOperation class when required.</p><h3>3. Liskov Substitution Principle:</h3><blockquote>It states that the <strong>Parent Object</strong> should be <strong>replacable</strong> by the <strong>Child Object</strong>.</blockquote><p>In order to obey this law, the <strong>Child class</strong> should support all methods of <strong>Parents class</strong>.</p><p><strong>Ex:</strong></p><pre>interface SmartTV{<br>       String getOTTAppList();<br>       String getWifiConnectedStatus();<br>       String getDisplayResolution();<br>}</pre><pre>class LG_TV_Android implements SmartTV{<br>       String getOTTAppList(){<br>              return &quot;Youtube, Prime , Netflix, voot &quot;;<br>       }<br>     <br>       String  getWifiConnectedStatus(){<br>              return &quot;Not Connected&quot;;<br>       }</pre><pre>       String getDisplayResolution(){<br>              return &quot;Full HD 1920x1080&quot;;<br>       }<br>}</pre><pre>// Here comes the Child class which cannot replace the Parent Class<br>// or object<br>class ONIDA_TV implements SmartTV {<br>       String getOTTAppList(){<br>             throw new NotImplementedException();<br>       }</pre><pre>       String getWifiConnectedStatus(){<br>             throw new NotImplementedException();<br>       }</pre><pre>       String getDisplayResolution(){<br>             return &quot;Standard Resolution&quot;;<br>       }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVyvJpiRTiRwucuESxtITw.png" /></figure><h3>4. Interface Segregation Principle:</h3><blockquote>“ Clients should not be forced to depend upon interfaces that they do not use.”</blockquote><blockquote>The principle states that many client-specific interfaces are better than one general-purpose interface.</blockquote><blockquote>“Clients should not be forced to implement a function they do no need.”</blockquote><p><strong>Ex:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWx0arLY0662jqRVjE9AeQ.png" /><figcaption>C# code</figcaption></figure><h3>5. Dependency Inversion Principle:</h3><blockquote>“Our class should depend upon <strong>interfaces</strong> or <strong>abstract classes</strong> instead of <strong>Concrete class</strong> and functions.”</blockquote><p><strong>Note:<br>Concrete Class:</strong> is a class that has an implementation for all of its methods.</p><p><strong>Ex:</strong></p><pre>// <strong>Without Dependency Inversion:</strong></pre><pre>class Desktop {<br>      private Monitor monitor;<br>      private QwertyKeyBoard keyboard;</pre><pre>      public Desktop(){<br>           this.monitor = new Monitor();<br>           this.keyboard = new QwertyKeyBoard();<br>      }<br>}</pre><pre>class Monitor{}<br>class QwertyKeyBoard{}</pre><p><strong>Note:</strong><br>From above code, The <strong>Desktop class</strong> is tightly coupled with <strong>Monitor class</strong> and <strong>QwertyKeyBoard</strong> <strong>class</strong>.</p><p><strong>Now with Dependency Inversion: ( Also called Dependency Injection )<br></strong>We just pass the <strong>instance</strong> of the <strong>Monitor object</strong> and <strong>QwertyKeyBoard</strong>.<br>This is also called <strong>Dependency Injection through Constructor.</strong></p><pre>class Desktop{</pre><pre>     private Monitor monitor;<br>     private QwertyKeyBoard keyboard;<br>    <br>     public Desktop(Monitor monitor, QwertyKeyboard keyboard){<br>            this.monitor = monitor;<br>            this.keyboard = keyboard;<br>     }<br>}  </pre><p><strong>Now to Make more Generic:<br></strong>Suppose if I have different types of keyboard other than QwertyKeyBoard.<br>Then we can create interface Keyboard.<br>This is the more Abstract way of creating.</p><pre>class Desktop{</pre><pre>     private Monitor monitor;<br>     private Keyboard keyboard;<br>    <br>     public Desktop(Monitor monitor, Keyboard keyboard){<br>            this.monitor = monitor;<br>            this.keyboard = keyboard;<br>     }<br>}</pre><pre>interface Keyboard{}<br>class Monitor{}<br>class QwertyKeyboard implements Keyboard{}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7b2ee92d85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Every Student should attend Hackathon?]]></title>
            <link>https://medium.com/@pavanboro/why-every-student-should-attend-hackathon-d10317c2e1d2?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10317c2e1d2</guid>
            <category><![CDATA[hackathons]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Sun, 02 Dec 2018 09:57:17 GMT</pubDate>
            <atom:updated>2018-12-02T09:57:17.973Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll be presenting my previous experience with Hackathon. And I hope, at the end of this article, you’ll get inspired to attend at least one hackathon in your 4 years of Bachelor’s degree.</p><p>In the past, I have attended several hackathons like Angel Hack at Microsoft campus, Google, IIIT-H, NIT-C. My last hackathon was at IIIT-Hyderabad where I have built an Academic advisor chatbot. It is a chatbot that helps 10+2 student to choose the best course.</p><p>So let’s make clear what actually a ‘Hackathon’ is?</p><p>Could you have a guess?</p><p>hmmmmm……… Is it related to something like hacking facebook account, WhatsApp account or stealing Ambani’s bank balance?</p><p>Not really! If you had thought that hackathon is related to hacking, it’s not your mistake. Your not the only one who got it wrong. I have met many people at hackathon who thought that it was hacking contest. So the question is if it is not hacking then what is it? <br>Okay! Now here’s the answer to the question — A hackathon is an event where people gather to create an innovative solution to the real world problem. <br>So it’s clear that Hackathon is not only about Software it’s about solving the real world problem.</p><p>Now I’ll be describing my hackathon experience at Angel Hack, Microsoft Office.</p><p>At the beginning of the event, it is a time that where I can introduce myself to people and connect with them.<br> So soon after the hackathon begun at 11:00 AM. We started thinking of the problem to solve. We thought of creating an online platform for all the offline shopkeepers basically a web app. This solves the problem of user like me who are not aware of the things like where can I get the “Head First Android ” book in Hyderabad. So instead of traveling and searching for the book every shop near you, there would be a chance that you may miss a shop where that book is available. So what we have done is created an app which looks for the book in every shop and notifies you. Isn’t that Amazon, Flipkart, Snapdeal enough to get things? Yeah! They are. But if you’re like me who wants to read and touch the book and then purchase it, then I would love to know which shop it is available at, also I’m impatient I don’t want to wait for 1,2,3 or 6 Days for the delivery of the product. <br>“If I know it where to get then I buy it.”</p><p>So that’s done with the idea part now it starts the real part the building or developing part. We were the team of 4 with each divided with roles — Presenter, Designer, Developer, Deployer.</p><p>The advantage of the hackathon is that I’m free to get any expert help from the experts. Also, this is the chance to impress the employer and boost up your career by their advice. Also if you want, you could ask them how to get into their company. It is easy to get into the company by referral than to submit an online application for the job.</p><p>So lastly at the end of the hackathon, you could hear to real innovative solutions to the problem where you can learn a lot from other smart geeks.</p><p>In summary, I have put the benefits of attending a hackathon below.<br>1. Meet a lot of like-minded people<br>2. Get to an experience of project deadline time.<br>3. Connect with Employees, get a chance to get some insight about the company.<br>4. Get to learn innovative solutions to a problem<br>5. An epicentre for next billion dollar company.<br>6. Learn something new.<br>7. Have Fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10317c2e1d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on Machine Learning — 1]]></title>
            <link>https://medium.com/@pavanboro/notes-on-machine-learning-1-4b987d8418d9?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b987d8418d9</guid>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Tue, 30 May 2017 11:37:52 GMT</pubDate>
            <atom:updated>2017-05-30T12:40:17.513Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes taken from <a href="https://www.coursera.org/learn/machine-learning">Machine Learning course by Andrew Ng on Coursera.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5y-MqiYKmizFhdI-x8peaw.jpeg" /></figure><h3>Week — 1</h3><p><strong>Definition of Machine Learning:</strong></p><p>There are two definition of ML given by Arthur Samuel (1959) and Tom Mitchell (1998).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Y-owTpLhq52rbRhqXXzJcw.png" /></figure><p>Well the definition by Arthur Samuel is quite self explanatory.</p><p>Now, lets look at What Tom Mitchell mean by that.</p><p>Here’s the simple diagram I have depicted to shorten the definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfIEquAlwxSOcJhy7en57w.png" /></figure><p>So based on previous experience there is increase in the performance of the task.</p><p><strong>Example of Machine Learning:</strong></p><ol><li>Classifying emails as Spam or not Span — — — (Task)</li><li>Watching you label emails as spam or not spam — — (Experience)</li><li>The number of emails correctly classified as Spam/not Spam — — (Performance)</li></ol><p><strong>Machine Learning can be classified as:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNcf9LQT-wsk8b-JjMTsuQ.png" /></figure><h3><strong>Supervised Learning:</strong></h3><p>In this we are given a data set and already know what correct output should look like.</p><p>There exist a relationship between output and input.</p><p>Supervised Learning Categorised into 2:</p><ol><li><strong><em>Regression:</em></strong></li></ol><p>In this we are trying to predict within a continuous output.</p><p>Ex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*jxI09l4BA5dsPwMeT2lt-g.png" /><figcaption>Housing Price Prediction</figcaption></figure><p><strong><em>2. Classification :<br></em></strong>Here we are trying to predict results in discrete output<br>Ex: <br>Given a patient with tumour.<br>Predict whether tumour is <strong>malignant</strong> or <strong>benign</strong>.</p><h3><strong>UnSupervised Learning:</strong></h3><p>This allows us to approach problems with little or no idea what our results should look like.</p><p>We can derive the structure or pattern by <strong>clustering</strong> the data based on relationships among the variables in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*i672HCMHHfxUWSe-umNaoQ.png" /><figcaption>UnSupervised Learning — Clustering</figcaption></figure><p>Ex:</p><p><strong>Clustering:</strong></p><p>Given, 1,000,000 different genes.<br>Grouping them into clusters.</p><p><strong>Non-Clustering:</strong></p><p>“Cocktail Party Algorithm” allows find the structure in chaotic environment.<br>So basically separate the higher sound from lower sound.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b987d8418d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Programming Resource]]></title>
            <link>https://medium.com/@pavanboro/my-programming-resource-8b4b7a49d3c8?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4b7a49d3c8</guid>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Sun, 23 Apr 2017 16:40:52 GMT</pubDate>
            <atom:updated>2017-05-16T02:32:52.662Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>HTML &amp; CSS Validator:</strong></h3><ul><li><a href="https://validator.w3.org/#validate_by_input">Markup Validation Service</a></li><li><a href="https://jigsaw.w3.org/css-validator/#validate_by_input">The W3C CSS Validation Service</a></li></ul><h3><strong>HTML:</strong></h3><ol><li><a href="https://www.w3schools.com/html/default.asp">HTML reference</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5">HTML5 reference</a></li></ol><p><strong><em>Stuff learnt:</em></strong></p><p><a href="https://www.freecodecamp.com/challenges/create-a-form-element"><strong><em>Forms</em></strong></a></p><pre>&lt;form action=&quot;/url-where-you-want-to-submit-form-data&quot;&gt;<br>&lt;/form&gt;</pre><p><a href="https://www.w3schools.com/css/css_rwd_viewport.asp"><strong><em>To make page responsive:</em></strong></a></p><pre>&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;</pre><p><strong><em>Importing google fonts:</em></strong></p><p>try importing google fonts: <a href="https://www.freecodecamp.com/challenges/import-a-google-font">https://www.freecodecamp.com/challenges/import-a-google-font</a></p><p>Get the links for google fonts: <a href="https://fonts.google.com/">https://fonts.google.com/</a></p><p><strong>Degrading the font:</strong></p><p>When any font is not available we should have other option.</p><p>So by separating it with commas.</p><p>Ex:</p><pre>font-family: Lobster, Monospace;</pre><h3><strong>CSS:</strong></h3><ol><li><a href="https://www.w3schools.com/css/default.asp">CSS</a></li><li><a href="http://cssreference.io/">Visual CSS ref</a></li></ol><p><strong><em>Blog:</em></strong></p><p>i. <a href="https://css-tricks.com/guides/">https://css-tricks.com/guides/</a></p><p><strong><em>Stuff learnt:</em></strong></p><p><strong><em>Import external CSS in html:</em></strong></p><pre>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;myStyle.css&quot; /&gt;</pre><p><strong><em>Centering Things: </em></strong><a href="https://www.w3.org/Style/Examples/007/center.en.html#block">https://www.w3.org/Style/Examples/007/center.en.html#block</a></p><p><a href="http://tutorial.techaltum.com/cssboxmodel.html">Border Vs Margin Vs Padding</a></p><p><strong><em>Flexbox:</em></strong></p><p><a href="http://spaceninja.com/2015/08/24/what-is-flexbox/">What is Flexbox?</a></p><p>Flexbox is a layout mode added in CSS3 to replace hacky float and table layouts. It comes with a clever set of defaults that make it easy to create complex layouts with relatively little code. It’s stable, easy-to-use, and well-supported.</p><p><a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/#flexbox-basics">A complete guide to Flexbox.</a></p><h3><strong>jQuery:</strong></h3><p><a href="https://www.w3schools.com/jquery/default.asp"><strong><em>jQuery learn:</em></strong></a></p><p><a href="http://api.jquery.com/">jQuery ref:</a></p><p><strong><em>Stuff learnt:</em></strong></p><p><strong>Making ajax call:</strong></p><p>Best example at U<a href="https://www.youtube.com/watch?time_continue=1&amp;v=P7S7_0Z2YPk">dacity</a>:</p><pre>var nytimesUrl = &#39;<a href="https://nytimes.com/svc/search/v2/articlesearch.json?=&#39;">https://nytimes.com/svc/search/v2/articlesearch.json?=&#39;</a> + city + &#39;&amp;sort=newest&amp;api-key=758718ccf8e3493585e97f37d5b22c28&#39;;</pre><pre>$.getJSON(nytimesUrl, function(data){<br>          $nytHeaderElem.text(&#39;New York Times Articles About&#39;+city);<br>          <br>          articles = data.response.docs;<br>          for(var i = 0; i &lt; articles.length; i++) {<br>            var article = articles[i];<br>              $nytElem.append(&#39;&lt;li class=&quot;article&quot;&gt;&#39;+<br>                             &#39;&lt;a href=&quot;&#39;+article.web_url+&#39;&quot;&gt;&#39;+article.headline.main+&#39;&lt;/a&gt;&#39;+<br>                             &#39;&lt;p&gt;&#39;+ article.snippet + &#39;&lt;/p&gt;&#39;+ &#39;&lt;/li&gt;&#39;);<br>          }<br>      })</pre><h3><strong>API:</strong></h3><p>What is CORS?</p><p><a href="https://www.youtube.com/watch?time_continue=156&amp;v=pYjX1icSNws"><strong><em>wikipedia api:</em></strong></a></p><p><a href="https://www.youtube.com/watch?time_continue=156&amp;v=pYjX1icSNws">Tutorial</a></p><p><a href="https://www.mediawiki.org/wiki/Category:MediaWiki_action_API">Links to various wiki api</a></p><h3><strong>Git &amp; Github:</strong></h3><pre>git init<br>git add README.md<br>git commit -m &quot;first commit&quot;<br>git remote add origin https://github.com/boro741/HeadLine.git<br>git push -u origin master</pre><h3><strong>Python:</strong></h3><p><strong>My Doubts:</strong></p><p><a href="https://www.codecademy.com/en/forum_questions/505ba3cfc6addb000200e33c"><strong>Multiline comments don’t actually exist in Python:</strong></a></p><p>Triple quotes are treated as regular strings with the exception that they can span multiple lines. By regular strings I mean that if they are not assigned to a variable they will be immediately garbage collected as soon as that code executes. hence are <strong>not ignored</strong> by the interpreter in the same way that #a comment is.</p><h3><a href="https://blog.httpwatch.com/2011/03/01/6-things-you-should-know-about-fragment-urls/#page"><strong>What is Fragment url?</strong></a></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtLRF7fI4CdA%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtLRF7fI4CdA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtLRF7fI4CdA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d77db1e9f518d7c6b69458bfff91e3/href">https://medium.com/media/62d77db1e9f518d7c6b69458bfff91e3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4b7a49d3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API]]></title>
            <link>https://medium.com/@pavanboro/rest-api-c8c4b15b6935?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c4b15b6935</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Mon, 03 Apr 2017 16:28:19 GMT</pubDate>
            <atom:updated>2017-04-05T18:34:29.375Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes taken from <a href="https://www.youtube.com/playlist?list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp">The Net Ninja</a> .</p><p>Contents:</p><ol><li>What is a REST API?</li><li>Setting Up</li><li>HTTP Methods</li><li>Creating an Express App</li><li>Handling Requests</li><li>Creating Routes</li><li>Postman</li><li>Handling POST Requests &amp; middleware</li><li>Models &amp; Schemas</li><li>Saving Data to MongoDB</li><li>Error Handling</li><li>Handling DELETE Requests</li><li>PUT Requests</li><li>GeoJSON</li><li>GET Requests</li><li>Creating a Front-end</li><li>Creating a React Component</li></ol><h3><strong>What is a REST API?</strong></h3><p><strong><em>API: </em></strong>Application Programming Interface</p><p>So what actually is it?</p><p>Let’s have a look at real world example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*hDDCqdCBhh-nfB6nDMY52g.png" /><figcaption>Application HUMAN Interface</figcaption></figure><p>Here remote is an interface for the TV.</p><p>And we the human use the remote to control the TV.</p><p>So this model is called Application HUMAN Interface.</p><p>In the similar manner we have a interface i.e endpoints(remote) and program(Human) interact or use resource of application (TV) through those endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*NscDlKpMMWO9e6Oprgxhzg.png" /><figcaption>Application Programming Interface</figcaption></figure><p><strong>REST:</strong> Representational State Transfer</p><p>It is a standard/set of guidelines by which we can structure and create API’s</p><p>REST make use of resource base URL.</p><p>Ex:</p><p>Webpage — <a href="http://www.football.com/scores">http://www.football.com/scores</a></p><p>JSON — <a href="http://www.football.com/api/scores">http://www.football.com/api/scores</a></p><p><strong>REST properties:</strong></p><p>They make use of HTTP methods:</p><ul><li>GET — retrieve data from server</li><li>POST — send data to the server</li><li>PUT — update data</li><li>DELETE — delete data</li></ul><p>HTTP status codes:</p><ul><li>200 — OK</li><li>404 — resource not found</li><li>500 — server error</li><li>422 — Unprocessable entity ( request was well formed but was unable to be followed due to semantic errors.)</li></ul><h3><strong>2. Setting up :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*TG45joLAOhhk10QFyzhTJg.png" /><figcaption>Our Setup</figcaption></figure><h3><strong>3. HTTP Methods:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*b8rY6DvPTxisMMCYayRryA.png" /><figcaption>API Routes</figcaption></figure><pre>// Example using jQuery</pre><pre>$.ajax({<br> method: &quot;POST&quot;,<br> url: &quot;http://www.ninjago.com/api/ninjas&quot;,<br> data: {name: &quot;Ganash&quot;,rank:&quot;Red Belt&quot;<br>})</pre><pre>$.ajax({<br> method: &quot;GET&quot;,<br> url: &quot;http://www.ninjago.com/api/ninjas&quot;,<br>})</pre><h3><strong>4. Creating Express app:</strong></h3><pre>const express = require(&#39;express&#39;);</pre><pre>// set up express app<br>const app = express();</pre><pre>// listen for requests<br>app.listen(process.env.port || 4000, function(){<br>    console.log(&#39;now listening for requests&#39;);<br>});</pre><h3><strong>5. Handling Request:</strong></h3><pre>const express = require(&#39;express&#39;);<br><br>// set up express app<br>const app = express();<br><br>app.get(&#39;/api&#39;, function(req, res){<br>  res.send({ name: &#39;Yoshi&#39; });<br>});<br><br>// listen for requests<br>app.listen(process.env.port || 4000, function(){<br>    console.log(&#39;now listening for requests&#39;);<br>});</pre><h3><strong>6. Creating Routes:</strong></h3><p><strong>Routing: </strong>It refers to the application endpoint(URL) and how they respond to the client request.</p><p>Ex:</p><pre>app.get(&#39;/ninjas&#39;, function(req, res){<br>  res.send({type: &#39;GET&#39;});<br>});</pre><p><strong>Why do we need to route?</strong></p><p>To make our code clean and modular we use route.</p><p>Instead of writing all the routing code like app.get , app.post methods in the index file we create a route and write all our routing code.</p><p>// index.js</p><pre>const express = require(&#39;express&#39;);<br>const routes = require(&#39;./routes/api&#39;);<br>// set up express app<br>const app = express();</pre><pre>// initialize routes<br>app.use(&#39;/api&#39;, routes);<br>//routes.initialize(app);</pre><pre>// listen for requests<br>app.listen(process.env.port || 4000, function(){<br>    console.log(&#39;now listening for requests&#39;);<br>});</pre><p>// routes/api.js</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();</pre><pre>// get a list of ninjas from db<br>router.get(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;GET&#39;});<br>});</pre><pre>router.post(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;POST&#39;});<br>});</pre><pre>router.put(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;PUT&#39;});<br>});</pre><pre>router.delete(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;DELETE&#39;});<br>});</pre><pre>module.exports = router;</pre><p>For <a href="http://jilles.me/express-routing-the-beginners-guide/">detailed explanation click.</a></p><h3><strong>8. Handling POST Request and Middleware:</strong></h3><p><strong>Middleware:</strong></p><p>Any code that is fired between the request that is coming in and response going out is called Middleware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*FYmjTuIFxZnT35ZOpMXRog.png" /><figcaption>Middleware</figcaption></figure><p>If we wanna use multiple middleware:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*F43lfNWfjmM2WcSO2pVG8g.png" /><figcaption>Multiple Middleware</figcaption></figure><p>If we wanna use <strong>body-parser</strong> :</p><p>So what is <strong>body-parser</strong>?</p><p>When the request is passed the body-parser is going to look at the body of the request , take it, parse it and attach it to the request object.</p><p>We gonna use body-parser at top of the middleware:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*bY8bA6_Ye2Ty-h0fVz52tw.png" /><figcaption>using body-parser</figcaption></figure><h3><strong>9. Models and Schemas:</strong></h3><p><strong>Models:</strong></p><p>It represents collections in MongoDB.</p><p>Ex:</p><p>User model to represent a collection of Users.</p><p>Ninja contains the collections of ninjas.</p><p><strong>Schemas:</strong></p><p>It defines the structure of our data objects.</p><p>Ex:</p><pre>{<br>  name: String,<br>  rank : String,<br>  availability: boolean<br>}</pre><p>Ex of model and Schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*eEXKdxEOlLX6SuCuRsflKg.png" /><figcaption>Collection of Objects</figcaption></figure><p><a href="http://mongoosejs.com/"><strong>Mongoose:</strong></a></p><p>Allows us to create our Models and Schemas easily.</p><p>Adds a layer of methods to easily save, edit, retrieve and delete data from mongoDB.</p><p>Ex:</p><pre>// models/ninja.js</pre><pre>const mongoose = require(&#39;mongoose&#39;);<br>const Schema = mongoose.Schema;</pre><pre>// Create ninja Schema and Model<br>const NinjaSchema = new Schema({<br>  name: {<br>    type: String,<br>    required: [true, &#39;Name field is required&#39;]<br>  },<br>  rank : {<br>    type: String<br>  },<br>  available: {<br>    type: boolean,<br>    default: false<br>  }</pre><pre>// Add in Geo Location<br>});</pre><pre>// Ninja is name of our model<br>// ninja is name of our collection in db<br>// so mongoose gonna create ninjas for us or plularise ninja<br>// Above image shows the example.</pre><pre>const Ninja = mongoose.model(&#39;ninja&#39;, NinjaSchema);</pre><pre>module.exports = Ninja;</pre><h3><strong>10. Saving Data to MongoDB:</strong></h3><p>connecting to mongoDB:</p><pre>//index.js</pre><pre>const express = require(&#39;express&#39;);<br>const routes = require(&#39;./route/api&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const mongoose = require(&#39;mongoose&#39;);</pre><pre>// Setting up express app<br>const app = express();</pre><pre>// Connect to MongoDB<br>mongoose.connect(&#39;mongodb://localhost/ninjago&#39;);<br>mongoose.Promise = global.Promise;</pre><pre>// Middlewares</pre><pre>app.use(bodyParser.json());<br>// Initialize routes<br>app.use(&#39;/api&#39;,routes);</pre><pre>// Listen for request<br>app.get(&#39;/api&#39;, function(req,res){<br>  res.send({name: &#39;Yash&#39;});<br>});</pre><pre>app.listen(process.env.port || 4000, function() {<br>  console.log(&#39;now listening for request&#39;);<br>});</pre><p>// route/api.js</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const Ninja = require(&#39;../models/ninja&#39;);</pre><pre>// Get a list of ninjas from the db<br>router.get(&#39;/ninjas&#39;, function(req, res){<br>  res.send({type: &#39;GET&#39;});<br>});</pre><pre>// add a new ninja to the dataBase<br>router.post(&#39;/ninjas&#39;, function(req,res){<br>  Ninja.create(req.body).then(function(ninja){<br>    res.send(ninja);<br>  });</pre><pre>});</pre><pre>router.put(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;PUT&#39;});<br>});</pre><pre>router.delete(&#39;/ninjas&#39;, function(req,res){<br>  res.send({type: &#39;DELETE&#39;});<br>});</pre><pre>module.exports = router;</pre><p><strong>Now running mongoDB:</strong></p><p>If you are on a mac and getting error then try with</p><pre>sudo ./mongod</pre><p><a href="https://robomongo.org/"><strong>Robomongo:</strong></a></p><p>It is an piece of software used for visual representation of database.</p><p>Install <a href="https://robomongo.org/">Robomongo</a> .</p><p><strong>Experiment:</strong></p><pre>const Ninja = mongoose.model(‘ninja’, NinjaSchema);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*JnFU5e13eTdzFzatdEYttw.png" /><figcaption>ninja model</figcaption></figure><p>So when I changed the above code to something like this</p><pre>const Ninja = mongoose.model(‘ja’, NinjaSchema);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*bmpz9Aiqd9dCL9RiXB3MRQ.png" /><figcaption>ja model</figcaption></figure><h3><strong>11. Error Handling:</strong></h3><p>we gonna use a middleware for Error Handling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*moB1cYk62MiEZjc9Ozxr5g.png" /><figcaption>Error Handling</figcaption></figure><p>So what is meant by <strong>next</strong> ?</p><p>It mean go to next middleware.</p><p><strong>Error Handling middleware:</strong></p><pre>// Error Handling Middleware<br>app.use(function(err, req, res, next){<br>  res.status(422).send({error: err.message});<br>});</pre><h3><strong>12. Handline DELETE request:</strong></h3><p>// routes/api.js</p><pre>router.delete(&#39;/ninjas/:id&#39;, function(req,res,next){<br>  Ninja.findByIdAndRemove({_id:req.params.id}).then(function(ninja){<br>    res.send(ninja);<br>  }).catch(next);<br>});</pre><h3><strong>13. PUT request: (update request)</strong></h3><p>// routes/api.js</p><pre>router.put(&#39;/ninjas/:id&#39;, function(req,res,next){<br>  Ninja.findByIdAndUpdate({_id: req.params.id}, req.body).then(function(){<br>    Ninja.findOne({_id: req.params.id}).then(function(ninja){<br>      res.send(ninja);<br>    });<br>  }).catch(next);<br>});</pre><h3><strong>14. </strong><a href="http://geojson.org/"><strong>GeoJSON</strong></a><strong>:</strong></h3><p>// models/ninja.js</p><pre>// Create geolocation Schema<br>const GeoSchema = new Schema({<br>  type: {<br>    type: String,<br>    default: &quot;Point&quot;<br>  },<br>  coordinates: {<br>    type: [Number],<br>    index: &quot;2dsphere&quot;<br>  }<br>});<br>// Create ninja Schema and Model<br>const NinjaSchema = new Schema({<br>  name: {<br>    type: String,<br>    required: [true, &#39;Name filed is required&#39;]<br>  },<br>  rank: {<br>    type: String<br>  },<br>  available: {<br>    type: Boolean,<br>    default: false<br>  },<br>  // Add in Geo Location<br>  Geometry: GeoSchema<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*GMGQWKkMnSdB4674zOTopg.png" /><figcaption>2d Vs 2d Sphere</figcaption></figure><h3><strong>15. GET request:</strong></h3><p>URL parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*U-3q7pk0SFQJ8V1lnso81A.png" /><figcaption>URL parameter</figcaption></figure><p>// routes/api.js</p><pre>router.get(&#39;/ninjas&#39;, function(req, res, next){<br>    Ninja.geoNear(<br>        {type: &#39;Point&#39;, coordinates: [parseFloat(req.query.lng), parseFloat(req.query.lat)]},<br>        {maxDistance: 100000, spherical: true}<br>    ).then(function(ninjas){<br>        res.send(ninjas);<br>    }).catch(next);<br>});</pre><h3><strong>16.Creating a Front-end:</strong></h3><pre>app.use(express.static(&#39;public&#39;));</pre><h3><strong>17. Creating a React Component:</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c4b15b6935" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Emitter]]></title>
            <link>https://medium.com/@pavanboro/event-emitter-deda2ef78031?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/deda2ef78031</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Sat, 01 Apr 2017 09:57:07 GMT</pubDate>
            <atom:updated>2017-04-01T10:34:56.996Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes taken from <a href="https://www.youtube.com/playlist?list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp">The Net Ninja</a> .</p><p>Modules to import:</p><ol><li>events</li><li>util — used for inheriting</li></ol><p><strong>Event on and Emit :</strong></p><p>syntax:</p><pre>// On<br>element.on(&#39;someEvent&#39;, function() { <br>     // do something when event <br>     // is triggered<br>});</pre><pre>// Emit<br>element.emit(&#39;someEvent&#39;, pass in something to the function);</pre><p>Ex:</p><pre>var events = require(&#39;events&#39;);</pre><pre>var myEmitter = new events.EventEmitter();</pre><pre>myEmitter.on(&#39;someEvent&#39;, function(mssg){<br>  console.log(mssg);<br>});</pre><pre>myEmitter.emit(&#39;someEvent&#39;, &#39;the event was emitter&#39;);</pre><p>sample app Ex:</p><pre>var events = require(&#39;events&#39;);<br>var util = require(&#39;util&#39;);</pre><pre>var Person = function(name){<br>  this.name = name;<br>};</pre><pre>util.inherits(Person, events.EventEmitter);</pre><pre>var james = new Person(&#39;james&#39;);<br>var mary = new Person(&#39;mary&#39;);<br>var ryu = new Person(&#39;ryu&#39;);<br>var people = [james,mary,ryu];</pre><pre>people.forEach(function(person){<br>  person.on(&#39;speak&#39;, function(mssg){<br>    console.log(person.name + &#39; said: &#39;+ mssg);<br>  })<br>});</pre><pre>james.emit(&#39;speak&#39;, &#39;Hey dudes&#39;);</pre><p>Observation:</p><p>If we are using only EventEmitter then we could do this way</p><pre>var events = require(&#39;events&#39;).EventEmitter;</pre><p>For more explanation head on to <a href="https://coligo.io/nodejs-event-emitter/">this article.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deda2ef78031" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modules]]></title>
            <link>https://medium.com/@pavanboro/modules-9104ad60d63d?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9104ad60d63d</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Fri, 31 Mar 2017 16:33:23 GMT</pubDate>
            <atom:updated>2017-04-01T08:25:06.861Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes taken from <a href="https://www.youtube.com/playlist?list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp">The Net Ninja</a>.</p><p><a href="https://nodejs.org/api/globals.html"><strong>Global Object:</strong></a></p><p>In browser Global object is the window object.</p><p>In node.js Global Object is an object that contains objects which are available to all modules.</p><p>list of<a href="https://nodejs.org/api/globals.html"> global objects</a></p><p><strong>Function Expression:</strong></p><pre>// Normal function <br> function sayBye() {<br>    console.log(&#39;Bye&#39;);<br> }</pre><pre>// Function Expression</pre><pre>var sayBye = function(){<br>    console.log(&#39;Bye&#39;);<br>}</pre><p>Note: we can pass function to another functions.</p><p><strong>Modules and Require():</strong></p><p>We use them to split our code up into re-usable, logical sections.</p><p>// count.js</p><pre>var counter = function(arr) {<br>    return &#39;There are&#39; + arr.length + &#39; elements in this array&#39;;<br>};</pre><pre>module.exports = counter;</pre><p>// app.js</p><pre>var counter = require(&#39;./count&#39;);</pre><pre>console.log(counter([&#39;shaun&#39;, &#39;crystal&#39; , &#39;ryu&#39;]));</pre><p>run node app.js</p><p><strong>Module Patterns:</strong></p><p>// stuff.js</p><pre>var counter = function(arr) {<br>    return &#39;There are&#39; + arr.length + &#39; elements in this array&#39;;<br>}; </pre><pre>var adder = function(a,b) {<br>    return `The sum of the 2 numbers is ${a+b}`;<br>};</pre><pre>var pi = 3.142;</pre><pre>module.exports.counter = counter;<br>module.exports.adder = adder;<br>module.exports.pi = pi;</pre><p>// app.js</p><pre>var stuff = require(&#39;./stuff&#39;);</pre><pre>console.log(stuff.counter([&#39;shaun&#39;,&#39;crystal&#39;, &#39;ryu&#39;]));<br>console.log(stuff.adder(5,6));<br>console.log(stuff.adder(stuff.pi,5));</pre><p>run app.js</p><p><strong>Observation by playing with code:</strong></p><p>When only</p><pre>module.exports = counter;</pre><p>is used we can use it directly as counter([‘shaun’, ‘crystal’ , ‘ryu’])</p><p>And when we use</p><pre>module.exports.counter = counter;</pre><p>and in app.js</p><pre>var test = require(&#39;./sutff&#39;);</pre><p>we have to use test.counter</p><p>This is because we are importing multiple objects from the same file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9104ad60d63d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The V8 Engine]]></title>
            <link>https://medium.com/@pavanboro/the-v8-engine-1b3a1c624f4d?source=rss-1c0431ac1c8e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3a1c624f4d</guid>
            <dc:creator><![CDATA[Pavan Boro]]></dc:creator>
            <pubDate>Wed, 29 Mar 2017 04:03:19 GMT</pubDate>
            <atom:updated>2017-03-29T04:03:19.496Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes taken from <a href="https://www.youtube.com/watch?v=86tgU7UaJmU&amp;index=3&amp;list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp">The Net Ninja</a></p><p>Computers does not understand JavaScript. So it needs to be converted to a language that a computer can understand i.e. Machine code .</p><p>JavaScript engine (V8) does that stuff of converting to JS to Machine level language.</p><p>Node.js is written in C++ also</p><p>V8 is written in C++ which can be standalone or embedded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*UfIT5-mVCj8bBWWZH5MD9Q.png" /><figcaption>Node.js embedded with V8</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3a1c624f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>