<?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 Yumcoder on Medium]]></title>
        <description><![CDATA[Stories by Yumcoder on Medium]]></description>
        <link>https://medium.com/@omid.jn?source=rss-8dcdb3dc2cce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jcxeJg1RLgLJDSfm7xXk3g.jpeg</url>
            <title>Stories by Yumcoder on Medium</title>
            <link>https://medium.com/@omid.jn?source=rss-8dcdb3dc2cce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:25:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omid.jn/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[Terraform WireGuard Config Generator: First Impressions]]></title>
            <link>https://medium.com/@omid.jn/terraform-wireguard-config-generator-first-impressions-b4be387c5fad?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4be387c5fad</guid>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[mesh-networking]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <category><![CDATA[wireguard]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 04:22:44 GMT</pubDate>
            <atom:updated>2025-09-23T04:22:44.164Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/fedlify/terraform-wireguard">GitHub Repo</a></p><p>I stumbled across a handy little module this week: a provider-agnostic Terraform wrapper that spits out WireGuard configs in a few keystrokes. Instead of gluing together Bash scripts and templatefiles, you hand the module a map of nodes, pick your topology, and Terraform renders the full <em>wg0.conf</em> bundle for every peer. It’s a refreshingly opinionated take on self-hosted VPN automation.</p><p><strong>Why it stood out</strong></p><ul><li><strong>Topology-aware:</strong> Two modes ship out of the box (<strong>mesh</strong> for a full peer-to-peer fabric and <strong>hub-and-spoke</strong> for the traditional home-lab VPN). Flip a variable and the peer matrix rewires itself automatically.</li><li><strong>Key management choices:</strong> Bring your own public/private keys <em>or</em> let the module mint them. Under the hood it shells out to <em>wg genkey</em>, but you can swap in any executable.</li><li><strong>Tests included:</strong> Terraform’s native terraform test suite covers the busywork — ensuring peer defaults, DNS fallbacks, and generated keys land in the right places. It’s simple, fast, and — importantly — documented.</li><li><strong>Hands-on lab:</strong> A Docker Compose lab ships in lab/docker-two-node. Run terraform apply, boot two privileged Ubuntu containers, and you can watch handshakes form in seconds with <em>wg</em> <em>show</em> or a quick <em>ping</em>.</li></ul><p><strong>Getting going</strong></p><p>Drop the module into an existing Terraform project:</p><pre>module &quot;wireguard&quot; {<br>  source   = &quot;github.com/fedlify/terraform-wireguard&quot;<br>  topology = &quot;hub-and-spoke&quot;<br>  hub      = &quot;gateway&quot;<br><br>  nodes = {<br>    gateway = {<br>      private_key = var.gateway_private_key<br>      public_key  = var.gateway_public_key<br>      addresses   = [&quot;10.44.0.1/24&quot;]<br>      endpoint    = &quot;vpn.example.com:51820&quot;<br>    }<br>    laptop = {<br>      addresses = [&quot;10.44.0.2/32&quot;]<br>    }<br>  }<br><br>  auto_generate_keys = true        # optionally mint fresh key pairs<br>  default_listen_port = 51820<br>}</pre><p>After <em>terraform apply</em>, export configs:</p><pre>terraform output -raw hub_config &gt; hub.conf</pre><p><strong>Where it fits</strong></p><p>The module is ideal for teams shipping lightweight VPN access alongside existing infrastructure code or hobbyists experimenting with new topologies. Because it’s purely templating, you can drop the output onto EC2, bare metal, home routers, or that single-board computer gathering dust. The new key-generation toggle removes one of the more annoying manual steps.</p><p><strong>Verdict</strong></p><p>This module hits the sweet spot between simplicity and utility. It doesn’t try to manage cloud instances for you — it focuses on generating consistent, repeatable WireGuard configuration from Terraform data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4be387c5fad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Universe: Reality Through a Vectorial Lens]]></title>
            <link>https://medium.com/@omid.jn/the-ai-universe-reality-through-a-vectorial-lens-23510efd0833?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/23510efd0833</guid>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 13:35:38 GMT</pubDate>
            <atom:updated>2024-12-31T13:37:30.740Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Modern science and philosophy often rely on mathematical models to make sense of the world around us. From physics to data science, complex ideas are distilled into concepts like “dimensions,” “spaces,” and “vectors” to describe phenomena and their relationships. One intriguing worldview that emerges from these notions is that <strong>we can conceptualize reality itself</strong> as an expansive, multidimensional space where each phenomenon — including humans, objects, events, and ideas — can be represented as a <strong>vector</strong>. These vectors do not exist in isolation; they constantly interact, influencing each other’s directions and magnitudes.</p><p>In such a system, there is no need for an external power, like a deity, to orchestrate these interactions. Instead, the “rules” of the system arise naturally from the interplay of vectors within it. Yet in this same worldview, our <strong>beginning</strong> (birth) and <strong>end</strong> (death) also have distinct, if somewhat abstract, interpretations. Some might say that in <strong>death</strong>, humans return to something akin to a “zero state” in the grand vector space — reminding us that, although we emerge with a particular vector signature, we may eventually dissolve back into the baseline of existence. Below is an exploration of this vector-based perspective on existence, including how it might accommodate the idea of our “zero set” at the end.</p><h3>1. The Universe as a High-Dimensional Space</h3><p>In everyday life, we perceive our world in three spatial dimensions, plus the passage of time. However, when scientists and philosophers conceptualize phenomena, they often talk about higher dimensions — these can be anything from abstract mathematical dimensions in physics to feature dimensions in data analysis. For instance, imagine describing a person by height, weight, personality traits, social connections, talents, and so on. Each of these attributes can be considered a “dimension” in a representation of that person.</p><p>By analogy, <strong>the entire universe could be thought of as a vast, multidimensional ‘space’</strong> where every aspect of reality — physical properties, chemical configurations, emotional states, cultural contexts — occupies its own dimension or set of dimensions. While we might never fully map all these dimensions, the conceptual framework allows us to see <strong>just how interconnected</strong> everything is.</p><h3>2. Phenomena as Vectors</h3><p>A <strong>vector</strong>, in its simplest mathematical sense, is an entity with both magnitude (size) and direction in a given space. In a higher-dimensional space, a vector might look like a list of numbers [v1,v2,…,vn] that pinpoints a location or a collection of attributes within that space.</p><ul><li><strong>Physical Systems</strong>: In physics, the state of a particle can be represented by variables such as position, momentum, and spin — effectively giving it a “vector state” in a suitable mathematical space.</li><li><strong>Human Beings</strong>: Each of us can be seen as a <strong>complex vector</strong> of physical traits (height, weight, etc.), mental traits (beliefs, desires), social traits (relationships), and cultural traits (language, customs).</li><li><strong>Interactions</strong>: When two entities or phenomena meet, they exert influences on each other, akin to vector addition or transformation. We change and are changed by our environment, our relationships, and the events we experience.</li></ul><p>From this perspective, <strong>a “phenomenon” isn’t just an isolated thing</strong>; it is a confluence of vectors whose directions and magnitudes might shift under new interactions.</p><h3>3. Relationships as Transformations</h3><p>One of the most powerful notions in mathematics is that vectors do not stay static when acted upon by external forces. Instead, they undergo transformations — such as addition, rotation, or scaling — depending on the nature of the interaction.</p><ul><li><strong>Personal Relationships</strong>: If we treat our relationships with friends, family, and society as vectors, their dynamics can shape our personal vector. For instance, close friendships may “add” empathy, motivation, or new perspectives to our being, effectively rotating or translating our vector in the multidimensional space.</li><li><strong>Cultural Phenomena</strong>: Societal norms, historical events, and technological innovations can be seen as transformations operating on entire populations. They alter collective vectors, shifting communal values and beliefs.</li><li><strong>Natural Laws</strong>: On a larger scale, the regularities we observe in the universe — gravity, electromagnetism, chemical bonds — are like deep, consistent transformations that define how vectors interact. These <em>laws</em> provide structure, rendering our reality coherent and predictable (at least within certain bounds).</li></ul><p>Crucially, <strong>these transformations do not require a transcendental “overseer”</strong> to manage them. Like the rules of algebra or geometry, the system’s logic emerges naturally from the foundational properties of the space and its vectors.</p><h3>4. Death and the “Zero Set”</h3><p>In a worldview that depicts existence as a dance of vectors, <strong>birth</strong> can be seen as the emergence of a new vector into the system — loaded with genetic, environmental, and personal attributes — while <strong>life</strong> is the continual transformation of that vector through experiences, relationships, and growth. The concept of <strong>death</strong> then becomes the point at which one’s unique vector no longer <em>actively</em> transforms within this multidimensional interplay.</p><p>From one perspective, we might say at death, the individual vector collapses back to something like <strong>a “zero set”</strong> or <strong>“origin”</strong> — not necessarily in a literal sense, but symbolically indicating:</p><ol><li><strong>Cessation of Active Transformation</strong>: The distinct human vector, with all its attributes, contributions, and interactions, stops generating new changes in the same way.</li><li><strong>Reintegration into the Larger System</strong>: The energy, matter, or influence once housed in that vector disperses back into the environment — physically, cognitively, and socially. The human body returns to the earth’s material cycles, and memories live on in the vectors of other individuals and cultural artifacts.</li></ol><p>Seen this way, the “zero set” is a philosophical or metaphorical reminder that we originate from an underlying baseline (the fabric of existence) and ultimately return to it. There is <strong>no outside agent</strong> demanding this cycle; it is simply the natural ebb and flow of the system.</p><h3>5. A Self-Contained System Without a Controlling God</h3><p>One of the central implications of this worldview is that <strong>the universe is fundamentally self-organizing</strong>. If all phenomena can be understood as vectors within a multidimensional space, and if their interactions are governed by intrinsic laws (mathematical or otherwise), then the constant flux we observe is the result of these internal principles.</p><ul><li><strong>Emergent Order</strong>: Complex patterns — like life on Earth or human societies — arise from local interactions of simpler entities (e.g., molecules, cells, individuals). No external “director” is needed to arrange these patterns; they emerge from the system’s own rules and initial conditions.</li><li><strong>Redefining Purpose</strong>: Without a deity orchestrating outcomes, purpose and meaning become matters of <strong>interaction and co-creation</strong>. Humans, for instance, can shape not only their own vectors but also those of other phenomena, forging ethical and existential goals.</li><li><strong>Responsibility and Interdependence</strong>: Recognizing that each vector influences others can deepen our sense of interconnectedness. When we realize our actions or beliefs alter the “vectors” in our social and natural environment, we become more attuned to the collective consequences of our choices.</li><li><strong>Returning to Zero</strong>: The notion that individuals eventually “return to zero” upon death fits a self-contained universe — no higher authority mandates this return; it unfolds from the nature of finite existence itself.</li></ul><h3>6. Possible Critiques and Future Directions</h3><p>Although this vector-based perspective offers a <strong>powerful metaphor</strong> for understanding reality, it also raises questions and objections:</p><ol><li><strong>Abstraction vs. Lived Experience</strong>: While abstract models help conceptualize complexities, some may argue they lack the texture and nuance of lived, subjective human experience — love, art, spirituality, etc.</li><li><strong>Determinism vs. Freedom</strong>: If all phenomena are vectors constrained by mathematical laws, do we have genuine freedom, or is everything predetermined by the initial conditions and the structure of the space?</li><li><strong>Ethical Foundations</strong>: Without a transcendent moral authority, where do moral norms come from? Is ethical reasoning just another “vector” in a system, or is there a more objective grounding?</li><li><strong>Interpretation of Death</strong>: Seeing death as a return to a “zero set” might be comforting to some, but others could find it abstract. There is ongoing debate about whether a purely physicalist view of death captures the totality of human consciousness and subjective experience.</li></ol><p>Nevertheless, these challenges also represent frontiers for exploration — be it in philosophy of mind, ethics, or theoretical physics.</p><h3>Conclusion</h3><p>The idea of <strong>reality as a multidimensional vector space</strong> offers a compelling, coherent model for understanding how phenomena arise, interact, and evolve — <strong>all without invoking a controlling deity</strong>. From the macrocosm of galaxies to the microcosm of human relationships, every entity or event can be seen as a point in a vast algebraic tapestry. Transformations and interactions, akin to vector addition or rotation, shape both individual entities and the collective universe.</p><p>Crucially, <strong>death</strong> within this system can be viewed as a vector’s reabsorption into a foundational “zero set,” symbolizing our return to the baseline of existence from which we originally emerged. This vision underscores the <strong>self-organizing</strong> and <strong>lawful</strong> nature of our cosmos: phenomena follow consistent patterns, and the resulting emergent order is neither accidental nor the product of divine intervention. It flows naturally from the interplay of vectors in a space defined by the foundational properties of reality itself. In embracing such a worldview, we place ourselves squarely within the system rather than outside it, challenging us to see our actions, our relationships, and our pursuit of meaning as deeply woven into the very fabric of existence — and ultimately leading us, in time, back to the set of zero.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23510efd0833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Options Pattern in Rust]]></title>
            <link>https://medium.com/@omid.jn/options-pattern-in-rust-6425520b2b23?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/6425520b2b23</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 16:38:49 GMT</pubDate>
            <atom:updated>2023-12-26T16:38:49.076Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, the “options pattern” for function parameters is a common idiom used to provide flexibility and configurability to functions by accepting functional options as arguments. This is often implemented using functional options as arguments, which are functions that modify a configuration object passed to the main function.</p><p>In Rust, you can achieve a similar effect using the builder pattern or by using structs with default values. Here’s an example of how you might implement a similar pattern in Rust:</p><pre>// Define a struct with default values<br>pub struct Config {<br>    pub option1: bool,<br>    pub option2: i32,<br>    // Add more options as needed<br>}<br><br>impl Config {<br>    // A method to create a new Config with default values<br>    pub fn new() -&gt; Config {<br>        Config {<br>            option1: false,<br>            option2: 42,<br>            // Initialize other options with their default values<br>        }<br>    }<br><br>    // Methods to set individual options and return a modified Config<br>    pub fn option1(mut self, value: bool) -&gt; Config {<br>        self.option1 = value;<br>        self<br>    }<br><br>    pub fn option2(mut self, value: i32) -&gt; Config {<br>        self.option2 = value;<br>        self<br>    }<br>    // Add more methods for other options as needed<br>}<br><br>// The main function that takes a Config as a parameter<br>pub fn my_function(config: Config) {<br>    // Use config.option1, config.option2, etc.<br>    println!(&quot;Option 1: {}&quot;, config.option1);<br>    println!(&quot;Option 2: {}&quot;, config.option2);<br>    // Use other options as needed<br>}<br><br>fn main() {<br>    // Use the builder pattern to set options<br>    let config = Config::new().option1(true).option2(100);<br>    <br>    // Pass the configured object to the function<br>    my_function(config);<br>}</pre><p>In this example, the Config struct serves as a configuration object, and the new method creates an instance with default values. The builder pattern is then used to set specific options before passing the configured object to the main function.</p><p>You can expand on this pattern by adding more options to the Config struct and corresponding methods to set those options in a fluent manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6425520b2b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not Using PureComponent or Memo]]></title>
            <link>https://medium.com/@omid.jn/not-using-purecomponent-or-memo-5621a3613ef8?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/5621a3613ef8</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pitfalls]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 12:41:20 GMT</pubDate>
            <atom:updated>2023-11-05T12:41:20.833Z</atom:updated>
            <content:encoded><![CDATA[<p>The “Not Using PureComponent or Memo” pitfall in React refers to the situation where you do not optimize your components to prevent unnecessary renders. React components, by default, re-render whenever their parent component re-renders, even if the component’s props haven’t changed. This can lead to performance issues, especially in larger applications. To mitigate this pitfall, you can use PureComponent or the React.memo higher-order component to optimize your components.</p><pre>class UserProfile extends React.Component {<br>  render() {<br>    return &lt;div&gt;User Profile: {this.props.user.name}&lt;/div&gt;;<br>  }<br>}<br><br>class App extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { user: { name: &#39;Alice&#39; } };<br>  }<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;UserProfile user={this.state.user} /&gt;<br>        &lt;button onClick={this.updateUser}&gt;Update User&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  updateUser = () =&gt; {<br>    const newUser = { name: &#39;Bob&#39; };<br>    this.setState({ user: newUser });<br>  };<br>}</pre><p>In this example, even when clicking the “Update User” button, the UserProfile component re-renders even though the user prop didn&#39;t change. This can be inefficient, especially in complex components.</p><h3>Solution: Using PureComponent or React.memo</h3><h4>Using PureComponent:</h4><pre>class UserProfile extends React.PureComponent {<br>  render() {<br>    return &lt;div&gt;User Profile: {this.props.user.name}&lt;/div&gt;;<br>  }<br>}</pre><p>With PureComponent, the UserProfile component will only re-render if its props or state have changed, preventing unnecessary renders.</p><h4>Using React.memo:</h4><pre>const UserProfile = React.memo(({ user }) =&gt; {<br>  return &lt;div&gt;User Profile: {user.name}&lt;/div&gt;;<br>});</pre><p>React.memo is a higher-order component that works similarly to PureComponent but can be applied to functional components.</p><p>By using PureComponent for class components or React.memo for functional components, you can optimize your React application to reduce unnecessary re-renders and improve performance. Always consider whether a component should re-render based on its props and state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5621a3613ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State Mutations pitfall]]></title>
            <link>https://medium.com/@omid.jn/react-state-mutations-pitfall-b885ae364d8c?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/b885ae364d8c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 12:27:52 GMT</pubDate>
            <atom:updated>2023-11-05T12:27:52.150Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>State Mutations</strong></h3><p>The “State Mutations” pitfall in React occurs when developers directly modify the state object, which can lead to unexpected behavior and bugs in your application. React relies on immutability to efficiently update the DOM and manage component re-renders. When you mutate the state directly, React might not detect the changes correctly, leading to inconsistencies in your UI. Here’s an example to illustrate this pitfall and how to avoid it:</p><pre>class Counter extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      count: 0,<br>    };<br>  }<br><br>  increment() {<br>    // Directly mutating state, which is a pitfall<br>    this.state.count++;<br>    this.setState({ count: this.state.count }); // Incorrect way to update state<br>  }<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>        &lt;button onClick={() =&gt; this.increment()}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>In this example, the increment method directly modifies the count property of the state, which is a mutation and should be avoided.</p><h3>Solution: Using setState Correctly</h3><p>To avoid state mutations, use the setState method correctly. Either pass an object with the updated state properties or use the functional form of setState when the new state depends on the previous state.</p><p>Using Object Form:</p><pre>increment() {<br>  // Using object form of setState to update state correctly<br>  this.setState({ count: this.state.count + 1 });<br>}</pre><p>Using Functional Form:</p><pre>increment() {<br>  // Using functional form of setState when the new state depends on the previous state<br>  this.setState((prevState) =&gt; {<br>    return { count: prevState.count + 1 };<br>  });<br>}</pre><p>By using setState correctly, you ensure that React manages state changes appropriately, leading to a more predictable and reliable application behavior. Always follow the principle of immutability to avoid unexpected side effects in your React components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b885ae364d8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Example of Key Generation, Encryption, and Decryption In RSA]]></title>
            <link>https://medium.com/@omid.jn/example-of-key-generation-encryption-and-decryption-in-rsa-547b2e854828?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/547b2e854828</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[rsa]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 17:37:50 GMT</pubDate>
            <atom:updated>2023-10-17T17:37:50.806Z</atom:updated>
            <content:encoded><![CDATA[<p>The following example illustrates RSA&#39;s key generation, encryption, and decryption process using small numbers for simplicity. Let’s go through the steps in detail:</p><h3><strong>Key Generation</strong>:</h3><ol><li>Select two prime numbers:</li></ol><ul><li>p = 3</li><li>q = 11</li></ul><p>2. Calculate n and φ(n):</p><ul><li>n = p * q = 3 * 11 = 33</li><li>φ(n) = (p — 1)(q — 1) = (3–1)(11–1) = 2 * 10 = 20</li></ul><blockquote>Euler’s Totient function, often denoted as φ(n) (phi of n), is a mathematical function that counts the number of positive integers less than or equal to n that are relatively prime to n. In other words, it calculates the number of positive integers that have no common factors (other than 1) with n. Euler’s Totient function is a fundamental concept in number theory and plays a crucial role in various mathematical and cryptographic applications, including RSA encryption.</blockquote><blockquote>The formula for Euler’s Totient function is as follows:</blockquote><blockquote>φ(n) = (p-1)(q-1)</blockquote><blockquote>Where:</blockquote><blockquote>1) n is a positive integer, typically the product of two distinct prime numbers, p and q.<br>2) p and q are prime factors of n.</blockquote><blockquote>The key idea is that when n is a product of two prime numbers, as is often the case in RSA encryption, φ(n) measures the number of positive integers [<strong>computational problem</strong>] that are coprime to n, and this value is used in various cryptographic calculations.</blockquote><p>3. Choose a <strong>public</strong> exponent (e):</p><ul><li>e = 3 (a <strong><em>common choice</em></strong>, ensuring it is coprime to φ(n))</li><li>The <em>public key is pair (n, e) = (33, 3)</em>.</li></ul><p>4. Calculate the <strong><em>private</em></strong> exponent (d):</p><ul><li>Use the equation d ≡ e⁻¹ (mod φ(n)).</li><li>In this case, d ≡ 3⁻¹ (mod 20) ≡ 7 (mod 20). You should use the Extended Euclidean Algorithm or another method to find the modular multiplicative inverse of 3 modulo 20. Here’s the calculation:</li></ul><blockquote>To find the modular multiplicative inverse of 3 modulo 20, you need to find a value “d” such that:<br>(3 * d) % 20 = 1 <br>Using the Extended Euclidean Algorithm, you can find that the modular multiplicative inverse of 3 modulo 20 is indeed 7.<br>3⁻¹ (mod 20) ≡ 7 (mod 20)</blockquote><p>5. <strong>So, the public key is (n, e) = (33, 3), and the private key is (n, d) = (33, 7).</strong></p><h3><strong>Encryption</strong>:</h3><p>6. Alice wants to send a message, m = 5, to Bob using Bob’s public key (n, e).</p><p>7. Alice encrypts the message using the formula C ≡ M^e (mod n):</p><ul><li>C ≡ 5³ (mod 33) = 125 (mod 33) = 26.</li></ul><p>8. Alice sends the encrypted message, C = 26, to Bob.</p><h3>Decryption:</h3><p>9. Bob receives the encrypted message, C = 26, and uses his private key (n, d).</p><p>10. Bob decrypts the message using the formula M ≡ C^d (mod n):</p><ul><li>M ≡ 26⁷ (mod 33) ≡ 8031810176 (mod 33) ≡ 5.</li></ul><p>11. Bob successfully retrieves the plaintext message, which is 5.</p><p>In this example, the message (m = 5) is successfully encrypted, sent, and decrypted using RSA encryption with the provided prime numbers (p and q), public key (n, e), and private key (n, d). This demonstrates the fundamental principles of RSA encryption and decryption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=547b2e854828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Option pattern” in Go]]></title>
            <link>https://medium.com/@omid.jn/the-option-pattern-in-go-9edf55e88320?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/9edf55e88320</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[golan]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 22:36:17 GMT</pubDate>
            <atom:updated>2023-09-10T22:36:17.689Z</atom:updated>
            <content:encoded><![CDATA[<p>The “Option pattern” in Go is a design pattern used to manage optional parameters in a clean and flexible way when defining functions or methods. It’s particularly useful when a function has many parameters, most of which have reasonable default values, and you want to provide a more user-friendly and expressive API for callers.</p><p>In Go, this pattern is often implemented using <strong>functional options</strong> or <strong>configuration structs</strong>. Let’s explore both approaches:</p><ol><li><strong>Functional Options</strong>: In this approach, you define functions that accept functional options as arguments. Each option function modifies some aspect of an object or configuration</li></ol><pre>package mypackage<br><br>type MyService struct {<br>    // Fields representing various configuration options<br>    Timeout     time.Duration<br>    MaxRetries  int<br>    EnableCache bool<br>}<br><br>type Option func(*MyService)<br><br>// Option functions to configure the service<br>func WithTimeout(timeout time.Duration) Option {<br>    return func(s *MyService) {<br>        s.Timeout = timeout<br>    }<br>}<br><br>func WithMaxRetries(maxRetries int) Option {<br>    return func(s *MyService) {<br>        s.MaxRetries = maxRetries<br>    }<br>}<br><br>func WithCacheEnabled(enableCache bool) Option {<br>    return func(s *MyService) {<br>        s.EnableCache = enableCache<br>    }<br>}<br><br>// NewMyService creates a new MyService instance with options<br>func NewMyService(options ...Option) *MyService {<br>    // Default configuration<br>    svc := &amp;MyService{<br>        Timeout:     5 * time.Second,<br>        MaxRetries:  3,<br>        EnableCache: true,<br>    }<br><br>    // Apply provided options<br>    for _, option := range options {<br>        option(svc)<br>    }<br><br>    return svc<br>}</pre><p>Using the functional options, clients can create an instance of MyService with only the configuration they care about:</p><pre>// Creating a MyService instance with custom options<br>service := NewMyService(<br>    WithTimeout(10 * time.Second),<br>    WithMaxRetries(5),<br>)<br><br>// Creating a MyService instance with default options<br>defaultService := NewMyService()</pre><p>2. <strong>Configuration Struct</strong>: Another approach is to use a configuration struct where you set fields to configure the behavior of an object.</p><pre>package mypackage<br><br>type MyServiceConfig struct {<br>    Timeout     time.Duration<br>    MaxRetries  int<br>    EnableCache bool<br>}<br><br>type MyService struct {<br>    // Fields representing various configuration options<br>    config MyServiceConfig<br>}<br><br>// NewMyService creates a new MyService instance with the provided configuration<br>func NewMyService(config MyServiceConfig) *MyService {<br>    // Apply default values if not provided<br>    if config.Timeout == 0 {<br>        config.Timeout = 5 * time.Second<br>    }<br>    if config.MaxRetries == 0 {<br>        config.MaxRetries = 3<br>    }<br><br>    return &amp;MyService{config}<br>}</pre><p>Clients can create an instance of MyService by initializing a MyServiceConfig struct with the desired options:</p><pre>// Creating a MyService instance with custom configuration<br>customConfig := MyServiceConfig{<br>    Timeout:     10 * time.Second,<br>    MaxRetries:  5,<br>}<br>service := NewMyService(customConfig)<br><br>// Creating a MyService instance with default configuration<br>defaultConfig := MyServiceConfig{}<br>defaultService := NewMyService(defaultConfig)</pre><p>The option pattern in Go gives you flexibility in configuring objects and functions while keeping the code clean and maintainable. You can choose the approach that best fits your project’s requirements and coding style.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9edf55e88320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First-Class Functions in Go]]></title>
            <link>https://medium.com/@omid.jn/first-class-functions-in-go-4056edaab26d?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/4056edaab26d</guid>
            <category><![CDATA[first-class-function]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 22:25:16 GMT</pubDate>
            <atom:updated>2023-09-10T22:25:16.474Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, functions are first-class citizens, which means they are treated as first-class values and can be used in the same way as other types such as integers, strings, or structs. This feature provides flexibility and allows you to work with functions in various ways. Here are some key aspects of first-class functions in Go:</p><ol><li><strong>Functions as Values</strong>: In Go, you can assign functions to variables, pass them as arguments to other functions, and return them as results from functions. This enables you to create higher-order functions that operate on other functions.</li></ol><pre>func add(a, b int) int {<br>    return a + b<br>}<br><br>func subtract(a, b int) int {<br>    return a - b<br>}<br><br>// Function as a variable<br>var operation func(int, int) int<br>operation = add<br>result := operation(5, 3) // result is 8<br><br>// Function as a parameter<br>func calculate(op func(int, int) int, x, y int) int {<br>    return op(x, y)<br>}<br><br>addResult := calculate(add, 5, 3)       // addResult is 8<br>subtractResult := calculate(subtract, 5, 3) // subtractResult is 2</pre><p>2. <strong>Function Literals (Closures)</strong>: You can define anonymous functions, also known as function literals or closures, in Go. These functions can capture and use variables from their surrounding lexical scope.</p><pre>func main() {<br>    x := 10<br><br>    // Function literal<br>    add := func(y int) int {<br>        return x + y<br>    }<br><br>    result := add(5) // result is 15 (captures the variable x)<br>}</pre><p>3. <strong>Functions as Types</strong>: You can declare custom types based on functions. This can be useful for enhancing code readability and providing clarity when working with complex function signatures.</p><pre>type BinaryOperation func(int, int) int<br><br>func add(a, b int) int {<br>    return a + b<br>}<br><br>func subtract(a, b int) int {<br>    return a - b<br>}<br><br>func calculate(op BinaryOperation, x, y int) int {<br>    return op(x, y)<br>}<br><br>result := calculate(add, 5, 3)       // result is 8<br>result2 := calculate(subtract, 5, 3) // result2 is 2</pre><p><strong>First-class functions in Go</strong> provide the foundation for building flexible and expressive code, enabling <strong>patterns like functional programming and callbacks. They are commonly used in libraries and frameworks for various purposes, including event handling, concurrency, and functional-style operations on collections.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4056edaab26d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang race condition example]]></title>
            <link>https://medium.com/@omid.jn/golang-race-condition-example-2c4bee1e5604?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4bee1e5604</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 22:14:34 GMT</pubDate>
            <atom:updated>2023-09-10T22:14:34.766Z</atom:updated>
            <content:encoded><![CDATA[<p>The following code snippet demonstrates a function called Query that performs a parallel query on multiple database connections and returns the first response it receives. <em>However, there is a potential race condition in the code that can lead to unexpected behavior if the result arrives before the main function has a chance to receive it.</em> To address this issue, you can add a buffer to the channel ch to ensure that the send operation always succeeds, regardless of the order of execution.</p><pre>func Query(conns []Conn, query string) Result {<br>    ch := make(chan Result)<br>    for _, conn := range conns {<br>        go func(c Conn) {<br>            select {<br>            case ch &lt;- c.DoQuery(query):<br>            default:<br>            }<br>        }(conn)<br>    }<br>    return &lt;-ch<br>}</pre><p>let’s dive deeper into the potential race condition in the code.</p><p>In this code:</p><ol><li>The Query function creates a channel ch for receiving results from the database connections.</li><li>It then iterates over a slice of Conn objects (representing database connections) and launches a goroutine for each connection.</li><li>Each goroutine sends the result of executing a database query (c.DoQuery(query)) to the channel ch.</li></ol><p>Now, let’s consider the <strong>potential race condition</strong>:</p><ul><li>The main function expects to receive a result from the channel ch by executing return &lt;-ch.</li><li>However, there is no guarantee about the order in which the goroutines will execute or how quickly they will send their results to the channel.</li><li>If, by chance, one of the goroutines executes its send operation (ch &lt;- c.DoQuery(query)) before the main function reaches return &lt;-ch, the result will be sent to the channel. However, the main function is not yet ready to receive it because it hasn&#39;t reached the &lt;-ch operation.</li><li>This situation <strong>can lead</strong> to a race condition where the result arrives before the main function is prepared to receive it. In such cases, the result <strong>may be</strong> sent to the channel and potentially lost because there is no receiver ready to accept it.</li></ul><p>To address this race condition and ensure that the result is never lost, you can buffer the channel <strong>with a capacity equal to the number of database connections</strong>. This way, even if a result arrives before the main function is ready, it will be stored in the channel until the main function is ready to receive it. This modification guarantees that the first result to arrive will be retrieved regardless of the order of execution. Here’s the updated code for reference:</p><pre>func Query(conns []Conn, query string) Result {<br>    ch := make(chan Result, len(conns)) // Buffer the channel<br>    for _, conn := range conns {<br>        go func(c Conn) {<br>            select {<br>            case ch &lt;- c.DoQuery(query):<br>            default:<br>            }<br>        }(conn)<br>    }<br>    return &lt;-ch<br>}</pre><p>By buffering the channel with a capacity equal to the number of connections, you ensure that all results will be stored temporarily in the channel until the main function is ready to receive them, resolving the race condition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4bee1e5604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang and Cross-Site Scripting (XSS) attacks]]></title>
            <link>https://medium.com/@omid.jn/golang-and-x-content-type-options-e49895c1891a?source=rss-8dcdb3dc2cce------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49895c1891a</guid>
            <category><![CDATA[mime-type-sniffing]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[securejson]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Yumcoder]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 00:25:41 GMT</pubDate>
            <atom:updated>2023-09-10T00:29:42.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s consider an example of a security problem that can occur without the “X-Content-Type-Options” header, leading to a potential security vulnerability known as MIME-type confusion.</p><blockquote><em>Imagine you have a web application that allows users to upload files. Users can upload files with arbitrary extensions, but the server only serves those files with a Content-Type of “application/octet-stream” (binary data) to prevent executing malicious scripts.</em></blockquote><p>Here’s a scenario that can lead to a security issue without the “X-Content-Type-Options” header:</p><p>An attacker uploads a file named “<strong>malicious.html</strong>” with the following content:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Malicious Page&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script&gt;<br>        alert(&quot;This is a malicious script!&quot;);<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>When a user requests the “malicious.html” file from the server, the server sends it with a Content-Type of “application/octet-stream” to prevent it from being interpreted as HTML.</p><p><strong>However, without the “X-Content-Type-Options” header set to “nosniff,” some browsers may ignore the server’s declared content type and attempt to sniff the content themselves.</strong></p><p>In this case, the browser might see that the content appears to be HTML and treat it as such, executing the JavaScript code and displaying the alert. This behavior is known as MIME-type sniffing.</p><p>By setting the “X-Content-Type-Options” header to “nosniff,” <strong>you instruct the browser not to perform this MIME type sniffing and to respect the declared content type, thus preventing the security issue.</strong></p><p>Here’s how you can mitigate this issue with the “X-Content-Type-Options” header in a web application:</p><pre>package main<br><br>import (<br>    &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br>    r := gin.Default()<br><br>    // Middleware to set the X-Content-Type-Options header to &quot;nosniff&quot;<br>    r.Use(func(c *gin.Context) {<br>        c.Header(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;)<br>        c.Next()<br>    })<br><br>    // Serve files with Content-Type &quot;application/octet-stream&quot; (binary data)<br>    r.Static(&quot;/files&quot;, &quot;/path/to/uploaded/files&quot;)<br><br>    r.Run(&quot;:8080&quot;)<br>}</pre><p>By setting “X-Content-Type-Options” to “nosniff,” <strong>you ensure that the browser doesn’t try to interpret files as a different MIME type based on their content, thus mitigating the risk of executing unintended scripts in this scenario.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49895c1891a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>