<?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 Ricardo Gellman on Medium]]></title>
        <description><![CDATA[Stories by Ricardo Gellman on Medium]]></description>
        <link>https://medium.com/@ricardo-gellman?source=rss-fef71fb2c403------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w8uVESBUhLWVjoiG6fRGVg.jpeg</url>
            <title>Stories by Ricardo Gellman on Medium</title>
            <link>https://medium.com/@ricardo-gellman?source=rss-fef71fb2c403------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:02:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricardo-gellman/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[Metamorphic AI Interfaces with Sparql Ontology Graphs]]></title>
            <link>https://ricardo-gellman.medium.com/metamorphic-ai-interfaces-with-sparql-ontology-graphs-91bfabcca09f?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/91bfabcca09f</guid>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[sparql]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 12:27:26 GMT</pubDate>
            <atom:updated>2026-09-27T12:27:26.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine an assistant receiving two questions. The first asks for a short explanation. The second asks how a group of entities is distributed across locations, categories or time. If both answers return as the same block of text, the assistant may be technically correct, but the interface is still semantically blind.</p><p>Responsive design taught applications to adapt to the size of a screen. A Metamorphic UI introduces another kind of adaptation: the interface adapts to the meaning of the answer. A collection can become a table, a geographic relationship can become a map, a small group of structured entities can become cards, and a quantitative comparison can become a chart.</p><p>The transformation does not happen because the user navigates to another page. It happens because the assistant understands the question, retrieves governed evidence and selects the visual representation that best explains the result.</p><p>This is an innovative idea, but it must not become an uncontrolled one. Allowing a language model to invent arbitrary HTML, components and interactions for every response can create inconsistency, accessibility problems and security risks. The model should be able to propose meaning, but deterministic software must decide what is valid.</p><p>In this architecture, the language model proposes. The ontology grounds. SPARQL retrieves. The security layer constrains. The rendering layer transforms the result into a trusted visual component.</p><h3>The Question Is Not Yet a Query</h3><p>A question written in natural language can contain several signals at the same time. It may contain an entity, a relationship, a constraint, a reference to a previous message and even an explicit request such as ?show this on a map.? Before producing a query, the assistant must separate these signals and understand what the user is actually trying to achieve.</p><p>The current question is therefore combined with conversation state and only the relevant parts of the semantic catalog. Recent dialogue can resolve expressions such as ?the same group? those results? or ?now compare them? The catalog contributes ontology vocabulary, aliases, known relationships, valid scopes, rendering policies and a small collection of analogous examples.</p><p>This context should be selective. Sending the complete ontology, every example and every rendering rule to the model on every turn would increase cost while reducing precision. The objective is not to give the model everything. The objective is to give it the smallest amount of knowledge required to interpret the current question correctly.</p><p>The result of this stage is a structured plan. Instead of returning only prose, the planner produces typed fields such as relevance, intent, route, query, requested view and explanation. Missing or malformed fields can then be rejected before any data engine is contacted.</p><p>The simplified idea is:</p><p><strong>Plan = question + useful conversation context + relevant semantic knowledge</strong></p><p>The important detail is that this plan remains a proposal. A deterministic router decides whether the turn should produce a safe response, continue as direct dialogue or execute a governed data request. The language model interprets the meaning, while fixed rules decide what happens next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xDrwitxqqRaouVwq9oLKg.png" /></figure><p>This separation creates an important boundary. A probabilistic component is useful for understanding language, but authorization, query execution and application flow should not depend on an unpredictable decision. The model can suggest a route. The orchestrator must verify it.</p><h3>The Ontology Becomes the Common Language</h3><p>At this point, we must consider where meaning lives. A relational database is excellent at storing records, constraints and transactions, but its tables do not automatically explain the semantic intention of each relationship to an assistant. Column names describe structure. They do not always describe meaning.</p><p>An ontology graph adds this missing layer. The TBox describes the vocabulary of the system: classes, properties and possible relationships. The ABox contains the actual instances and the relationships that exist between them. Together, they create a navigable representation of the domain that can be understood by both software and people.</p><p>The ontology is not a replacement for the operational database. It is a semantic projection of it.</p><p>Imagine a library. The database is the collection of books and records. The ontology is the catalog that explains authors, subjects, editions and relationships. SPARQL is the language used to ask questions through this catalog without needing to know where every record was physically stored.</p><p>To create this graph safely, the publication process should be separated from the online question process. In the offline flow, a schema registry defines the authoritative classes, object relationships, data properties and source provenance. From this registry, a TBox builder produces the ontology declarations, while an ABox extractor converts source records and resolved relationships into instance triples.</p><p>R2RML can be used as a portable and reviewable description of how relational structures correspond to RDF triples. In more complex environments, the executable ABox extractor can also apply resolved semantics that are difficult to express through a static mapping alone. The two mechanisms are therefore complementary: one documents the mapping, while the other performs the live publication.</p><p>The generated ontology and instance triples are then serialized and published into isolated named graphs. One graph stores the ontology and another stores the instance data. A synchronization and verification process compares the source and graph representations, preventing the assistant from reasoning over an outdated or incomplete semantic model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KECMElAQXZn8V7iF2kF7hA.png" /></figure><p>When a user asks a question, the online flow begins. The assistant assembles a compact catalog containing the prompt contract, ontology vocabulary, glossary, live vocabulary, scopes, view policies, routing rules and the most relevant examples. A SPARQL planner translates the interpreted question into a read-only graph pattern.</p><p>Before execution, the query passes through a validator. Only operations such as SELECT and ASK are accepted. Update operations, federation, foreign namespaces and access to graphs outside the permitted module are rejected. Row limits and execution time are also bounded.</p><p>The validated query is evaluated against the published graph, and the variable bindings are normalized into a stable evidence structure. This final step is essential because the presentation layer should not depend directly on the query engine. Whether the evidence was retrieved from a graph engine today or another governed source tomorrow, the agent and renderer can consume the same contract.</p><p>Bringing this to the real world, the ontology becomes more than documentation. It participates in question interpretation, guides valid relationship paths, constrains query generation and contributes semantic information to the rendering decision.</p><h3>From Evidence to a Metamorphic Interface</h3><p>After the graph returns the correct information, another problem begins: how should the answer be shown?</p><p>A traditional chat interface usually renders text and perhaps a generic table. A Metamorphic UI receives a richer evidence vector. This vector can include the explicit request made by the user, the view used in the previous turn, the response type, typed cards, returned columns, semantic properties and row count.</p><p>The rendering decision can then follow a simple principle:</p><p><strong>Chosen view = explicit request; otherwise the best semantic and structural fit</strong></p><p>If the user explicitly asks for a map and the result contains valid geographic semantics, the map receives priority. If the evidence contains a category and a numeric measure, a chart may explain the comparison more effectively. A small number of typed records may become cards. A broad rectangular result remains a table, which also works as the safest fallback.</p><p>This is where ontology and rendering become connected. The renderer should not infer meaning only from column names. A field called location_code, for example, is not enough to guarantee that a map is valid. The semantic catalog can state that the field represents a geographic entity, identify the appropriate layer and define the required viewport or drawing behavior.</p><p>The backend therefore remains authoritative for the selected view. The frontend can make an optimistic prediction while the question is being sent, but the final response carries the validated view_type and any additional rendering metadata. This prevents each client from developing its own interpretation of the same result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKoqbRUzZZfG7Uq2o7u0Ig.png" /></figure><p>The complete flow is protected by a security corridor. Authentication establishes the request boundary. Authorization resolves the active identity, role and permitted capabilities. The query safety gate then confirms that the operation is read-only, scoped to the correct named graph, limited in size and bounded in execution time.</p><p>Inside this corridor, the manager selects exactly one specialized agent. The agent validates the request, executes the query and returns structured evidence containing columns, rows, cards, warnings and timing information. Retry is allowed only for a recoverable planning or validation problem and remains limited. A policy violation is terminal and never becomes another opportunity for the model to negotiate with the security rules.</p><p>The rendering selector then evaluates priority and data shape. An optional visual-hint agent may suggest a map, timeline, chart, list or another supported presentation. However, this suggestion is descriptive, not authoritative. A deterministic renderer verification step checks that all required fields are present and that the proposed visualization can actually be built.</p><p>If a requested chart does not contain a valid measure, the system renders a table. If a map does not contain valid geographic bindings, the system renders a table. The fallback is not a failure. It is the mechanism that keeps the answer truthful and usable.</p><h3>Metamorphic Does Not Mean Random</h3><p>The most important characteristic of this architecture is that the interface changes without becoming unpredictable.</p><p>The language model does not generate a new application for every answer. The frontend owns a registry of trusted components such as tables, maps, cards and charts. Each component has an explicit input contract. The backend selects a supported view and returns evidence in the required shape. The renderer verifies the contract before displaying anything.</p><p>The innovation is therefore not arbitrary interface generation. It is governed visual selection.</p><p>Responsive UI changes the arrangement because the screen changed. Personalized UI changes the content because the user changed. Metamorphic UI changes the representation because the meaning and evidence changed.</p><p>This also creates a more sustainable architecture. When a new concept is added, the ontology describes its relationships, the catalog teaches the planner how to refer to it, the graph publisher exposes its instances and the rendering metadata explains which views are compatible. The chat interface does not need another collection of disconnected conditional statements for every new domain rule.</p><p>The same semantic model supports retrieval and presentation. This reduces the distance between what the assistant understands, what the query retrieves and what the user finally sees.</p><h3>Creating the Architecture</h3><p>The first step is to establish a semantic registry as the source of truth. Every class, property and relationship exposed to the assistant should include provenance back to the operational source. This registry can generate the ontology, guide the ABox extraction, support verification and provide a compact prompt representation.</p><p>The second step is to build a selective catalog. The catalog should not be a long prompt stored in one file. It should separate glossary, scopes, routes, views, ontology paths and examples, allowing the orchestrator to assemble only what is relevant for each turn.</p><p>The third step is to make the planner return a typed contract. Intent, route, query, view and reasoning should be independent fields that can be validated. Free-form prose should explain the plan, not control the application.</p><p>The fourth step is to place a strict read-only validator in front of SPARQL execution. Namespace isolation, named-graph scope, allowed operations, row limits and timeouts must remain deterministic.</p><p>The fifth step is to normalize the result. The renderer should receive evidence, not a database-driver response. Stable columns, rows, typed records, warnings and timing make the downstream agents independent from the retrieval engine.</p><p>Finally, the frontend should implement a finite collection of verified renderers. Every renderer must define the evidence it requires and provide a safe fallback. The model may suggest a visual form, but only deterministic validation should authorize it.</p><p>With this combination, a chat stops being only a place where text is printed. It becomes a semantic interface that can reorganize itself around the nature of the question and the structure of the answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91bfabcca09f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern]]></title>
            <link>https://ricardo-gellman.medium.com/adapter-design-pattern-a9f606f0c1bc?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f606f0c1bc</guid>
            <category><![CDATA[angualr]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[adapter-design-pattern]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 13:54:00 GMT</pubDate>
            <atom:updated>2024-03-30T11:50:11.640Z</atom:updated>
            <content:encoded><![CDATA[<p>How to virtual represent USB to HDMI and USB to DVI connectivity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcD4UzCrsYXm2jdbp7F-ew.png" /></figure><p>What&#39;s the purpose of an Adapter ? Per meaning, a device for connecting pieces of equipment that cannot be connected directly. A bridge that can convert an input to an output, or, multiple inputs into an output.</p><p>In this scenario, I will addressed the need for connectivity between different types of screens and a component in an Angular application.</p><p>First, we introduced the Screen interface, which represents an interfaces to Display itens. This class provides a foundation for screens connectivity, allowing for a consistent communication with the component.</p><pre>interface Screen {<br>  display(): void;<br>}</pre><p>To bridge the gap between the USB interface and the HDMI and DVI interfaces, I created two classes: HDMIScreen and DVIScreen. Both has something in common, they are screen types, so they need to implement the Screen interface.</p><pre>class HDMIScreen implements Screen {<br>  display(): void {<br>    console.log(&#39;This is using HDMI Cable&#39;);<br>  }<br><br>  // HDMI Specific logic<br>}<br><br>class DVIScreen implements Screen {<br><br>  display(): void {<br>    console.log(&#39;This is using DVI Cable&#39;);<br>  }<br><br>  // DVI Specific logic<br>}</pre><p>Despite the variations in screen interfaces, the AdapterUSB remains agnostic of the connection method. Receiving a screen as parameter and displaying it&#39;s content, decoupling between the component and the specific screen implementation. This design promotes flexibility and scalability, as the component can easily integrate screens with USB, HDMI, or DVI connections simply by providing the appropriate adapter parameter.</p><pre>class AdapterUSB {<br>  connect(screen: Screen): void {<br>    screen.display();<br>  }<br>}</pre><p>Now we take two screens with the connectivities HDMI and DVI and connect it to the adapter,</p><pre>const hdmiScreen = new HDMIScreen();<br>const dviScreen = new DVIScreen();<br><br>const adapterUSB = new AdapterUSB();<br><br>// Displaying content<br>adapterUSB.connect(hdmiScreen);<br>adapterUSB.connect(dviScreen);</pre><p>Source: <a href="https://github.com/ameagol/adapterDesignPatternUsbHdmi">https://github.com/ameagol/adapterDesignPatternUsbHdmi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f606f0c1bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saving Children's Life with A.I]]></title>
            <link>https://ricardo-gellman.medium.com/saving-childrens-life-with-a-i-ce05fb634980?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce05fb634980</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 13:11:20 GMT</pubDate>
            <atom:updated>2023-10-05T13:11:20.234Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will mostly present a prototype of a possible comercial or person project that uses A.I and internet of things to save childrens life.</p><p>The basic idea of the project is to map the area around a swimming pool and identify patterns that would be considered risks or dangers for children who come near the water.</p><p>Some of these could be the deep end of the pool, absence of adults, delay in getting out of the water, among others, as well as identifying animals that could also be at risk of drowning, and issuing different types of alerts, such as warnings on cell phones, sound signals such as sirens, and even automatic activation of emergency services and firefighters.</p><p>As we are dealing with the analysis of moving images, we need hardware with greater processing capacity, so we either need a computer compiling and analyzing the images or a Raspberry PI module with Wi-Fi, connected to a siren, a fixed camera for the pool and a power point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oE-L64EqbgJpoy6QgtsUoQ.png" /></figure><p>The detection ML model is based on Ultranalytics’ YOLOv5, which is capable of detecting a wide range of different objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuQuWnHVjZNLFgS_tkcAnw.png" /></figure><p>For the IOT Module, you should buy the Rasp Pi kit + Cam + speaker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*AguSP2p8iEntVgOKVkiwxQ.png" /></figure><p>and you can start testing with the code below:</p><pre>import cv2<br>import math<br>from pathlib import Path<br>from yolov8.models.experimental import attempt_load<br>from yolov8.utils.datasets import LoadStreams<br>from yolov8.utils.general import check_img_size, non_max_suppression, scale_coords<br>from yolov8.utils.plots import Annotator, colors<br>from yolov8.utils.torch_utils import select_device<br>import torch<br><br># Set your YOLO model weights path<br>weights_path = &#39;path/to/your/yolov8n.pt&#39;<br><br># Set your class names<br>classNames = [&quot;kid&quot;, &quot;bicycle&quot;, &quot;car&quot;, &quot;motorbike&quot;, &quot;aeroplane&quot;, &quot;bus&quot;, &quot;train&quot;, &quot;truck&quot;, &quot;boat&quot;,<br>              &quot;traffic light&quot;, &quot;fire hydrant&quot;, &quot;stop sign&quot;, &quot;parking meter&quot;, &quot;bench&quot;, &quot;bird&quot;, &quot;cat&quot;,<br>              &quot;dog&quot;, &quot;horse&quot;, &quot;sheep&quot;, &quot;cow&quot;, &quot;elephant&quot;, &quot;bear&quot;, &quot;zebra&quot;, &quot;giraffe&quot;, &quot;backpack&quot;, &quot;umbrella&quot;,<br>              &quot;handbag&quot;, &quot;tie&quot;, &quot;suitcase&quot;, &quot;frisbee&quot;, &quot;skis&quot;, &quot;snowboard&quot;, &quot;sports ball&quot;, &quot;kite&quot;, &quot;baseball bat&quot;,<br>              &quot;baseball glove&quot;, &quot;skateboard&quot;, &quot;surfboard&quot;, &quot;tennis racket&quot;, &quot;bottle&quot;, &quot;wine glass&quot;, &quot;cup&quot;,<br>              &quot;fork&quot;, &quot;knife&quot;, &quot;spoon&quot;, &quot;bowl&quot;, &quot;banana&quot;, &quot;apple&quot;, &quot;sandwich&quot;, &quot;orange&quot;, &quot;broccoli&quot;,<br>              &quot;carrot&quot;, &quot;hot dog&quot;, &quot;pizza&quot;, &quot;donut&quot;, &quot;cake&quot;, &quot;chair&quot;, &quot;sofa&quot;, &quot;pottedplant&quot;, &quot;bed&quot;,<br>              &quot;diningtable&quot;, &quot;toilet&quot;, &quot;tvmonitor&quot;, &quot;laptop&quot;, &quot;mouse&quot;, &quot;remote&quot;, &quot;keyboard&quot;, &quot;cell phone&quot;,<br>              &quot;microwave&quot;, &quot;oven&quot;, &quot;toaster&quot;, &quot;sink&quot;, &quot;refrigerator&quot;, &quot;book&quot;, &quot;clock&quot;, &quot;vase&quot;, &quot;scissors&quot;,<br>              &quot;teddy bear&quot;, &quot;hair drier&quot;, &quot;toothbrush&quot;]<br><br># Initialize the YOLO model<br>device = select_device()<br>model = attempt_load(weights_path, map_location=device)<br>imgsz = check_img_size(640, s=model.stride.max())<br><br># Start webCam<br>cap = cv2.VideoCapture(0)<br><br># Use for local tests<br># video_path = &#39;/path/to/your/video/KIDS3.mp4&#39;<br># cap = cv2.VideoCapture(video_path)<br><br>while True:<br>    ret, img0 = cap.read()<br>    if not ret:<br>        break<br><br>    img = img0.copy()<br><br>    # Preprocess the image<br>    img = torch.from_numpy(img).to(device)<br>    img = img.float()<br>    img /= 255.0<br>    if img.ndimension() == 3:<br>        img = img.unsqueeze(0)<br><br>    # Get detections<br>    pred = model(img, augment=False)[0]<br>    pred = non_max_suppression(pred, conf_thres=0.25, iou_thres=0.45)<br><br>    annotator = Annotator(imgsz, line_thickness=3)<br>    if pred[0] is not None:<br>        detections = pred[0]<br>        detections = scale_coords(img.shape[2:], detections[:, :4], img0.shape).round()<br><br>        for *xyxy, conf, cls in detections:<br>            x1, y1, x2, y2 = map(int, xyxy)<br>            label = f&#39;{classNames[int(cls)]} {conf:.2f}&#39;<br>            color = colors(int(cls))<br>            cv2.rectangle(img0, (x1, y1), (x2, y2), color, 2)<br>            annotator.text((x1, y1), label, color)<br><br>    cv2.imshow(&#39;YOLO&#39;, img0)<br><br>    if cv2.waitKey(1) == ord(&#39;q&#39;):<br>        break<br><br>cap.release()<br>cv2.destroyAllWindows()</pre><p>If you want to use, share, reproduce please use git source <a href="https://github.com/ameagol/kidshero">https://github.com/ameagol/kidshero</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce05fb634980" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking Like a DEV: Chap1]]></title>
            <link>https://ricardo-gellman.medium.com/thinking-like-a-dev-chap1-b2c2b90f5676?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c2b90f5676</guid>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 18:18:47 GMT</pubDate>
            <atom:updated>2023-04-20T18:18:47.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7S0UEbDYVOgWdG6WtaG9cw.png" /></figure><p>A visual way to exemplify how to think before code</p><p>Thinking like a DEV isn’t something you’re born knowing, and like everything else, it’s a matter of exercise, coffee and many insomnia nights.</p><p>In order to help you sleep better, I decided to create some chapters that will give some important and basic examples of how to think like a DEV, following to main principles. Think Logical but Think simpler!</p><p>Let&#39;s take a dummy example:</p><p>Remove Duplicate entries for the string below:</p><pre>String removeDuplicates = &quot;AAabcdBBeffghijkAAalmnOOpp&quot;;</pre><p>In a real world, a similar example would be setting up a dining table.</p><p>By taking all tableware and thinking logically but not simpler, you could:</p><ul><li>sort the elements</li><li>group by type.</li><li>traverse each group</li><li>take only one of each group</li><li>put each group element traversed, beside the plate, like in image below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzXgK3GvgqHiLWiY_9ME_A.png" /></figure><p>As a DEV Always ask yourself, is there any simpler and objective way to achieve the same result ?</p><p>What if we could traverse the array and put each item in a place that do not accept duplicates, and in case you do it, the last element would be replaced by the current element ?</p><p>In software we have it, called hash table, or collections that only accept a single Key for each Value!</p><p>Knowing that, you start thinking logically and also simpler!</p><ul><li>Traverse the array</li><li>Add each element as a key of a hash table</li><li>Clone the hash table and put each beside plate</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NS-fkaEVBkD1RJ0GCEDJA.png" /></figure><p>Now lets get back the string solution and implement it.<br>Consider like A = Big Spoon, and a = small spoon :)</p><pre>import java.io.*;<br>import java.util.HashSet;<br>public class MyClass {<br>    public static void main(String args[]) {<br>      <br>      String removeDuplicates = &quot;AAabcdBBeffghijkAAalmnOOpp&quot;;<br>      <br>      HashSet&lt;Character&gt; hashTable = new HashSet&lt;Character&gt;();<br><br>        removeDuplicates<br>            .chars()<br>                .mapToObj(i -&gt; (char)i)<br>                    .forEach(i -&gt; hashTable.add(i));<br>            <br>        System.out.println(hashTable);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*wuBNp32hBY-UgcY2oOlY7Q.png" /></figure><p>thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c2b90f5676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say goodbye for [ifs-elses-ifs] with command design pattern]]></title>
            <link>https://ricardo-gellman.medium.com/say-goodbye-for-ifs-elses-ifs-with-command-design-pattern-19da965049e1?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/19da965049e1</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[commander]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 20:12:53 GMT</pubDate>
            <atom:updated>2023-02-21T17:10:14.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fapwVT1klsOcE7kA.png" /></figure><p>in this article I will try to be as brief and objective as possible, and explain in a clear and convincing way how important the use of design patterns is for a clean, reusable and easy to maintain code</p><p>To exemplify, I’ll start with redundant code, not clean and difficult to maintain. Redundant because some strings could be externalized in variables, not clean because as it grows it will require a refactoring by service types, otherwise we will have database documents mixed with A.I documents, DevOps etc. And finally, difficult to maintain, because if URLs change, it will be necessary to adjust multiple lines of code, and the problem rate will increase significantly</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        String cloudProvider = &quot;gcp&quot;;<br>        String serviceProvider = &quot;vertex&quot;;<br><br>        String cloudData = getCloudData(cloudProvider, serviceProvider);<br>        <br>        // Here you define the code of your command execution<br>        wget cloudData<br>    }<br><br>    // Obtain the cloud docs based in Provider and service<br>    public static String getCloudData(String cloudProvider, String serviceProvider){<br>        if(cloudProvider.equals(&quot;aws&quot;)){<br>            if(serviceProvider.equals(&quot;lambda&quot;)){<br>                return &quot;https://docs.aws.amazon.com/lambda&quot;;<br>            } else if (serviceProvider.equals(&quot;sqs&quot;)){<br>                return &quot;https://docs.aws.amazon.com/sqs&quot;;<br>            }<br>        }else if(cloudProvider.equals(&quot;azzure&quot;)){<br>            if(serviceProvider.equals(&quot;bot&quot;)){<br>                return &quot;https://azure.microsoft.com/products/bot-services/&quot;;<br>            } else if (serviceProvider.equals(&quot;bastion&quot;)){<br>                return &quot;https://azure.microsoft.com/services/azure-bastion/&quot;;<br>            } <br>        }else if(cloudProvider.equals(&quot;gcp&quot;)){<br>            if(serviceProvider.equals(&quot;vertex&quot;)){<br>                return &quot;https://cloud.google.com/vertex-ai&quot;;<br>            } else if (serviceProvider.equals(&quot;dialogflow&quot;)){<br>                return &quot;https://cloud.google.com/dialogflow&quot;;<br>            } <br>        }<br>        return null;<br>    }<br>}j</pre><p>Before we implement the solution with the Command design pattern (some also consider a Rules Design Pattern + command), let’s separate the code into parts.</p><ul><li>Cloud Provider Groups</li><li>Service Offering Groups</li><li>Documentation source</li><li>URL’s</li></ul><p>Let&#39;s consider the first two groups as generic, as they will be used by more than one implementation, and it can receive as many new clouds as new services as it grows. This means that both will be interfaces to be implemented</p><p>For each of them we will have a validation and a response, and each item of the IF will be an exclusive class, which can be changed, inserted or removed at any time, without any impact on the system</p><pre>public interface ICloudProvider {<br>    public boolean detect(String cloud);<br>    public String getProvider();<br>}</pre><pre>public interface IServiceOffering {<br>    public boolean detect(String cloud);<br>    public String getOffering();<br>    public void runCommand(String data);<br>}</pre><p>Each cloud provider and service offering will have its own implementation, based in the interfaces, as an example below. The detect method will receive the string and if detect matches, will resolve with cloud provider</p><pre>public class Amazon implements ICloudProvider {<br>    @Override<br>    public boolean detect(String cloud) {<br>        return cloud.equals(&quot;amazon&quot;);<br>    }<br><br>    @Override<br>    public String getProvider() {<br>        return &quot;https://docs.aws.amazon.com/&quot;;<br>    }<br>}</pre><p>The same for the Services</p><pre>public class Lambda implements IServiceOffering {<br>    @Override<br>    public boolean detect(String service) {<br>        return service.equals(&quot;lambda&quot;);<br>    }<br><br>    @Override<br>    public String getOffering() {<br>        return &quot;/lambda&quot;;<br>    }<br><br>    @Override<br>    public void runCommand(String data) {<br>        aws lambda update-function-code --function-name my-function data --zip-file fileb//my-function.zip<br>    }<br>}</pre><p>And than, set Commander orchestration class</p><pre>public class Commander {<br><br>    private Set&lt;ICloudProvider&gt; cloudProviders = new HashSet&lt;&gt;();<br>    private Set&lt;IServiceOffering&gt; serviceOfferings = new HashSet&lt;&gt;();<br><br>    public void invokeService(String cloud, String service){<br><br>        this.cloudProviders.add(new Amazon());<br>        this.cloudProviders.add(new Google());<br>        this.cloudProviders.add(new Microsoft());<br><br>        serviceOfferings.add(new Bastion());<br>        serviceOfferings.add(new Bot());<br>        serviceOfferings.add(new DialogFlow());<br>        serviceOfferings.add(new Lambda());<br>        serviceOfferings.add(new SQS());<br>        serviceOfferings.add(new Vertex());<br><br>        this.cloudProviders.stream()<br>            .filter( provider -&gt; provider.detect(cloud))<br>            .map(provider -&gt; provider.getProvider())<br>            .findFirst()<br>            .ifPresent(cloudProvider -&gt; this.serviceOfferings.stream()<br>                .filter( serviceOffer -&gt; serviceOffer.detect(service))<br>                .findFirst()<br>                .ifPresent(serviceOffer -&gt; serviceOffer.runCommand(cloudProvider)));<br>    }<br><br>}</pre><p>And your main class will be:</p><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        Commander commander = new Commander();<br>        commander.invokeService(&quot;aws&quot;, &quot;lambda&quot;);<br><br>    }</pre><p>Full code available on <a href="https://github.com/ameagol/command">https://github.com/ameagol/command</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19da965049e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantum Ledger Database (QLDB)]]></title>
            <link>https://ricardo-gellman.medium.com/quantum-ledger-database-qldb-b023a33532?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/b023a33532</guid>
            <category><![CDATA[blockch]]></category>
            <category><![CDATA[ledger]]></category>
            <category><![CDATA[qldb]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[quantum]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Wed, 29 Jun 2022 14:00:52 GMT</pubDate>
            <atom:updated>2022-06-29T14:00:52.583Z</atom:updated>
            <content:encoded><![CDATA[<p>You have probably heard terms like NFTs, DeFi, Quantum, Ledger, BlockChain, Digital Coins and others, but have you ever wondered how they are intrinsically related?</p><p>They are part of a new way to protect, validate and make unique anything that goes through it&#39;s management and control process. A decentralized process.</p><p>Part of this new world is the QLDB, where a new approach to how to store data is presented.</p><p>Thinking about chained related data, ensuring that your new state is securely linked to the previous state, and the entire chain of states can be validated, several proposals were presented.</p><p>The blockchain algorithm is one, where you create a genesis event, with date, initial hash, payload, and generate a hash that will be used as the preview hash of the next event, and thus chaining the data sequence securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*mkrjq9VrHCz2aF6Rz70LjQ.png" /></figure><p>Another aproach, from the persistence perspective is the QLDB. The basic idea behind QLDB consists of three different tables, so to speak, Journal, Current State and Index History.</p><p>The Journal would represent the blockchain concept in a similar way, but containing only the hashes (metadata) of the events, where the persisted hash is generated based on the inserted event, with this unique id equal to zero in the initial event of this chain.</p><p>The current state, which would house the last update information. His idea would be to optimize performance in the search for the most current information.</p><p>The index history, where it would present in chronological order in which the data was entered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kl9IA5vQpPuIVpub.png" /><figcaption>Amazon QLDB Diagram</figcaption></figure><p>Below, is presented a suggestion on how to implement the AWS QLDB straigh forward. For more details, please check references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Pqa5ibnqltNFCsP.png" /><figcaption>Amazon QLDB Simple Implementation proposed by Nikolay Vlasov and Aldred Halim</figcaption></figure><p>Reference: <br><a href="https://aws.amazon.com/pt/blogs/database/use-amazon-qldb-as-an-immutable-key-value-store-with-a-rest-api-and-json/"><em>https://aws.amazon.com/pt/blogs/database/use-amazon-qldb-as-an-immutable-key-value-store-with-a-rest-api-and-json/</em></a></p><p><a href="https://docs.aws.amazon.com/pt_br/qldb/latest/developerguide/what-is.overview.html"><em>https://docs.aws.amazon.com/pt_br/qldb/latest/developerguide/what-is.overview.html</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b023a33532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command Query Responsibility Segregation]]></title>
            <link>https://ricardo-gellman.medium.com/command-query-responsibility-segregation-3d81e6e2031b?source=rss-fef71fb2c403------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d81e6e2031b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Ricardo Gellman]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 13:42:18 GMT</pubDate>
            <atom:updated>2021-04-27T13:42:18.710Z</atom:updated>
            <content:encoded><![CDATA[<p>You are sleeping, no indication of dawn, your phone rings! It’s a voice that says: I need your help! Our environment is slow. Very Slow! This is perhaps the most paradoxical of the problems. It can be simple, it can be Chaos!</p><p>Many systems were born out of ideas and needs created years ago, or even decades ago, where neither performance nor scalability were such important issues to consider. They were! If your solution has a high index of queries, and a volume of concurrent updates in your database, the CQRS architecture standard can become your great ally! Below I present a simplified diagram of the proposal created by Bertrand Meyer and Greg Young</p><p>Imagine a supermarket sales system, where only the branches and the headquarters update information on products for sale, but the whole country consults and actually buys these products. The network that offers the service is the one who infers the command, and the customers, who make the consultations. In this scenario, we can present the architecture in a simplified way with a service that receives data update requests via the command center, and in turn, the data persists on a normalized basis. At the same time it notifies another service that sends an update on another de-normalized base or cache. This database has a higher performance in data delivery and at the same time removes the competitive factor of consultation on the official database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*VNiuXfxEGG6M4jgmAfSEug.png" /></figure><p>Bringing to the real world, I present in a simplified way what would be the embryonic implementation of this architecture. A BFF layer in Node, which receives requests from the command interface and sends it to a Java Spring back End, which persists in a PostgreSQL database and updates the cache base in Elastic Search. This in turn provides the data for the query interface (Query).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*bisDVgGP4f8rEh0tUvX4Hg.png" /></figure><p>At this point, we must consider the combination of this solution with event-oriented architecture, where there is a break in asynchronicity, decoupling the need for the request followed by the response. In this way, we can share information on topics and exchange messages in queues, aiming at unobstructed attendance to requirements, in an organized and orderly manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*FsIOMqEWWxkNH3Tz-j6Dcg.png" /></figure><p>In this architecture we define the topic pattern at the command entry, as it will be responsible for notifying via broadcast, both the normalized base persistence service and the de-normalized base update service. This in turn communicates directly with the cache service, which can in turn be transmitted via the queue pattern communication. Below I demonstrate what this real-world implementation would be like. The Java Service produces an event for Apache Kafka, which in turn replicates the information for consumers who will A. Update the relational database, and B. Post an event in the RabbitMQ queue, which will be consumed by the service integrated with Elastic Search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*K9TpgIg6VeCwBu9-GG5siw.png" /></figure><p>As we love sunny days, but also the winter skies, with lots of CLOUDS, we shall not forget to where we are going. Now I will present how to implement the same solution in an ultra-modern environment on AWS, independent of servers (Servless) and asynchronous management of requirements. The Command is part of a Web Service in S3, triggering a lambda that persists the request in a relational database (normalized) and sends an event to the queue of the SQS Queue service. This in turn is consumed by another servless lambda, which sends the received information to a not normalized repository (DynamoDB NoSQL). This repository is consulted by an independent lambda that performs queries coming from the API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*9lLQd4I4Rk73ul1LtGcDSQ.png" /></figure><p>I hope that this article will bring light to the architecture debate and that everyone will contribute with tips, suggestions and improvements</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d81e6e2031b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>