<?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 Lahiru Sampath on Medium]]></title>
        <description><![CDATA[Stories by Lahiru Sampath on Medium]]></description>
        <link>https://medium.com/@lsampath210?source=rss-17b3ed2cc240------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*bvReIL6D8CTeeWXhnoL42A.jpeg</url>
            <title>Stories by Lahiru Sampath on Medium</title>
            <link>https://medium.com/@lsampath210?source=rss-17b3ed2cc240------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:12:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lsampath210/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[The Strange Case of PostgreSQL Advisory Locks]]></title>
            <link>https://medium.com/@lsampath210/the-strange-case-of-postgresql-advisory-locks-bc6be6190788?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc6be6190788</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 14:44:46 GMT</pubDate>
            <atom:updated>2025-08-02T14:44:46.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*r258VJ5Dc3WBPvsm4FUEPg.png" /><figcaption>Not a database lock</figcaption></figure><p><strong>PostgreSQL</strong> is packed with concurrency control features to ensure data consistency and prevent conflicts during concurrent access.</p><p>But sometimes, the requirement isn’t to enforce constraints within the database, but to coordinate behavior between parts of your application or service. You’re not protecting db rows or tables; you’re managing access to a shared resource, a background job, or a critical section of logic. That’s where <strong>advisory locks</strong> come into play.</p><p>Advisory locks are not automatically enforced. They don’t prevent updates or deletes. They’re more like a <strong>stop sign, </strong>that you have to write your code to check the lock and back off.</p><h3>How does it work?</h3><p>They work by locking a key, (which is a <strong>BIGINT</strong> value in most scenarios) just like below example.</p><pre>SELECT pg_advisory_lock(1996);</pre><p>Here’s how you lock key <em>1996</em>. Anyone else trying to lock the same key gets blocked until you release it.</p><h3>Blocking vs non-blocking behavior</h3><p>There are two flavours when it comes to getting blocked by a advisory lock.</p><p><strong>Blocking</strong> locks mean if the lock you try to acquire is already taken, then your operation waits until you eventually get the lock. In the above example, we acquire the lock using a blocking approach.</p><p>Since blocking can be problematic in modern system designs, there’s a <strong>non-blocking</strong> approach that immediately returns a boolean indicating success or failure. See the example below,</p><pre>SELECT pg_try_advisory_lock(12345);<br>-- Returns true if successful, false if already locked</pre><h3>Session-level vs transaction-level locks</h3><p>There are two scopes of advisory locks.</p><p><strong>Session-level</strong> locks stick around until you explicitly release the lock or the session ends. A session is basically the lifespan of the connection between your client and the database server. They’re useful when your locking logic spans multiple operations or needs to persist outside transactions.</p><p>The code below shows how to create and release session-level locks. (The earlier examples also used session-level locks.)</p><pre>-- Blocking<br>SELECT pg_advisory_lock(45678);<br><br>-- Otherwise, Non-blocking approach<br>SELECT pg_try_advisory_lock(45678);<br><br>-- Release manually<br>SELECT pg_advisory_unlock(45678);</pre><p><strong>Transaction-level</strong> advisory locks, on the other hand, are scoped to the current transaction. They are automatically released when the transaction is committed or rolled back, and cannot be manually released.</p><p>Usage of blocking transaction-level lock,</p><pre>BEGIN;<br>SELECT pg_advisory_xact_lock(12345);<br>-- Do critical work<br>COMMIT;  -- Lock is released here</pre><p>A non-blocking variant,</p><pre>DO $$<br>DECLARE<br>    got_lock boolean;<br>BEGIN<br>    SELECT pg_try_advisory_xact_lock(12345) INTO got_lock;<br>    IF got_lock THEN<br>        -- Do the work<br>    ELSE<br>        RAISE NOTICE &#39;Could not acquire the lock !!!!&#39;;<br>    END IF;<br>END $$;</pre><h3>When (and Why) to Use Advisory Locks</h3><p>As we discussed earlier, this is not about ensuring database level concurrency.</p><p>Sometimes we need to coordinate work at the application level using locks. But traditional in-memory locks are limited to the scope of a single service or instance, they don’t work across multiple instances in a distributed setup.</p><p>If you have several service instances all connected to a <strong>shared PostgreSQL database</strong>, advisory locks become a powerful tool. They let you coordinate access to critical sections, limit concurrency for shared resources, or prevent multiple workers from picking up and processing the same job.</p><blockquote>But, why can‘t we use a flag column in a database table as a lock?</blockquote><p>Using flags in tables is risky, since transactions aren’t always atomic unless you crank up isolation levels, which adds overhead. Plus, flags (a column in the table) are written to disk. Advisory locks, on the other hand, are <strong>in-memory, atomic</strong>, and purpose-built for coordination, making them a cleaner, faster solution.</p><p>In the strange case of PostgreSQL advisory locks, sometimes the best locks are the ones you control yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc6be6190788" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Constructors]]></title>
            <link>https://medium.com/@lsampath210/scala-constructors-c654414658e0?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/c654414658e0</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[constructor]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 20:23:20 GMT</pubDate>
            <atom:updated>2023-09-24T08:29:13.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Constructors are used to create objects. If you are coming from Java, then constructors might have been a straightforward concept for you. But in Scala, this concept is a bit more complex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6tZaPg726Xtij4K10s9XQ.jpeg" /><figcaption>Constructors</figcaption></figure><p>There are two types of constructors in Scala.</p><ol><li>Primary Constructors</li><li>Auxiliary Constructors</li></ol><p><strong>Primary Constructors</strong></p><p>Let’s start from an example class with a simple primary constructor.</p><pre>class Student(id: Int, name: String) { <br>  println(&quot;hello from primary constructor&quot;) <br>}<br><br>val s1 = new Student(1, &quot;john&quot;)<br>&gt; hello from primary constructor</pre><p>There can be only one primary constructor per class definition. As we can see, the primary constructor is bound into the Student class itself. Statements we write inside the class body (curly brackets) are part of the primary constructor. Class body except for method definitions inside the class, can argued to be the primary constructor body.</p><p>When you don’t have parameters in your constructor, Scala defines a default primary constructor by itself. There is a special case about parameter-less constructors in Scala classes. Specifying parentheses is optional when there are no parameters in your class’s primary constructor. For both class definition and constructor invocation.</p><pre>class A { }<br>class B() {}<br><br>val a1 = new A<br>val a2 = new A()<br>val b1 = new B<br>val b2 = new B()</pre><p>As above code snippet suggests, final outcome will be the same regardless of the parentheses.</p><p><strong>Auxiliary (secondary) Constructors</strong></p><p>Any constructor except the primary constructor is called an auxiliary constructor. Can define multiple such constructors with <strong>this </strong>keyword, but with different signatures. The first statement of any auxiliary constructor should always call the primary constructor. Let’s define an auxiliary constructor with those rules.</p><pre>class Student(id: Int, name: String) { <br>  println(&quot;hello from primary constructor&quot;) <br>  <br>  def this(name: String) = { <br>    this(0, name) <br>    println(&quot;hello from auxiliary constructor&quot;) <br>  } <br>}<br><br>val s2 = new Student(&quot;smith&quot;)<br>&gt; hello from primary constructor<br>&gt; hello from auxiliary constructor</pre><p><strong>Invoking superclass constructor</strong></p><p>Only the primary constructor is allowed to invoke superclass constructors. Auxiliary constructors can only call the primary constructor of the same class. When a superclass has multiple constructors, the primary constructor of the subclass can decide which super- constructor to be invoked. Let’s take an example to describe this situation.</p><pre>class Person(age: Int, name: String) { <br>  println(&quot;primary constructor of Person&quot;) <br>  def this(name: String) = { <br>    this(0, name) <br>    println(&quot;auxiliary constructor of Person&quot;) <br>  } <br>}<br><br>// calls auxiliary constructor of superclass<br>class Employee(empId: Int, age: Int, name: String) extends Person(name) { <br>  println(&quot;primary constructor for Employee&quot;) <br>  def this(empId: Int, name: String) = { <br>    this(empId, 0, name) <br>    println(&quot;auxiliary constructor of Employee&quot;) <br>  } <br>}<br><br>// calls primary constructor of superclass<br>class EmployeeTwo(empId: Int, age: Int, name: String) extends Person(age, name) {}</pre><p>As we can see in the example, we can define our class to invoke any superclass constructor.</p><p><strong>Access modifiers for constructors</strong></p><p>In Scala, there are three access modifiers that can be used for constructors: private, protected, and public. By default, constructors are public. Public constructors can be accessed anywhere in our program, while others have some restrictions. Let’s define some constructors with different access privileges and discuss.</p><pre>class Animal(age: Int) {}                //-----public/default constructor<br>class Animal private (age: Int) {}       //-----private constructor<br>class Animal protected (age: Int) {}     //-----protected constructor<br>class Animal private {}                  //-----protected constructor without any parameters</pre><p>Private keyword before the constructor definition makes it visible only for the class itself and companion object. Use case is to hide the constructor and provide other means of instantiation, like using companion objects or builders. We cannot use new keyword from an outside entity. Keep in mind that private constructors restrict the class from inheritance. You cannot extend from a private class.</p><p>Protected constructors have similar visibility, but they can be inherited from and sub classes can access super class constructor.</p><p>In conclusion, Scala constructors can be both simple and complex at the same time. Understanding how constructors work is fundamental to mastering Scala’s powerful and flexible programming language. With this knowledge, you can effectively harness the full potential of Scala to build robust and efficient applications.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c654414658e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Traits — part I]]></title>
            <link>https://medium.com/@lsampath210/scala-traits-part-i-6d252c68868b?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d252c68868b</guid>
            <category><![CDATA[traits]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 01:15:10 GMT</pubDate>
            <atom:updated>2022-11-23T01:15:10.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scala Traits — part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1UiQE3M1WFTft87zwYa-hA.png" /></figure><p>Traits are similar to Java interfaces, and they are compiled into Java interfaces. But they are not exactly the same.</p><p>Check this very simple trait definition:</p><pre>trait Human {<br>  def eat(): Unit<br>  def walk(): Unit<br>  def greet: string<br>}</pre><p>Classes, objects, and other traits can inherit from traits. Assume you have defined a trait called BarkerTrait. Now you can inherit from that trait as follows:</p><pre>&gt; class DogClass extends BarkerTrait<br>&gt; object HuskyObject extends BarkerTrait<br>&gt; trait DogTrait extends BarkerTrait<br>&gt; class DogClass extends AnimalClass with BarkerTrait</pre><p>Java interfaces can only inherit from other interfaces. But unlike Java, Scala traits can inherit from both classes and other traits. (Keep in mind, you cannot inherit from Scala object definitions)</p><pre>&gt; trait BarkerTrait extends TalkerTrait<br>&gt; trait BarkerTrait extends AnimalClass<br>&gt; trait BarkerTrait extends AnimalClass with TalkerTrait</pre><p>Scala allows you to have concrete members inside trait definitions. Scala traits that contain code are called mixins. But what exactly can be recognized as code in mixins?</p><ol><li>Concrete/non-abstract method definitions.</li><li>variables/fields</li><li>Constructors without parameters</li></ol><p>We can call the above things “code,” “concrete members,” or “non-abstract members” of a mixin trait.</p><p>Check the following mixin trait with concrete members:</p><pre>trait Human {<br>  val name = “Human Name”<br>  def eat(): Unit<br>  def walk(): Unit<br>  def greet: String = “Hi my name is “ + name + “.”<br>}</pre><p>When a trait has abstract methods, you have to override and implement them inside the trait’s non-abstract child classes or objects. Check the following example class extended from Human mixin trait:</p><pre>class CountryMan extends Human {<br>   override def eat(): Unit = {<br>      println(&quot;eat like a countryman.&quot;)<br>      println(&quot;take a nap after eating&quot;)<br>   }<br><br>   override def walk() = println(&quot;walk on top of the mountains&quot;)<br>}</pre><p>Traits cannot be instantiated. They cannot have parameterized constructors, yet they can parameterless constructors. (Scala 3 traits can have parameters).</p><p>Scala trait is a large topic that cannot be covered in a single article. I am planning to cover more details in future articles.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d252c68868b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why, how and where DNS records are cached ??]]></title>
            <link>https://medium.com/@lsampath210/why-how-and-where-dns-records-are-cached-3e4f587ea40c?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e4f587ea40c</guid>
            <category><![CDATA[internet-protocol]]></category>
            <category><![CDATA[dns-servers]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[dns-cache]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 13:22:40 GMT</pubDate>
            <atom:updated>2022-11-18T13:22:40.141Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why, how and where DNS records are cached ??</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rV5sxpBsWEJBbDorNjmg0w.jpeg" /></figure><h3><strong>Why domain name records are cached?</strong></h3><p>Domain names are names assigned by people that cannot be understood by machines. They need ip addresses to find something on the internet. Thus, someone has to convert domain names to ip addresses, so that internet protocol can understand our requirements. We call it DNS resolving.</p><p>When you type a url with a domain name in the browser, it has to go through a lot of servers just to resolve the underlying ip address. Which is complex and time consuming. DNS caching is a temporary database of recent DNS lookups, introduced to make this process much easier.</p><h3><strong>Browser cache</strong></h3><p>Different browsers can have different DNS caching mechanisms. Firefox maintains a volatile cache which is flushed when we quit the browser. But Chrome (which is popular for caching everything) maintains a non-volatile cache which won’t be removed by quitting or restarting.</p><p>You have to manually flush Chrome DNS records cache by visiting below configuration page,</p><pre>chrome://net-internals/?#dns</pre><p>Keep in mind, DNS cache won’t be completely removed if you have open sockets when you flush. Because open sockets can immediately create new DNS records in your cache again.</p><p>In Chrome, you can close all open sockets by visiting this config page,</p><pre>chrome://net-internals/#sockets</pre><h3><strong>Caching beyond browser</strong></h3><p>If the browser cannot resolve domain name records within its cache, then it will ask from outside. Browser first asks from OS level resolvers. Nowadays, most operating systems have domain name resolvers and caches. For example most Ubuntu versions come with <strong><em>systemd-resolved</em></strong> or <strong><em>resolvectl</em></strong>, which act as a local DNS server.</p><p>Beyond OS, some home broadband routers have their own domain name record caches. And most ISPs maintain their own caches as well. If none of them works, they have to ask from recursive name servers, room nameservers or TLD nameservers, until they reach an authoritative nameserver to answer their domain name lookup request.</p><p>Keep in mind all those lookup requests are recursive calls. When some answers the request, the response will come back in the same path while updating each and every server it has gone through. Thus, the next request does not have to get into trouble.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e4f587ea40c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Spring instantiate JpaRepository interfaces.]]></title>
            <link>https://medium.com/@lsampath210/how-spring-instantiate-jparepository-interfaces-52e97c8875e5?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/52e97c8875e5</guid>
            <category><![CDATA[jparepository]]></category>
            <category><![CDATA[dynamic-proxy]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 13:40:32 GMT</pubDate>
            <atom:updated>2022-10-28T13:40:32.943Z</atom:updated>
            <content:encoded><![CDATA[<h4>I have been working with Spring framework for quite some time. While using their JPA dependency, the level of abstraction provided by these JpaRepository interfaces always amazes me.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mElC_sJG76h0v9tdrhKNEA.jpeg" /></figure><p>JpaRepository interfaces are a specification provided by the Spring Boot framework for managing relational data. We can extend these interfaces with custom method definitions and yet we don’t have to implement them.</p><p>Check following definition to retrive Battery data using a JpaRepository,</p><pre>public interface BatteryRepository extends<br>        JpaRepository&lt;Battery, Long&gt; {<br>    List&lt;Battery&gt; findByName(String name);<br>    List&lt;Battery&gt; findByCapacityGreaterThanEqual(Float capacity);<br>    List&lt;Battery&gt; findByCapacityLessThan(Float capacity);<br>}</pre><p>Spring does not instantiate this interface, so there is no code generation at runtime. They create a dynamic proxy instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*cAyoPwGw2GQFSuySPBX08w.png" /><figcaption>object relationship between batteryService and battery repository proxy</figcaption></figure><p>A dynamic proxy is an object generated at runtime that implements (but does not actually implement a concrete class) one or more interfaces. This Proxy maintains an InvocationHandler object to handle method invocations.</p><p>Something similar happens inside Spring when we use JpaRepository interfaces. Spring has a ProxyFactory to generate proxy objects for those JpaRepository interfaces.</p><p>What if I am lying?</p><p>When you inject yourself an object of the BatteryRepository type, is it really a proxy object?</p><pre>@Autowired<br>private BatteryRepository batteryRepository;<br><br>@Test<br>void testBatteryServiceIsProxy() {<br>   boolean isProxy = AopUtils.<em>isAopProxy</em>(batteryRepository);<br>   Assertions.<em>assertTrue</em>(isProxy);<br>}</pre><p>AopUtils.isAopProxy() method should return true, for any proxy object we have. Be my guest.</p><p>Assume we want to invoke the <em>findByName() </em>method of the BatteryRepository interface. When we invoke this method (defined in the interface), through the proxy object, our call is redirected to the <em>invoke()</em> method of the InvocationHandler object. Inside this <em>invoke()</em> method, Java can generate whatever program logic is according to the method name and available arguments.</p><p>I am not going to discuss Spring’s underlying mechanism to derive JPA queries inside this <em>invoke()</em> method. It is something we have to talk about later.</p><p>All this magic happen at run time.</p><p>But what if you don’t want all this magic to happen? Maybe you want to actually implement this BatteryRepository interface on your own.</p><pre>@NoRepositoryBean<br>public interface BatteryRepository extends<br>        JpaRepository&lt;Battery, Long&gt; {<br>    List&lt;Battery&gt; findByName(String name);<br>}</pre><p>Use this <em>@NoRepositoryBean </em>annotation on top of your interface definition. Now Spring won’t consider this as a suitable candidate for proxies. You can now use this interface to create your own custom concrete classes without having to worry about all of those proxies.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52e97c8875e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paypal integration for Spring-Boot backend]]></title>
            <link>https://medium.com/@lsampath210/paypal-integration-for-spring-boot-backend-243e71c89a74?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/243e71c89a74</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[payment-processing]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[paypal]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 10:57:24 GMT</pubDate>
            <atom:updated>2022-10-22T10:57:24.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhYNFNKonmrybJILxoOoow.png" /></figure><p>Paypal is a very common Payment Service Provider used in enterprise applications. Here we are trying to integrate the Paypal payment gateway into our Spring Boot backend and expose it through REST endpoints to a potential frontend.</p><p>We are using Maven as our build tool and there are two possible maven dependencies to use: <a href="https://mvnrepository.com/artifact/com.paypal.sdk/checkout-sdk/2.0.0"><strong>checkout-sdk</strong></a> or <a href="https://mvnrepository.com/artifact/com.paypal.sdk/rest-api-sdk/1.14.0"><strong>rest-api-sdk</strong></a>. But it’s better to use <strong>checkout-sdk because</strong> they have stopped releasing new versions of <strong>rest-api-sdk</strong> since 2017.</p><p>You need to have a Paypal account created to begin with. Then create a Sandbox app to generate your clientId and clientSecret codes. We don’t need a live app created, unless we are going for production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzPS5cJ-y6eyifbiP6Ra5A.png" /><figcaption>Architecture diagram with a frontend</figcaption></figure><p>This architecture is for a system with frontend and a REST backend API. But I am not going to implement frontend here. Let’s go through necessary backend components one-by-one.</p><ol><li>Frontend should initiate the payment with “Pay Now” button click event. It takes an amount to be paid to the backend. Let’s create a controller class to listen into those payment initilization requests from frontend.</li></ol><pre>@RestController<br>@RequestMapping(value = &quot;/paypal&quot;)<br>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>public class PaymentController {<br>    @Autowired<br>    private PaypalService paypalService;<br><br>    @PostMapping(value = &quot;/init&quot;)<br>    public PaymentOrder createPayment(<br>            @RequestParam(&quot;sum&quot;) BigDecimal sum) {<br>        return paypalService.createPayment(sum);<br>    }<br>}</pre><p>2. Now, within our backend, we have to send an <em>order creation request </em>to Paypal using their <strong>PaypalHttpClient</strong>. First, we need to create a <strong>PaypalHttpClient </strong>bean within our spring container. We can use a configuration class for that.</p><pre>@Configuration<br>public class PaypalConfiguration {<br>    @Bean<br>    public PayPalHttpClient getPaypalClient(<br>            @Value(&quot;${paypal.clientId}&quot;) String clientId,<br>            @Value(&quot;${paypal.clientSecret}&quot;) String clientSecret) {<br>        return new PayPalHttpClient(new PayPalEnvironment.Sandbox(clientId, clientSecret));<br>    }<br>}</pre><p>Please note we should configure paypal clientId and clientSecret in our backend configuration files.</p><p>Once we have this PaypalHttpClient configured and injected into the spring container, we can use it to create order request to the PayPal PSP.</p><pre>@Slf4j<br>@Service<br>public class PaypalService {<br><br>    @Autowired<br>    private PayPalHttpClient payPalHttpClient;<br><br>    public PaymentOrder createPayment(BigDecimal fee) {<br>        OrderRequest orderRequest = new OrderRequest();<br>        orderRequest.checkoutPaymentIntent(&quot;CAPTURE&quot;);<br>        AmountWithBreakdown amountBreakdown = new AmountWithBreakdown().currencyCode(&quot;USD&quot;).value(fee.toString());<br>        PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest().amountWithBreakdown(amountBreakdown);<br>        orderRequest.purchaseUnits(List.<em>of</em>(purchaseUnitRequest));<br>        ApplicationContext applicationContext = new ApplicationContext()<br>                .returnUrl(&quot;https://localhost:4200/capture&quot;)<br>                .cancelUrl(&quot;https://localhost:4200/cancel&quot;);<br>        orderRequest.applicationContext(applicationContext);<br>        OrdersCreateRequest ordersCreateRequest = new OrdersCreateRequest().requestBody(orderRequest);<br><br>        try {<br>            HttpResponse&lt;Order&gt; orderHttpResponse = payPalHttpClient.execute(ordersCreateRequest);<br>            Order order = orderHttpResponse.result();<br><br>            String redirectUrl = order.links().stream()<br>                    .filter(link -&gt; &quot;approve&quot;.equals(link.rel()))<br>                    .findFirst()<br>                    .orElseThrow(NoSuchElementException::new)<br>                    .href();<br><br>            return new PaymentOrder(&quot;success&quot;,  order.id(), redirectUrl);<br>        } catch (IOException e) {<br>            <em>log</em>.error(e.getMessage());<br>            return new PaymentOrder(&quot;Error&quot;);<br>        }<br>    }<br>}</pre><p>Please note that <strong>returnUrl </strong>and <strong>cancelUrl </strong>are URLs for two views in the frotend. We will be talking about them in the future. At the end of this code, we are acquiring the<strong> approve-url </strong>provided by Paypal PSP. We need to return this url to the frontend.</p><p>3. Now we have approve-url in our frontend, we need to manuly redirect to this URL to authorize the payment. Note that authorization URL with be something like below.</p><p><em>“https://www.sandbox.paypal.com/checkoutnow?token=69R3925679086770L&quot;</em></p><p>4. Once you have gone through authorization wizard provided by Paypal and submit, it will communicate with Paypal PSP itself to complete the authorization.</p><p>5. If authorization is failed, you will be redirected to the <strong>cancelUrl </strong>provided at step 2. If it is success, you will be redirected to the <strong>captureUrl </strong>with two request params. “<strong>token</strong>” and “<strong>PayerID</strong>”.</p><p>6. Once you are redirected to the capture view, we need to complete this payment by sending a capture request to the backend. We need another controller method to listen in on those payment completion requests.</p><pre>@RestController<br>@RequestMapping(value = &quot;/paypal&quot;)<br>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>public class PaymentController {<br>    @Autowired<br>    private PaypalService paypalService;<br><br>    @PostMapping(value = &quot;/init&quot;)<br>    public PaymentOrder createPayment(<br>            @RequestParam(&quot;sum&quot;) BigDecimal sum) {<br>        return paypalService.createPayment(sum);<br>    }<br><br>    @PostMapping(value = &quot;/capture&quot;)<br>    public CompletedOrder completePayment(@RequestParam(&quot;token&quot;) String token) {<br>        return paypalService.completePayment(token);<br>    }<br>}</pre><p>7. Now within our payment server, we need to send payment capture request to Paypal PSP again to complate the payment and do the fund transaction.</p><pre>@Slf4j<br>@Service<br>public class PaypalService {<br><br>    @Autowired<br>    private PayPalHttpClient payPalHttpClient;<br><br>    public PaymentOrder createPayment(BigDecimal fee) {<br>        //.........................<br>    }<br><br><br>    public CompletedOrder completePayment(String token) {<br>        OrdersCaptureRequest ordersCaptureRequest = new OrdersCaptureRequest(token);<br>        try {<br>            HttpResponse&lt;Order&gt; httpResponse = payPalHttpClient.execute(ordersCaptureRequest);<br>            if (httpResponse.result().status() != null) {<br>                return new CompletedOrder(&quot;success&quot;, token);<br>            }<br>        } catch (IOException e) {<br>            <em>log</em>.error(e.getMessage());<br>        }<br>        return new CompletedOrder(&quot;error&quot;);<br>    }<br><br>}</pre><p>Hope you learn something from this post. Please check following Git repo for complete source files.</p><p><a href="https://github.com/LSampath/paypal-spring-demo">GitHub - LSampath/paypal-spring-demo: Paypal checkout sdk integration for spring boot backend</a></p><p>Bye…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=243e71c89a74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spike Time Dependent Plasticity]]></title>
            <link>https://medium.com/analytics-vidhya/spike-time-dependent-plasticity-eef34fe0ce8f?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef34fe0ce8f</guid>
            <category><![CDATA[hebbian]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[stdp]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 05:17:05 GMT</pubDate>
            <atom:updated>2020-01-01T13:00:46.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*XVeoXOsXkn2VOl3mJEwXnA.jpeg" /></figure><p><strong>What is Spike Time Dependent Plasticity ?</strong></p><p>Back-propagation by gradient descent is the underlying learning rule of artificial neural networks (ANN). This rule relies upon loss function and tries to minimize the overall loss of the network by using derivative of loss as a feedback. Even though intuition for ANNs came from natural neural networks in our brain, there are many difference between those two and learning rules are one of them. Underlying learning rule of natural neural networks are way different from back-propagation.</p><p>Mostly neural networks with back-propagation are focused toward a fixed target. It means, once the neural network is trained for one particular task, it overwrites old weights and forget old patterns it has been trained for. In ANN, this phenomena are called catastrophic forgetting. Natural neural networks are not vulnerable to catastrophic learning and they are capable of learning continuously with new inputs (mostly throughout the lifetime). To improve ANNs to this such level, a dynamic learning rule is required.</p><p>Natural neural networks have a simple learning rule where weight dynamic of one particular connection/synapse is depending only on the activities of connection neurons, but not on the activity of whole network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*9Dz00an1e1FTr42SNEH0yQ.png" /><figcaption>Neural synapse</figcaption></figure><p><strong>Hebbian Rule</strong></p><p>One of the simplest and oldest learning algorithms claimed to be present in natural neural networks. Suppose there is a connection from neuron A to neuron B. In brain, this connection, neuron A (sender) and neuron B (receiver) are called synapse, presynaptic neuron and postsynaptic neuron respectively. According to Hebbian learning rule, if two neurons are fired together, synaptic weight between those two neurons can be increased.</p><p>In mathematics, Hebbian rule is expressed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*n4KKnwuEHH_LJ4_p8Tl-BQ.png" /></figure><p>Here, <strong><em>w­ij[n]</em></strong> is the weight on synapse from presynaptic neuron <strong><em>i</em></strong> to <strong><em>j</em></strong> at time step <strong><em>n.</em></strong> <strong><em>η</em></strong> is the learning rule coefficient and <strong><em>xi[n]</em></strong> and<strong><em> yj[n]</em></strong> are the outputs of neurons <strong><em>i</em></strong> and <strong><em>j</em></strong> in nth time step.</p><p>But, some properties of Hebbian rule are making it unsuitable as a biological learning rule.</p><p>Most dominant factor is not having a proper way to decrease synaptic weight. When two neurons fire together, synaptic weight can only be increased. Even though some studies have come up with extended versions of Hebbian rule with approaches to reduce synaptic weight, even they are not biologically plausible. Another problem of Hebbian is, not considering the temporal different between presynaptic spike and post-synaptic spike. It is not possible for both neurons to fire at the same time. There should be a temporal different between those two and it is not considered as an important factor with this learning rule.</p><p><strong>Spike Time Dependent Plasticity</strong></p><p>STDP rule emerged with answers to those problems. Here, synaptic weight update is depending on the sign and size of the temporal difference of pre and post spikes. According to STDP, repeated firing of presynaptic spikes before postsynaptic spikes can lead to increase of synaptic weight in the long term and repeated firing of postsynaptic neurons before emission of presynaptic spikes can lead to decrease of synaptic weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*tPBdl9tylL8V3v1EQHSs6w.png" /><figcaption>updated weight w.r.t. temporal difference in STDP rule</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*9GAADMSV_LClebJprOZ7_g.png" /></figure><p><strong><em>Δt = ti — tj</em></strong> is the temporal difference between the post and presynaptic spikes and <strong><em>F(w)</em></strong> describes the dependence of the update on the current weight of the synapse.</p><p>Some biological studies suggest that, if the temporal difference to too small, change in synaptic change will be positive (increase of weight) regardless of the order of pre and post spikes. As a result of that connection strength between frequently firing neurons are always enhanced.</p><p>However, implementing this STDP rule is considered to be computationally expensive task because to update synaptic weight, we have to keep track of spike times of each neurons to calculate temporal differences. ‘Synaptic traces’ is a much more efficient approach used by researchers to implement the same effect of STDP. Refer more on this topic if you wish to use STDP as the learning rule of your neural network.</p><p>Hope this is helpful.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef34fe0ce8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/spike-time-dependent-plasticity-eef34fe0ce8f">Spike Time Dependent Plasticity</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Retinal Receptive Fields using Difference of Gaussian kernel]]></title>
            <link>https://medium.com/@lsampath210/implementation-of-retinal-receptive-fields-using-difference-of-gaussian-kernel-6e13778b3ec?source=rss-17b3ed2cc240------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e13778b3ec</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[retina]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[receptive-field]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Lahiru Sampath]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 13:28:33 GMT</pubDate>
            <atom:updated>2019-11-17T13:28:33.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*APksoYcAVopvYdClGmrdYA.jpeg" /></figure><p>Receptive field is a region of a cell which can stimulate the cell under external factors. In visual system, receptive fields can be recognized as 2-dimensional spaces and are sensitive to intensity of light. Retina is a thin layer located in the eye, compromised of photo-receptor cells. These cells can detect qualities of the image projected on the retina using their receptive fields and send this information to the primary visual cortex of the brain via optic nerve.</p><p><strong>Functionality and Structure</strong></p><p>Retinal receptive fields are circular in shape, with separate sub-regions; center and surround. There two sub-regions have antagonistic preferences (bright and dark) and it divides these receptive fields into two categories. On-center off-surround and off-center on-surround receptive fields. On sub-regions are stimulated most when they are exposed to higher intensity of light while off sub-regions prefer darker situations. Thus, we can expect opposite behavior of on-center receptive fields from the off-center receptive fields.</p><p>Consider following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*JC6zT4wK0GUT1SISgGNSww.jpeg" /><figcaption>Figure 1 — Functionality of retinal receptive fields</figcaption></figure><p>Left column describes the spiking pattern of an on-center receptive field when exposed to different type of stimulus while right column describes details for off-center receptive fields. I am not going to explain the diagram in this article, as you can derive it yourself easily. Instead, lets focus on those two types of receptive fields in large scale.</p><p>Consider a layer of photo-receptor cells with on-center receptive fields, exposed to a stimuli. Suppose there is an edge separating a brighter section from darker section in this stimuli. Since on-center receptive fields are stimulated most at high intensities, photo-receptor cells who have their on-centers are at the bright side and surrounding is barely in dark section fires most. Likewise, cells on the bright side of each edge fires and output in large scale will be the same input stimuli with bright side of each edge enhanced. Opposite can be expected from layer of off-center photo-receptor cells.</p><p><strong>Implementation</strong></p><p>There are many edge detection kernels popular in image processing domain these days and most of them are convolution matrices used to enhance edges which doesn’t make separate outputs related to on and off receptive fields. But among them, Difference of Gaussian (DoG) kernel have been able to follow the natural behavior of retinal receptive fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*OKLVuTH4YUy3UGmIsc6vkg.jpeg" /><figcaption>Figure 2 — Stimulus convolved using simple edge detection kernel</figcaption></figure><p><strong>Difference of Gaussian (DoG) / Mexican Hat kernel</strong></p><p>Here we are taking difference of two 2-dimensional Gaussian functions with different standard variation values. Let’s consider the mathematical background of this process before taking about results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*l6b41XSuFI_sVra5sLsoZA.png" /></figure><p>In above figure, <em>f1</em> and <em>f2</em> are 2-dimensional Gaussian functions with<em> σ1</em> &lt;<em> σ2</em>. And <em>g1</em> and <em>g2</em> be differences of Gaussian kernel functions. Following plot includes 3-dimensional and 2-dimensional (top down) views of those functions for your better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*WDpuW0heO6smnvp6b0_38Q.jpeg" /><figcaption>Figure 3–3-dimensional and top-down views of Gaussian functions and DoG functions</figcaption></figure><p>Now, we will be convolving an image stimulus with using these two DoG kernels to get final results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aa7JzdmggL8Gylcsk-n-Bg.jpeg" /><figcaption>Figure 4 —Effect of DoG kernel on an input stimulus</figcaption></figure><p>Here we are using an image with shape of character Z as the input stimuli. (Consider darker color as areas high intensity of light and lighter colors as low intensity, when comparing to natural phenomena in retina). We can see inner margins of edges are enhanced while outer margins of edges are weakened after convolving with <em>g1</em> kernel, which is he behavior of on-center retinal receptive fields. Also, in the right most figure, outer margins of edges are enhanced, and inner margins are weakened after convolving with <em>g2</em> kernel as we can expect from off-center receptive fields.</p><p>Contrast of the enhancement (edge detection) can be optimized using tuning the standard deviation values.</p><p>Hope you got a basic idea about natural retinal receptive fields and mathematical background behind artificial implementation.</p><p><em>Visit </em><a href="http://www.songho.ca/dsp/convolution/convolution2d_example.html"><em>here</em></a><em> to improve your knowledge on convolution.</em></p><p>Thank you. ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e13778b3ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>