<?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 TechHara on Medium]]></title>
        <description><![CDATA[Stories by TechHara on Medium]]></description>
        <link>https://medium.com/@techhara?source=rss-8c4660af51b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vAfZLctPZXfBkVcv8RgAEg.jpeg</url>
            <title>Stories by TechHara on Medium</title>
            <link>https://medium.com/@techhara?source=rss-8c4660af51b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techhara/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[When GNU Tools Backfire on macOS: A Debugging Tale]]></title>
            <link>https://medium.com/@techhara/when-gnu-tools-backfire-on-macos-a-debugging-tale-43bb174c8f35?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/43bb174c8f35</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[gnu]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[homebrew]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 16:11:56 GMT</pubDate>
            <atom:updated>2025-12-09T16:11:56.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLQryFluXcxVCrOyZP8k6w.png" /></figure><p>For backend developers, Linux is the de-facto target environment, which means GNU tools are the norm. Many of us develop on macOS because it’s <em>mostly</em> compatible with Linux — close enough that we often forget the differences. Yesterday, I was reminded the hard way that “mostly” is not “always,” and it cost me a few hours of debugging.</p><h3>Issue</h3><p>I was running some tests with gzip and wanted to compile <strong>GNU gzip</strong>, since macOS ships the <strong>BSD</strong> version by default. Oddly enough, compilation failed:</p><pre>$ ./configure<br>$ make -j<br>...<br>ld: multiple errors: archive member &#39;/&#39; not a mach-o file in &#39;libver.a&#39;; archive member &#39;/&#39; not a mach-o file in &#39;lib/libgzip.a&#39;<br>clang: error: linker command failed with exit code 1 (use -v to see invocation)<br>make[2]: *** [Makefile:1981: gzip] Error 1<br>make[1]: *** [Makefile:2110: all-recursive] Error 1<br>make: *** [Makefile:1891: all] Error 2</pre><p>At first, I assumed this was a new macOS compatibility bug in gzip 1.14, similar to an issue I remembered from 1.11. I even drafted an email to bug-gzip@gnu.org. But before sending it, I decided to double-check by trying gzip <strong>1.13</strong>, which had previously built fine for me.</p><p>Surprise: <strong>1.13 failed too</strong> with the exact same error!</p><p>At that point, I knew the problem was on my machine. I grabbed another MacBook, installed only the Xcode command-line tools, ran the same build — and gzip 1.14 compiled perfectly.</p><p>So I compared logs across both systems, eliminating differences: make versions, awk vs gawk, environment variables, everything. The logs eventually matched line-for-line (aside from timestamps and PIDs), yet one system built successfully and the other didn’t.</p><p>Hours passed. The error still made no sense — ar showed nothing wrong with the archive:</p><pre>$ ar -t libver.a<br>version.o</pre><p>But when I tried linking the archive with the exact same command on both machines, one succeeded and one failed.</p><h3>Root Cause</h3><p>The culprit was subtle:<br><strong>my primary development machine was using GNU </strong><strong>ar (from binutils), not macOS’s default </strong><strong>ar.</strong></p><p>This meant:</p><pre>$ which ar<br>/opt/homebrew/opt/binutils/bin/ar</pre><p>When I inspected the archive with GNU ar, everything appeared fine because I had <em>created</em> the archive with that same tool:</p><pre>ar cr libver.a version.o<br>ar -t libver.a<br>version.o</pre><p>But when I inspected the same archive using macOS’s native tool:</p><pre>$ /usr/bin/ar -t libver.a<br>/<br>version.o</pre><p>macOS’s ar revealed an extra stray entry (/)—the exact issue the linker was complaining about. And since ranlib had also been replaced by the GNU version, both tools were generating archives incompatible with macOS’s Mach-O format.</p><p>The fix was simple once I knew:</p><pre>make -j AR=/usr/bin/ar RANLIB=/usr/bin/ranlib</pre><h3>Resolution</h3><p>This works, but obviously it’s not ideal to specify these paths every time. The real underlying issue was that the Homebrew binutils directory appeared <strong>before</strong> /usr/bin in my $PATH, silently overriding macOS’s system tools. What surprised me most was that <strong>GNU binutils output is not compatible with macOS</strong>, even for something as common as building static archives.</p><h3>Conclusion</h3><p>This experience was a strong reminder that macOS is <em>not</em> Linux, and even familiar-looking tools can behave very differently under the hood. Using GNU replacements for system utilities may seem harmless — until they quietly break your toolchain in ways that are hard to diagnose. If you’re doing low-level development or building software that relies on system linker tools, verify which binaries you’re actually using. A single shadowed executable in your $PATH can turn a routine build into an hours-long debugging session.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43bb174c8f35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local LLM Benchmark on Intel Lunar Lake]]></title>
            <link>https://medium.com/@techhara/local-llm-benchmark-on-intel-lunar-lake-133c39f10455?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/133c39f10455</guid>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[intel-lunar-lake]]></category>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 13:39:14 GMT</pubDate>
            <atom:updated>2025-12-07T13:39:14.495Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted to evaluate how Intel’s Lunar Lake performs when running local LLM inference using <a href="https://github.com/ggml-org/llama.cpp">llama.cpp</a>, and compare it against Apple’s M-series Silicon. On Intel hardware, there are three main compute backends to test:</p><ul><li>Vulkan — a cross-platform GPU compute backend.</li><li>SYCL — a C++-based, cross-platform programming model for heterogeneous computing.</li><li>IPEX-LLM — Intel’s optimized PyTorch extension library designed for low-latency LLM inference and fine-tuning on Intel CPUs and GPUs.</li></ul><h3>Apple Silcon</h3><p>To establish a baseline, I first measured Apple’s M-series performance using F16, Q8, and Q4 quantization levels from mistralai/Ministral-3–3B–Instruct–2512–GGUF. The BF16 model was converted to F16 using llama-quantize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dd8m2s8MdCQwmlqWRJ4rig.png" /><figcaption>llama-bench on Apple M2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlphd4Fy_ca9TpZTYPu9IA.png" /><figcaption>llama-bench on Apple M1 Pro</figcaption></figure><h3>Intel Lunar Lake</h3><p>The first run using <strong>Vulkan</strong> delivered underwhelming results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCYUoiXs1ELuH4aRIsncSA.png" /><figcaption>llama-bench on 258v with Vulkan-backend</figcaption></figure><p>When switching to <strong>SYCL</strong>, optimized for F16 (the only available precision options are F16 and F32), I observed a substantial boost in <strong>prompt processing speed (pp or prefill)</strong> compared to Vulkan. However, <strong>token generation (tg)</strong> results were mixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kc4JnHgB2MYfHtFwnlmwCQ.png" /><figcaption>llama-bench on 258v with Sycl-backend</figcaption></figure><p>Finally, I attempted the same test using <strong>IPEX-LLM</strong>, following <a href="https://github.com/intel/ipex-llm/blob/main/docs/mddocs/DockerGuides/docker_cpp_xpu_quickstart.md">Intel’s official guide</a>. Intel provides a precompiled <strong>llama.cpp</strong> binary optimized for IPEX-LLM, but development appears to have stalled — the latest release dates back to April 2025. That version lacks support for newer architectures and models, including Mistral 3, so I was only able to benchmark older ones like <strong>Llama 3</strong>.</p><h3><strong>Take Away</strong></h3><p>Lunar Lake’s integrated GPU (140V) demonstrated impressive <strong>prefill throughput</strong> when compiled with the SYCL backend — roughly <strong>2× faster than the M1 Pro</strong> and nearly on par with the M1 Max. However, <strong>token generation speed</strong> remains disappointing, comparable to the three-year-old M2.</p><p>While Lunar Lake isn’t designed for heavy sustained workloads, it performs decently for <strong>long-prompt, short-response</strong> tasks. For more balanced workloads, Apple’s M-series still offers better overall inference efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133c39f10455" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kickstart AI-AI conversation]]></title>
            <link>https://medium.com/@techhara/kickstart-ai-ai-conversation-107a77d5e983?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/107a77d5e983</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 22:30:24 GMT</pubDate>
            <atom:updated>2025-10-27T22:47:21.934Z</atom:updated>
            <content:encoded><![CDATA[<p>In the era of LLMs and AI agents, I was curious what would happen if we let two AIs converse. Today, let’s build a simple web interface where we let two AIs talk to each other without human intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OlFYbSa_Sq6oAcnfC1tnw.gif" /><figcaption>Two AI’s are talking to each other</figcaption></figure><h3>Requirement</h3><p>We need an LLM server compliant with OpenAI’s /chat/completions <a href="https://platform.openai.com/docs/api-reference/chat">API</a>. One can setup one with <a href="https://github.com/ggml-org/llama.cpp">llama-cpp</a> or <a href="https://ollama.com/">ollama</a>. One can also use OpenAI’s paid model directly — this will cost you a few cents though.</p><h3>Code</h3><p>For the GUI interface, we will use <a href="https://streamlit.io/">streamlit</a> library. Below is a working code. Make sure to edit Model and API configuration section accordingly.</p><pre># app.py<br>&quot;&quot;&quot;<br>Two LLMs Talking – Streamlit App<br>---------------------------------<br>This app sets up an interactive conversation between two language models (&quot;Agent 1&quot; and &quot;Agent 2&quot;)<br>that exchange messages for a configurable number of turns.<br><br>Features:<br>- Editable system prompts for each agent<br>- Adjustable number of conversation turns<br>- Real-time streaming of responses<br>&quot;&quot;&quot;<br><br>import streamlit as st<br>from openai import OpenAI<br><br><br># --- Streamlit page configuration ---<br>st.set_page_config(page_title=&quot;Two LLMs Talking&quot;, layout=&quot;wide&quot;)<br>st.title(&quot;AI-AI Conversation&quot;)<br><br><br># --- Model and API configuration ---<br>BASE_URL = &quot;http://192.168.0.22:8080/v1&quot;  # Server where the model is hosted<br>API_KEY = &quot;no-key&quot;  # Replace if authentication is required<br>MODEL_NAME = &quot;phi4&quot;  # Model ID configured on the server<br><br># Initialize the OpenAI API client<br>client = OpenAI(api_key=API_KEY, base_url=BASE_URL)<br><br><br># --- Sidebar and UI elements ---<br>col1, col2 = st.columns(2)<br><br>with col1:<br>    agent1_system = st.text_area(<br>        &quot;Agent 1 System Prompt&quot;,<br>        (<br>            &quot;You are a curious AI who loves to challenge an idea or thought. &quot;<br>            &quot;Engage in discussion with polite tone but be concise and limit your question to 100 words.&quot;<br>        ),<br>    )<br><br>with col2:<br>    agent2_system = st.text_area(<br>        &quot;Agent 2 System Prompt&quot;,<br>        (<br>            &quot;You are a persuasive AI who loves to convey an idea or thought. &quot;<br>            &quot;Engage in discussion with polite tone but be concise and limit your response to 100 words.&quot;<br>        ),<br>    )<br><br>start_text = st.text_area(<br>    &quot;Initial Message (Agent 1 starts here):&quot;,<br>    &quot;What is the best programming language?&quot;,<br>)<br>num_turns = st.slider(&quot;Number of exchanges:&quot;, 1, 10, 5)<br><br>run_button = st.button(&quot;Start Conversation&quot;)<br><br><br># --- Core logic functions ---<br>def send_message(messages):<br>    &quot;&quot;&quot;<br>    Streams the response from the model based on provided messages.<br><br>    Args:<br>        messages (list[dict]): Chat messages formatted for OpenAI API.<br><br>    Yields:<br>        str: Incremental text chunks during streaming.<br>    &quot;&quot;&quot;<br>    response = client.chat.completions.create(<br>        model=MODEL_NAME,<br>        messages=messages,<br>        stream=True,<br>    )<br><br>    full_reply = &quot;&quot;<br>    for chunk in response:<br>        if chunk.choices:<br>            delta = chunk.choices[0].delta.content<br>            if delta:<br>                full_reply += delta<br>                yield delta<br>    return full_reply<br><br><br>def run_conversation():<br>    &quot;&quot;&quot;<br>    Runs the conversational loop between two agents for a set number of turns.<br>    Alternates between Agent 1 and Agent 2, streaming messages as they are generated.<br>    &quot;&quot;&quot;<br>    # Initialize message histories<br>    msgs_agent1 = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: agent1_system}]<br>    msgs_agent2 = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: agent2_system}]<br><br>    # Starting message: Agent 1 begins the dialogue<br>    st.chat_message(&quot;Q&quot;).markdown(f&quot;:blue[**Agent 1:**] {start_text}&quot;)<br>    message = start_text<br>    current_speaker = 1  # 1 = Agent1 asks, 2 = Agent2 replies<br><br>    for _ in range(num_turns):<br>        if current_speaker == 1:<br>            # Agent 1→Agent 2 turn<br>            msgs_agent2.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message})<br>            full_reply = &quot;&quot;<br>            with st.chat_message(&quot;A&quot;):<br>                placeholder = st.empty()<br>                for delta in send_message(msgs_agent2):<br>                    full_reply += delta<br>                    placeholder.markdown(f&quot;:red[**Agent 2:**] {full_reply}&quot;)<br><br>            msgs_agent2.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: full_reply})<br>            message = full_reply<br>            current_speaker = 2<br><br>        else:<br>            # Agent 2→Agent 1 turn<br>            msgs_agent1.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message})<br>            full_reply = &quot;&quot;<br>            with st.chat_message(&quot;Q&quot;):<br>                placeholder = st.empty()<br>                for delta in send_message(msgs_agent1):<br>                    full_reply += delta<br>                    placeholder.markdown(f&quot;:blue[**Agent 1:**] {full_reply}&quot;)<br><br>            msgs_agent1.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: full_reply})<br>            message = full_reply<br>            current_speaker = 1<br><br><br># --- Run conversation if button clicked ---<br>if run_button:<br>    run_conversation()</pre><p>Most of the code is self-explanatory, but the main idea is to keep two separate messages array for each agent, i.e., msgs_agent1 and msgs_agent2, and feed one’s response as the other’s prompt.</p><p>To run, simply do</p><pre>streamlit run app.py</pre><p>Enjoy watching two LLMs in conservation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=107a77d5e983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Scrolling in Flutter: Synchronized TextFields]]></title>
            <link>https://medium.com/@techhara/advanced-scrolling-in-flutter-synchronized-textfields-fb6d9fae4679?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6d9fae4679</guid>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[textfield]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 16:49:28 GMT</pubDate>
            <atom:updated>2025-06-01T16:49:28.531Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll explore an advanced scrolling technique in Flutter. We’ll build an application featuring two TextField widgets displayed side-by-side. The core functionality will be to automatically synchronize their scrolling: when a user selects text in one TextField, the other will automatically scroll to the position of the same word index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*IfeMDjE2U3bxJRI9nGJnaQ.gif" /><figcaption>the final app we will build</figcaption></figure><h3>The Task: Synchronized Word Scrolling</h3><p>Our goal is to create an app with two TextFields. When a user selects a word in the first TextField, we want the following to happen:</p><ol><li><strong>Identify the selected word’s index:</strong> Determine the position of the selected word within the first TextField&#39;s text.</li><li><strong>Map to the second TextField:</strong> Find the character position of the word at the <em>same index</em> in the second TextField&#39;s content.</li><li><strong>Programmatic Scrolling:</strong> Programmatically scroll the second TextField so that the identified character is centered within its visible area.</li></ol><p>Crucially, this synchronization should be bi-directional: selecting text in the second TextField should likewise scroll the first.</p><h3>Baseline Code: Setting Up the TextFields</h3><p>Let’s begin with the fundamental structure: two TextFields placed side-by-side. To enable our advanced scrolling, we&#39;ll need direct access to each TextField&#39;s TextEditingController, ScrollController, and GlobalKey. We&#39;ll instantiate these and pass them into our TextField widgets.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Scroll Sync&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const MyHomePage(),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  late final TextEditingController _controller1;<br>  late final TextEditingController _controller2;<br><br>  late final ScrollController _scrollController1;<br>  late final ScrollController _scrollController2;<br><br>  final GlobalKey _textFieldKey1 = GlobalKey();<br>  final GlobalKey _textFieldKey2 = GlobalKey();<br><br>  final _padding = 8.0;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _controller1 = TextEditingController(<br>      text:<br>          &quot;1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n&quot;,<br>    );<br>    _controller2 = TextEditingController(<br>      text:<br>          &#39;101 102\n103 104\n105 106\n107 108\n109 110\n111 112\n113 114\n115 116\n117 118\n119 120 121 122 123\n124 125\n126\n127 128 129 130 131 132 133\n134\n135\n136 137\n138 139\n140 141 142\n143 144 145 146\n147 148 149 150\n151 152\n153 154 155\n156 157 158 159 160\n161 162 163 164 165 166 167\n168 169 170 171 172 173\n174 175 176 177 178\n179 180 181\n182 183 184 185\n186 187\n188 189\n190\n191 192 193 194\n195 196 197 198\n199 200 &#39;,<br>    );<br><br>    _scrollController1 = ScrollController();<br>    _scrollController2 = ScrollController();<br>  }<br><br>  @override<br>  void dispose() {<br>    _scrollController1.dispose();<br>    _scrollController2.dispose();<br>    _controller1.dispose();<br>    _controller2.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Row(<br>        children: [<br>          Expanded(<br>            child: TextField(<br>              key: _textFieldKey1,<br>              scrollController: _scrollController1,<br>              controller: _controller1,<br>              maxLines: null,<br>              expands: true,<br>              decoration: InputDecoration(<br>                border: InputBorder.none,<br>                contentPadding: EdgeInsets.all(_padding),<br>              ),<br>            ),<br>          ),<br>          VerticalDivider(color: Colors.black, thickness: 1),<br>          Expanded(<br>            child: TextField(<br>              key: _textFieldKey2,<br>              scrollController: _scrollController2,<br>              controller: _controller2,<br>              maxLines: null,<br>              expands: true,<br>              decoration: InputDecoration(<br>                border: InputBorder.none,<br>                contentPadding: EdgeInsets.all(_padding),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><h3>Word Mapping Logic</h3><p>Next, we need a function to map a character position in one TextField to the corresponding character position in the other. As outlined, we&#39;ll achieve this by determining the word index of the selected text and then finding the start of that same-indexed word in the target TextField.</p><pre><br>int getWordPosition(String text, int charPos) {<br>  final List&lt;String&gt; words = text.substring(0, charPos).split(RegExp(r&#39;\s+&#39;));<br>  return words.isEmpty ? 0 : words.length - 1;<br>}<br><br>int getCharPosition(String text, int wordPos) {<br>  if (text.isEmpty || wordPos == 0) return 0;<br><br>  final pattern = RegExp(r&#39;\s+&#39;);<br>  final matches = pattern.allMatches(text).take(wordPos).toList();<br>  if (matches.length &lt; wordPos) {<br>    return text.length;<br>  }<br><br>  return matches.last.end;<br>}<br><br>int getCorrespondingCharPos(String src, int charPos, String dst) {<br>  final wordPos = getWordPosition(src, charPos);<br>  return getCharPosition(dst, wordPos);<br>}</pre><h3>Calculating Scroll Offset with TextPainter</h3><p>This is the core implementation of the article. To programmatically scroll to a specific character, we need to calculate the exact pixel offset. This requires leveraging Flutter’s lower-level rendering objects: RenderBox and TextPainter. Additionally, we&#39;ll need access to the TextSpan object that TextField uses for rendering. Since TextSpan isn&#39;t directly exposed, we&#39;ll create a custom TextEditingController to cache it whenever buildTextSpan() is called.</p><pre>@@ -49,9 +49,29 @@<br>   State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br> }<br> <br>+class MyTextEditingController extends TextEditingController {<br>+  MyTextEditingController({super.text});<br>+<br>+  TextSpan cacheTextSpan = TextSpan();<br>+<br>+  @override<br>+  TextSpan buildTextSpan({<br>+    required BuildContext context,<br>+    TextStyle? style,<br>+    required bool withComposing,<br>+  }) {<br>+    cacheTextSpan = super.buildTextSpan(<br>+      context: context,<br>+      style: style,<br>+      withComposing: withComposing,<br>+    );<br>+    return cacheTextSpan;<br>+  }<br>+}<br>+<br> class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>-  late final TextEditingController _controller1;<br>-  late final TextEditingController _controller2;<br>+  late final MyTextEditingController _controller1;<br>+  late final MyTextEditingController _controller2;<br> <br>   late final ScrollController _scrollController1;<br>   late final ScrollController _scrollController2;<br>@@ -61,15 +81,47 @@<br> <br>   final _padding = 8.0;<br> <br>+  double _getScrollOffset(<br>+    GlobalKey textFieldKey,<br>+    MyTextEditingController controller,<br>+    int cursorPos,<br>+    ScrollController scrollController,<br>+  ) {<br>+    final textSpan = controller.cacheTextSpan;<br>+<br>+    final TextPainter textPainter = TextPainter(<br>+      text: textSpan,<br>+      textDirection: TextDirection.ltr,<br>+      maxLines: null,<br>+    );<br>+<br>+    final RenderBox renderBox =<br>+        textFieldKey.currentContext!.findRenderObject() as RenderBox;<br>+<br>+    // calculate the width by subtracting 2*padding<br>+    final width = renderBox.size.width - 2 * _padding;<br>+    textPainter.layout(maxWidth: width);<br>+    final TextPosition textPosition = TextPosition(offset: cursorPos);<br>+    final Offset offset = textPainter.getOffsetForCaret(<br>+      textPosition,<br>+      Rect.zero,<br>+    );<br>+<br>+    final double lineHeight = textPainter.preferredLineHeight;<br>+    return offset.dy -<br>+        (scrollController.position.viewportDimension / 2) +<br>+        (lineHeight / 2);<br>+  }<br>+<br>   @override<br>   void initState() {<br>     super.initState();<br> <br>-    _controller1 = TextEditingController(<br>+    _controller1 = MyTextEditingController(<br>       text:<br>           &quot;1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n&quot;,<br>     );<br>-    _controller2 = TextEditingController(<br>+    _controller2 = MyTextEditingController(<br>       text:<br>           &#39;101 102\n103 104\n105 106\n107 108\n109 110\n111 112\n113 114\n115 116\n117 118\n119 120 121 122 123\n124 125\n126\n127 128 129 130 131 132 133\n134\n135\n136 137\n138 139\n140 141 142\n143 144 145 146\n147 148 149 150\n151 152\n153 154 155\n156 157 158 159 160\n161 162 163 164 165 166 167\n168 169 170 171 172 173\n174 175 176 177 178\n179 180 181\n182 183 184 185\n186 187\n188 189\n190\n191 192 193 194\n195 196 197 198\n199 200 &#39;,<br>     );</pre><h3>Adding Listeners for Scroll Synchronization</h3><p>Finally, we’ll attach listeners to each TextField&#39;s controller. Whenever the text selection changes in one TextField, this listener will trigger the calculation of the corresponding scroll offset in the other TextField and then programmatically animate to that position.</p><pre>@@ -128,6 +128,9 @@<br> <br>     _scrollController1 = ScrollController();<br>     _scrollController2 = ScrollController();<br>+<br>+    _controller1.addListener(() =&gt; _scroll(_controller1));<br>+    _controller2.addListener(() =&gt; _scroll(_controller2));<br>   }<br> <br>   @override<br>@@ -139,6 +142,40 @@<br>     super.dispose();<br>   }<br> <br>+  void _scroll(MyTextEditingController srcController) {<br>+    MyTextEditingController controller;<br>+    GlobalKey key;<br>+    ScrollController scrollController;<br>+    if (srcController == _controller1) {<br>+      controller = _controller2;<br>+      key = _textFieldKey2;<br>+      scrollController = _scrollController2;<br>+    } else {<br>+      controller = _controller1;<br>+      key = _textFieldKey1;<br>+      scrollController = _scrollController1;<br>+    }<br>+<br>+    final cursorPos = getCorrespondingCharPos(<br>+      srcController.text,<br>+      srcController.selection.baseOffset,<br>+      controller.text,<br>+    );<br>+    final scrollOffset = _getScrollOffset(<br>+      key,<br>+      controller,<br>+      cursorPos,<br>+      scrollController,<br>+    );<br>+    WidgetsBinding.instance.addPostFrameCallback((_) {<br>+      scrollController.animateTo(<br>+        scrollOffset,<br>+        duration: const Duration(milliseconds: 200),<br>+        curve: Curves.easeOut,<br>+      );<br>+    });<br>+  }<br>+<br>   @override<br>   Widget build(BuildContext context) {<br>     return Scaffold(</pre><h3>Conclusion</h3><p>By combining custom TextEditingControllers, TextPainter for layout calculations, and ScrollControllers for programmatic scrolling, we&#39;ve achieved a sophisticated synchronized scrolling experience in Flutter. This technique can be adapted for various scenarios where precise text position mapping and automated scrolling are required.</p><h3>Completed Code</h3><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Scroll Sync&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const MyHomePage(),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}<br><br>int getWordPosition(String text, int charPos) {<br>  final List&lt;String&gt; words = text.substring(0, charPos).split(RegExp(r&#39;\s+&#39;));<br>  return words.isEmpty ? 0 : words.length - 1;<br>}<br><br>int getCharPosition(String text, int wordPos) {<br>  if (text.isEmpty || wordPos == 0) return 0;<br><br>  final pattern = RegExp(r&#39;\s+&#39;);<br>  final matches = pattern.allMatches(text).take(wordPos).toList();<br>  if (matches.length &lt; wordPos) {<br>    return text.length;<br>  }<br><br>  return matches.last.end;<br>}<br><br>int getCorrespondingCharPos(String src, int charPos, String dst) {<br>  final wordPos = getWordPosition(src, charPos);<br>  return getCharPosition(dst, wordPos);<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class MyTextEditingController extends TextEditingController {<br>  MyTextEditingController({super.text});<br><br>  TextSpan cacheTextSpan = TextSpan();<br><br>  @override<br>  TextSpan buildTextSpan({<br>    required BuildContext context,<br>    TextStyle? style,<br>    required bool withComposing,<br>  }) {<br>    cacheTextSpan = super.buildTextSpan(<br>      context: context,<br>      style: style,<br>      withComposing: withComposing,<br>    );<br>    return cacheTextSpan;<br>  }<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  late final MyTextEditingController _controller1;<br>  late final MyTextEditingController _controller2;<br><br>  late final ScrollController _scrollController1;<br>  late final ScrollController _scrollController2;<br><br>  final GlobalKey _textFieldKey1 = GlobalKey();<br>  final GlobalKey _textFieldKey2 = GlobalKey();<br><br>  final _padding = 8.0;<br><br>  double _getScrollOffset(<br>    GlobalKey textFieldKey,<br>    MyTextEditingController controller,<br>    int cursorPos,<br>    ScrollController scrollController,<br>  ) {<br>    final textSpan = controller.cacheTextSpan;<br><br>    final TextPainter textPainter = TextPainter(<br>      text: textSpan,<br>      textDirection: TextDirection.ltr,<br>      maxLines: null,<br>    );<br><br>    final RenderBox renderBox =<br>        textFieldKey.currentContext!.findRenderObject() as RenderBox;<br><br>    // calculate the width by subtracting 2*padding<br>    final width = renderBox.size.width - 2 * _padding;<br>    textPainter.layout(maxWidth: width);<br>    final TextPosition textPosition = TextPosition(offset: cursorPos);<br>    final Offset offset = textPainter.getOffsetForCaret(<br>      textPosition,<br>      Rect.zero,<br>    );<br><br>    final double lineHeight = textPainter.preferredLineHeight;<br>    return offset.dy -<br>        (scrollController.position.viewportDimension / 2) +<br>        (lineHeight / 2);<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _controller1 = MyTextEditingController(<br>      text:<br>          &quot;1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n&quot;,<br>    );<br>    _controller2 = MyTextEditingController(<br>      text:<br>          &#39;101 102\n103 104\n105 106\n107 108\n109 110\n111 112\n113 114\n115 116\n117 118\n119 120 121 122 123\n124 125\n126\n127 128 129 130 131 132 133\n134\n135\n136 137\n138 139\n140 141 142\n143 144 145 146\n147 148 149 150\n151 152\n153 154 155\n156 157 158 159 160\n161 162 163 164 165 166 167\n168 169 170 171 172 173\n174 175 176 177 178\n179 180 181\n182 183 184 185\n186 187\n188 189\n190\n191 192 193 194\n195 196 197 198\n199 200 &#39;,<br>    );<br><br>    _scrollController1 = ScrollController();<br>    _scrollController2 = ScrollController();<br><br>    _controller1.addListener(() =&gt; _scroll(_controller1));<br>    _controller2.addListener(() =&gt; _scroll(_controller2));<br>  }<br><br>  @override<br>  void dispose() {<br>    _scrollController1.dispose();<br>    _scrollController2.dispose();<br>    _controller1.dispose();<br>    _controller2.dispose();<br>    super.dispose();<br>  }<br><br>  void _scroll(MyTextEditingController srcController) {<br>    MyTextEditingController controller;<br>    GlobalKey key;<br>    ScrollController scrollController;<br>    if (srcController == _controller1) {<br>      controller = _controller2;<br>      key = _textFieldKey2;<br>      scrollController = _scrollController2;<br>    } else {<br>      controller = _controller1;<br>      key = _textFieldKey1;<br>      scrollController = _scrollController1;<br>    }<br><br>    final cursorPos = getCorrespondingCharPos(<br>      srcController.text,<br>      srcController.selection.baseOffset,<br>      controller.text,<br>    );<br>    final scrollOffset = _getScrollOffset(<br>      key,<br>      controller,<br>      cursorPos,<br>      scrollController,<br>    );<br>    WidgetsBinding.instance.addPostFrameCallback((_) {<br>      scrollController.animateTo(<br>        scrollOffset,<br>        duration: const Duration(milliseconds: 200),<br>        curve: Curves.easeOut,<br>      );<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Row(<br>        children: [<br>          Expanded(<br>            child: TextField(<br>              key: _textFieldKey1,<br>              scrollController: _scrollController1,<br>              controller: _controller1,<br>              maxLines: null,<br>              expands: true,<br>              decoration: InputDecoration(<br>                border: InputBorder.none,<br>                contentPadding: EdgeInsets.all(_padding),<br>              ),<br>            ),<br>          ),<br>          VerticalDivider(color: Colors.black, thickness: 1),<br>          Expanded(<br>            child: TextField(<br>              key: _textFieldKey2,<br>              scrollController: _scrollController2,<br>              controller: _controller2,<br>              maxLines: null,<br>              expands: true,<br>              decoration: InputDecoration(<br>                border: InputBorder.none,<br>                contentPadding: EdgeInsets.all(_padding),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6d9fae4679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — TextEditingController deep dive, part 2]]></title>
            <link>https://medium.com/@techhara/flutter-texteditingcontroller-deep-dive-part-2-864a19c3709b?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/864a19c3709b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[textfield]]></category>
            <category><![CDATA[texteditingcontroller]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Mon, 19 May 2025 13:01:46 GMT</pubDate>
            <atom:updated>2025-05-19T13:01:46.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter — advanced TextEditingController usage, part 2</h3><p>In the <a href="https://medium.com/@techhara/flutter-texteditingcontroller-deep-dive-85e280d47b10">previous article</a>, we explored how to use a single TextEditingController to manage a basic TextField. This time, let’s take it up a notch and build an interactive example involving two TextField widgets.</p><h3>🧪 Task Overview</h3><p>We’ll create two side-by-side TextField widgets. When the user selects text in one field, all matching substrings in the other field will be highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ltXjkVVkkKostThRxZQ9XA.gif" /><figcaption>this is what we will build from scratch in this article</figcaption></figure><h3>🏁 Starting Point</h3><p>Here’s the base code that initializes two TextFields:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Text Highlight&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const MyHomePage(),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class HighlightingTextEditingController extends TextEditingController {<br>  HighlightingTextEditingController({super.text});<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  late HighlightingTextEditingController _controller1;<br>  late HighlightingTextEditingController _controller2;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller1 = HighlightingTextEditingController(<br>      text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>    );<br>    _controller2 = HighlightingTextEditingController(<br>      text:<br>          &#39;green is the color of matcha\ngreen is the color of matcha\ngreen is the color of matcha&#39;,<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller1.dispose();<br>    _controller2.dispose();<br>    super.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Row(<br>        children: [<br>          Expanded(<br>            child: TextField(<br>              controller: _controller1,<br>              maxLines: null,<br>              expands: true,<br>            ),<br>          ),<br>          VerticalDivider(color: Colors.black, thickness: 1),<br>          Expanded(<br>            child: TextField(<br>              controller: _controller2,<br>              maxLines: null,<br>              expands: true,<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>At this stage, the TextFields are independent. Let&#39;s walk through how to implement the interaction step by step.</p><h3>Step 1: Keep track of text ranges to be highlighted</h3><p>The first thing we’ll do is to add a field to HighlightingTextEditingController class that keeps track of the text ranges to be highlighted. Let’s also add a highlight color field to be set at construction.</p><pre>@@ -28,7 +28,11 @@<br> }<br> <br> class HighlightingTextEditingController extends TextEditingController {<br>-  HighlightingTextEditingController({super.text});<br>+  HighlightingTextEditingController({super.text, required this.highlightColor})<br>+    : highlightRanges = [];<br>+<br>+  List&lt;TextRange&gt; highlightRanges;<br>+  Color highlightColor;<br> }<br> <br> class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>@@ -40,10 +44,12 @@<br>     super.initState();<br>     _controller1 = HighlightingTextEditingController(<br>       text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>+      highlightColor: Colors.green,<br>     );<br>     _controller2 = HighlightingTextEditingController(<br>       text:<br>           &#39;green is the color of matcha\ngreen is the color of matcha\ngreen is the color of matcha&#39;,<br>+      highlightColor: Colors.amber,<br>     );<br>   }</pre><h3>Step 2: Override buildTextSpan</h3><p>To display highlights, we override buildTextSpan. We iterate through each character and wrap it in a TextSpan, applying background color if the character falls within a highlight range.</p><p>⚠️ Note: This character-level rendering is not performance-optimized. Avoid this approach for large texts in production.</p><pre>@@ -33,6 +33,40 @@<br> <br>   List&lt;TextRange&gt; highlightRanges;<br>   Color highlightColor;<br>+<br>+  bool inHighlightRanges(int ix) {<br>+    return highlightRanges.any((range) =&gt; ix &gt;= range.start &amp;&amp; ix &lt; range.end);<br>+  }<br>+<br>+  @override<br>+  TextSpan buildTextSpan({<br>+    required BuildContext context,<br>+    TextStyle? style,<br>+    required bool withComposing,<br>+  }) {<br>+    if (highlightRanges.isEmpty || text.isEmpty) {<br>+      return super.buildTextSpan(<br>+        context: context,<br>+        style: style,<br>+        withComposing: withComposing,<br>+      );<br>+    }<br>+<br>+    final spans =<br>+        text.characters.indexed.map((e) {<br>+          final ix = e.$1;<br>+          final char = e.$2;<br>+          final inSelection = ix &gt;= selection.start &amp;&amp; ix &lt; selection.end;<br>+          return TextSpan(<br>+            text: char,<br>+            style:<br>+                !inSelection &amp;&amp; inHighlightRanges(ix)<br>+                    ? style?.copyWith(backgroundColor: highlightColor)<br>+                    : style,<br>+          );<br>+        }).toList();<br>+    return TextSpan(children: spans, style: style);<br>+  }<br> }<br> <br> class _MyHomePageState extends State&lt;MyHomePage&gt; {</pre><h3>Step 3: Add Selection Listeners</h3><p>Next, we register listeners on both controllers. When text is selected in one field, we scan the other field for matching substrings and update its highlight ranges.</p><pre>@@ -85,6 +85,13 @@<br>           &#39;green is the color of matcha\ngreen is the color of matcha\ngreen is the color of matcha&#39;,<br>       highlightColor: Colors.amber,<br>     );<br>+<br>+    _controller1.addListener(() {<br>+      _updateHighlightRanges(_controller1, _controller2);<br>+    });<br>+    _controller2.addListener(() {<br>+      _updateHighlightRanges(_controller2, _controller1);<br>+    });<br>   }<br> <br>   @override<br>@@ -94,6 +101,23 @@<br>     super.dispose();<br>   }<br> <br>+  void _updateHighlightRanges(<br>+    HighlightingTextEditingController selectedController,<br>+    HighlightingTextEditingController highlightController,<br>+  ) {<br>+    final selectedText = selectedController.selection.textInside(<br>+      selectedController.text,<br>+    );<br>+    final pattern = RegExp(selectedText);<br>+    final matches = pattern.allMatches(highlightController.text);<br>+    highlightController.highlightRanges.clear();<br>+    for (final match in matches) {<br>+      highlightController.highlightRanges.add(<br>+        TextRange(start: match.start, end: match.end),<br>+      );<br>+    }<br>+  }<br>+<br>   @override<br>   Widget build(BuildContext context) {<br>     return Scaffold(</pre><h3>Step 4: Refresh UI</h3><p>We are almost done. In this step we need to update the UI when selection changes in either of the TextFields. To avoid redundant setState() calls, we store the previous selection string and compare it with the current one. If unchanged, we skip UI updates.</p><pre>@@ -29,10 +29,12 @@<br> <br> class HighlightingTextEditingController extends TextEditingController {<br>   HighlightingTextEditingController({super.text, required this.highlightColor})<br>-    : highlightRanges = [];<br>+    : highlightRanges = [],<br>+      previousSelection = &quot;&quot;;<br> <br>   List&lt;TextRange&gt; highlightRanges;<br>   Color highlightColor;<br>+  String previousSelection;<br> <br>   bool inHighlightRanges(int ix) {<br>     return highlightRanges.any((range) =&gt; ix &gt;= range.start &amp;&amp; ix &lt; range.end);<br>@@ -108,14 +110,21 @@<br>     final selectedText = selectedController.selection.textInside(<br>       selectedController.text,<br>     );<br>-    final pattern = RegExp(selectedText);<br>-    final matches = pattern.allMatches(highlightController.text);<br>-    highlightController.highlightRanges.clear();<br>-    for (final match in matches) {<br>-      highlightController.highlightRanges.add(<br>-        TextRange(start: match.start, end: match.end),<br>-      );<br>-    }<br>+<br>+    if (selectedText == selectedController.previousSelection) return;<br>+<br>+    setState(() {<br>+      selectedController.previousSelection = selectedText;<br>+<br>+      final pattern = RegExp(selectedText);<br>+      final matches = pattern.allMatches(highlightController.text);<br>+      highlightController.highlightRanges.clear();<br>+      for (final match in matches) {<br>+        highlightController.highlightRanges.add(<br>+          TextRange(start: match.start, end: match.end),<br>+        );<br>+      }<br>+    });<br>   }<br> <br>   @override</pre><h3>Step 5: Respect Focus State</h3><p>We don’t want to act on selection changes from an unfocused field. To fix this, we assign a FocusNode to each controller and pass it to buildTextSpan.</p><pre>@@ -28,13 +28,17 @@<br> }<br> <br> class HighlightingTextEditingController extends TextEditingController {<br>-  HighlightingTextEditingController({super.text, required this.highlightColor})<br>-    : highlightRanges = [],<br>-      previousSelection = &quot;&quot;;<br>+  HighlightingTextEditingController({<br>+    super.text,<br>+    required this.highlightColor,<br>+    required this.focusNode,<br>+  }) : highlightRanges = [],<br>+       previousSelection = &quot;&quot;;<br> <br>   List&lt;TextRange&gt; highlightRanges;<br>   Color highlightColor;<br>   String previousSelection;<br>+  FocusNode focusNode;<br> <br>   bool inHighlightRanges(int ix) {<br>     return highlightRanges.any((range) =&gt; ix &gt;= range.start &amp;&amp; ix &lt; range.end);<br>@@ -58,7 +62,8 @@<br>         text.characters.indexed.map((e) {<br>           final ix = e.$1;<br>           final char = e.$2;<br>-          final inSelection = ix &gt;= selection.start &amp;&amp; ix &lt; selection.end;<br>+          final inSelection =<br>+              focusNode.hasFocus &amp;&amp; ix &gt;= selection.start &amp;&amp; ix &lt; selection.end;<br>           return TextSpan(<br>             text: char,<br>             style:<br>@@ -75,17 +80,25 @@<br>   late HighlightingTextEditingController _controller1;<br>   late HighlightingTextEditingController _controller2;<br> <br>+  late FocusNode _focusNode1, _focusNode2;<br>+<br>   @override<br>   void initState() {<br>     super.initState();<br>+<br>+    _focusNode1 = FocusNode();<br>+    _focusNode2 = FocusNode();<br>+<br>     _controller1 = HighlightingTextEditingController(<br>       text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>       highlightColor: Colors.green,<br>+      focusNode: _focusNode1,<br>     );<br>     _controller2 = HighlightingTextEditingController(<br>       text:<br>           &#39;green is the color of matcha\ngreen is the color of matcha\ngreen is the color of matcha&#39;,<br>       highlightColor: Colors.amber,<br>+      focusNode: _focusNode2,<br>     );<br> <br>     _controller1.addListener(() {<br>@@ -100,6 +113,8 @@<br>   void dispose() {<br>     _controller1.dispose();<br>     _controller2.dispose();<br>+    _focusNode1.dispose();<br>+    _focusNode2.dispose();<br>     super.dispose();<br>   }<br> <br>@@ -137,6 +152,7 @@<br>               controller: _controller1,<br>               maxLines: null,<br>               expands: true,<br>+              focusNode: _focusNode1,<br>             ),<br>           ),<br>           VerticalDivider(color: Colors.black, thickness: 1),<br>@@ -145,6 +161,7 @@<br>               controller: _controller2,<br>               maxLines: null,<br>               expands: true,<br>+              focusNode: _focusNode2,<br>             ),<br>           ),<br>         ],</pre><h3>Final code</h3><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Text Highlight&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const MyHomePage(),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class HighlightingTextEditingController extends TextEditingController {<br>  HighlightingTextEditingController({<br>    super.text,<br>    required this.highlightColor,<br>    required this.focusNode,<br>  }) : highlightRanges = [],<br>       previousSelection = &quot;&quot;;<br><br>  List&lt;TextRange&gt; highlightRanges;<br>  Color highlightColor;<br>  String previousSelection;<br>  FocusNode focusNode;<br><br>  bool inHighlightRanges(int ix) {<br>    return highlightRanges.any((range) =&gt; ix &gt;= range.start &amp;&amp; ix &lt; range.end);<br>  }<br><br>  @override<br>  TextSpan buildTextSpan({<br>    required BuildContext context,<br>    TextStyle? style,<br>    required bool withComposing,<br>  }) {<br>    if (highlightRanges.isEmpty || text.isEmpty) {<br>      return super.buildTextSpan(<br>        context: context,<br>        style: style,<br>        withComposing: withComposing,<br>      );<br>    }<br><br>    final spans =<br>        text.characters.indexed.map((e) {<br>          final ix = e.$1;<br>          final char = e.$2;<br>          final inSelection =<br>              focusNode.hasFocus &amp;&amp; ix &gt;= selection.start &amp;&amp; ix &lt; selection.end;<br>          return TextSpan(<br>            text: char,<br>            style:<br>                !inSelection &amp;&amp; inHighlightRanges(ix)<br>                    ? style?.copyWith(backgroundColor: highlightColor)<br>                    : style,<br>          );<br>        }).toList();<br>    return TextSpan(children: spans, style: style);<br>  }<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  late HighlightingTextEditingController _controller1;<br>  late HighlightingTextEditingController _controller2;<br><br>  late FocusNode _focusNode1, _focusNode2;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _focusNode1 = FocusNode();<br>    _focusNode2 = FocusNode();<br><br>    _controller1 = HighlightingTextEditingController(<br>      text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>      highlightColor: Colors.green,<br>      focusNode: _focusNode1,<br>    );<br>    _controller2 = HighlightingTextEditingController(<br>      text:<br>          &#39;green is the color of matcha\ngreen is the color of matcha\ngreen is the color of matcha&#39;,<br>      highlightColor: Colors.amber,<br>      focusNode: _focusNode2,<br>    );<br><br>    _controller1.addListener(() {<br>      _updateHighlightRanges(_controller1, _controller2);<br>    });<br>    _controller2.addListener(() {<br>      _updateHighlightRanges(_controller2, _controller1);<br>    });<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller1.dispose();<br>    _controller2.dispose();<br>    _focusNode1.dispose();<br>    _focusNode2.dispose();<br>    super.dispose();<br>  }<br><br>  void _updateHighlightRanges(<br>    HighlightingTextEditingController selectedController,<br>    HighlightingTextEditingController highlightController,<br>  ) {<br>    final selectedText = selectedController.selection.textInside(<br>      selectedController.text,<br>    );<br><br>    if (selectedText == selectedController.previousSelection) return;<br><br>    setState(() {<br>      selectedController.previousSelection = selectedText;<br><br>      final pattern = RegExp(selectedText);<br>      final matches = pattern.allMatches(highlightController.text);<br>      highlightController.highlightRanges.clear();<br>      for (final match in matches) {<br>        highlightController.highlightRanges.add(<br>          TextRange(start: match.start, end: match.end),<br>        );<br>      }<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Row(<br>        children: [<br>          Expanded(<br>            child: TextField(<br>              controller: _controller1,<br>              maxLines: null,<br>              expands: true,<br>              focusNode: _focusNode1,<br>            ),<br>          ),<br>          VerticalDivider(color: Colors.black, thickness: 1),<br>          Expanded(<br>            child: TextField(<br>              controller: _controller2,<br>              maxLines: null,<br>              expands: true,<br>              focusNode: _focusNode2,<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Alright, hopefully this article has helped you understand how to use a custom TextEditingController for advanced TextField features. Happy Flutter hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=864a19c3709b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — TextEditingController deep dive, part 1]]></title>
            <link>https://medium.com/@techhara/flutter-texteditingcontroller-deep-dive-85e280d47b10?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/85e280d47b10</guid>
            <category><![CDATA[textfield]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[texteditingcontroller]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Sat, 17 May 2025 16:20:20 GMT</pubDate>
            <atom:updated>2025-05-18T15:52:50.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter — advanced TextEditingController usage, part 1</h3><p>Let’s take a deep dive into Flutter’s TextEditingController and unlock advanced text-editing capabilities for your app. In this tutorial, you’ll learn how to highlight all substrings in a TextField that match the user’s current selection — a feature reminiscent of “Find All” in text editors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*BIpMWahg4fkNlf53d-NZbw.gif" /><figcaption>this is what we will implement from scratch</figcaption></figure><h3>Setting up the basics</h3><p>Let’s start with a minimal Flutter app that uses a custom controller:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Text Highlight&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>      ),<br>      home: const MyHomePage(),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class HighlightingTextEditingController extends TextEditingController {<br>  HighlightingTextEditingController({super.text});<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  late HighlightingTextEditingController _controller;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller = HighlightingTextEditingController(<br>      text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    super.dispose();<br>    _controller.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: TextField(controller: _controller, maxLines: null, expands: true),<br>    );<br>  }<br>}</pre><p>At this stage, HighlightingTextEditingController simply extends TextEditingController without adding new behavior.</p><h3>Adding Highlighting Functionality</h3><p>Let’s enhance our controller to support highlighting:</p><p><strong>1. Track Highlight Ranges</strong><br> Add a field to store the list of ranges that should be highlighted.</p><p><strong>2. Override </strong><strong>buildTextSpan</strong><br> Customize text rendering by overriding this method to apply background color to matched ranges (excluding the active selection).</p><p><strong>3. Listen for Selection Changes</strong><br> Whenever the selection changes, search for all matching substrings and update the highlight ranges.</p><p>Here’s how the diff</p><pre>--- before<br>+++ after<br>@@ -27,23 +27,75 @@<br> }<br> <br> class HighlightingTextEditingController extends TextEditingController {<br>-  HighlightingTextEditingController({super.text});<br>+  HighlightingTextEditingController({super.text}) : highlightRanges = [];<br>+<br>+  List&lt;TextRange&gt; highlightRanges;<br>+  final Color highlightColor = Colors.lightGreenAccent;<br>+<br>+  // whether the character at this index is to be highlighted or not<br>+  bool inHighlightRanges(int ix) {<br>+    return highlightRanges.any((range) =&gt; ix &gt;= range.start &amp;&amp; ix &lt; range.end);<br>+  }<br>+<br>+  @override<br>+  TextSpan buildTextSpan({<br>+    required BuildContext context,<br>+    TextStyle? style,<br>+    required bool withComposing,<br>+  }) {<br>+    if (highlightRanges.isEmpty || text.isEmpty) {<br>+      return super.buildTextSpan(<br>+        context: context,<br>+        style: style,<br>+        withComposing: withComposing,<br>+      );<br>+    } else {<br>+      final spans =<br>+          text.characters.indexed.map((e) {<br>+            final ix = e.$1;<br>+            final char = e.$2;<br>+            final inSelection = ix &gt;= selection.start &amp;&amp; ix &lt; selection.end;<br>+            return TextSpan(<br>+              text: char,<br>+              style:<br>+                  !inSelection &amp;&amp; inHighlightRanges(ix)<br>+                      ? style?.copyWith(backgroundColor: highlightColor)<br>+                      : style,<br>+            );<br>+          }).toList();<br>+      return TextSpan(children: spans, style: style);<br>+    }<br>+  }<br> }<br> <br> class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>   late HighlightingTextEditingController _controller;<br> <br>+  void _updateHighlightRanges() {<br>+    final selectedText = _controller.selection.textInside(_controller.text);<br>+    final pattern = RegExp(selectedText);<br>+    final matches = pattern.allMatches(_controller.text);<br>+    _controller.highlightRanges.clear();<br>+    for (final match in matches) {<br>+      _controller.highlightRanges.add(<br>+        TextRange(start: match.start, end: match.end),<br>+      );<br>+    }<br>+  }<br>+<br>   @override<br>   void initState() {<br>     super.initState();<br>     _controller = HighlightingTextEditingController(<br>       text: &#39;matcha is green\nmatcha is green\nmatcha is green&#39;,<br>     );<br>+    _controller.addListener(_updateHighlightRanges);<br>   }<br> <br>   @override<br>   void dispose() {<br>     super.dispose();<br>+    _controller.removeListener(_updateHighlightRanges);<br>     _controller.dispose();<br>   }</pre><h3>Key Takeaways</h3><ul><li>TextEditingController can be subclassed to customize how text is displayed and interacted with in a TextField</li><li>Overriding buildTextSpan gives you fine-grained control over text styling and highlighting</li><li>Always manage listeners and dispose of controllers in the widget lifecycle to prevent memory leaks</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e280d47b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When your Mac is stuttering]]></title>
            <link>https://medium.com/@techhara/when-your-mac-is-stuttering-f41beb087fed?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f41beb087fed</guid>
            <category><![CDATA[ssd]]></category>
            <category><![CDATA[os]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Sat, 17 May 2025 13:02:41 GMT</pubDate>
            <atom:updated>2025-05-17T13:02:41.887Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a MacBook Air with the M2 chip. When I first got it, it was incredibly fast, but over time I noticed it started to stutter-even during simple tasks like playing YouTube videos. At first, I suspected Safari was the problem, so I tried Firefox and Chrome, but the issue persisted. I also noticed my battery was draining faster than before. Clearly, something was wrong with my system.</p><p>My initial thought was that it might be time for a fresh macOS install. On Windows, it’s common for systems to slow down over time, often requiring a clean installation to restore performance. But after some research, I discovered another possible culprit: low disk space. Modern SSDs can experience significant slowdowns when nearly full, as they require free space to write data efficiently. The operating system also constantly reads and writes data for swap, caches, and background processes, which can exacerbate the issue if storage is tight.</p><p>I checked my disk space using df -h and found my 512GB SSD was 95% full. After cleaning up old files, Xcode caches, and unused SDKs, I reduced usage to 70%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*xPtk5Y7Vorrnq9neasW7qg.png" /></figure><p>The improvement was immediate. While it might not have been as fast as a fresh install, the stuttering stopped and battery life improved noticeably.</p><p>If your Mac is stuttering, check if your disk is too full! Freeing up space can make a significant difference in performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f41beb087fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling C from Rust]]></title>
            <link>https://medium.com/@techhara/calling-c-from-rust-d7129c8a1c0d?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7129c8a1c0d</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[dynamic-library]]></category>
            <category><![CDATA[static-library]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 00:32:01 GMT</pubDate>
            <atom:updated>2025-04-11T14:27:58.570Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, let’s look at how to call C functions from Rust.</p><p>Suppose we have a s library written in C, say</p><pre>// /project/root/mathlib.h<br>double add(double x, double y);<br><br>// /project/root/mathlib.c<br>#include &lt;math.h&gt;<br><br>double add(double x, double y) {<br>    return x + y;<br>}</pre><p>To call the function add() from Rust, we import the external function with extern keyword</p><pre>// /project/root/src/main.rs<br>unsafe extern &quot;C&quot; {<br>    fn add(x: f64, y: f64) -&gt; f64;<br>}<br><br>fn main() {<br>    unsafe {<br>        let result = add(2.0, 3.0);<br>        println!(&quot;The result of addition is: {}&quot;, result);<br>    }<br>}</pre><h3>Static Linking</h3><p>First, let’s link it statically. That is, our Rust executable will embed the C library code in itself.</p><pre># we assume we are at /project/root/ directory<br><br># create a static object file<br>gcc -fPIC -c -o libmathlib.o mathlib.c<br><br># create an archive<br>ar rucs libmathlib.a libmathlib.o</pre><p>Next, we need to create build.rs file that will link the C object file into the Rust executable</p><pre>// /project/root/build.rs<br>use std::env;<br><br>fn main() {<br>    let pwd = env::var(&quot;PWD&quot;).unwrap();<br><br>    println!(&quot;cargo::rustc-link-search={}&quot;, pwd);<br>    println!(&quot;cargo::rustc-link-lib=mathlib&quot;);<br>    println!(&quot;cargo::rerun-if-changed=mathlib.c&quot;);<br>}</pre><p>Now, we are ready to build and run!</p><pre># build<br>cargo build<br><br># run<br>target/debug/calling-c-from-rust<br>The result of addition is: 5</pre><p>We can verify that the libmathlib.a is statically linked</p><pre># libmathlib.a is not found in the dynamically linked dependencies<br>ldd target/debug/calling-c-from-rust<br> linux-vdso.so.1 (0x0000ffffb434c000)<br> libgcc_s.so.1 =&gt; /lib/aarch64-linux-gnu/libgcc_s.so.1 (0x0000ffffb4250000)<br> libc.so.6 =&gt; /lib/aarch64-linux-gnu/libc.so.6 (0x0000ffffb4090000)<br> /lib/ld-linux-aarch64.so.1 (0x0000ffffb4310000)</pre><h3>Dynamic Linking</h3><p>Next up, let’s see what changes if we want to dynamically link. The only change is that we need to compile into a shared library rather than static one.</p><pre>gcc -shared -fPIC mathlib.c -o libmathlib.so</pre><p>Note that we don’t need to invoke ar this time. The rest is exactly the same. Let’s build it again</p><pre># build<br>cargo build<br><br># run<br>target/debug/calling-c-from-rust<br>The result of addition is: 5</pre><p>Now, let’s make sure it is dynamically linked</p><pre># we see libmathlib.so<br>ldd target/debug/calling-c-from-rust<br> linux-vdso.so.1 (0x0000ffff93eec000)<br> libmathlib.so =&gt; /root/rust-and-c/libmathlib.so (0x0000ffff93e00000)<br> libgcc_s.so.1 =&gt; /lib/aarch64-linux-gnu/libgcc_s.so.1 (0x0000ffff93dc0000)<br> libc.so.6 =&gt; /lib/aarch64-linux-gnu/libc.so.6 (0x0000ffff93c00000)<br> /lib/ld-linux-aarch64.so.1 (0x0000ffff93eb0000)</pre><p>As expected, we do see libmathlib.so file appear.</p><p>Below is the full script that reproduces the steps here.</p><pre># clean up from previous run if any<br>mkdir -p calling-c-from-rust<br>rm -rf calling-c-from-rust<br><br># create a new rust project from scratch<br>cargo new calling-c-from-rust<br>cd calling-c-from-rust<br><br># write C header and source files<br>cat &lt;&lt; EOF &gt; mathlib.h<br>double add(double x, double y);<br>EOF<br><br>cat &lt;&lt; EOF &gt; mathlib.c<br>#include &lt;math.h&gt;<br><br>double add(double x, double y) {<br>    return x + y;<br>}<br>EOF<br><br># write rust program that calls add() function<br>cat &lt;&lt; EOF &gt; src/main.rs<br>unsafe extern &quot;C&quot; {<br>    fn add(x: f64, y: f64) -&gt; f64;<br>}<br><br>fn main() {<br>    unsafe {<br>        let result = add(2.0, 3.0);<br>        println!(&quot;The result of addition is: {}&quot;, result);<br>    }<br>}<br>EOF<br><br># static linking<br>gcc -fPIC -c -o libmathlib.o mathlib.c<br># linux<br>ar rucs libmathlib.a libmathlib.o<br># macos (uncomment below)<br># libtool -static -o libmathlib.a mathlib.o<br><br># dynamic linking (uncomment below)<br># gcc -fPIC -shared -o libmathlib.so mathlib.c<br><br>cat &lt;&lt; EOF &gt; build.rs<br>use std::env;<br><br>fn main() {<br>    let pwd = env::var(&quot;PWD&quot;).unwrap();<br><br>    println!(&quot;cargo::rustc-link-search={}&quot;, pwd);<br>    println!(&quot;cargo::rustc-link-lib=mathlib&quot;);<br>    println!(&quot;cargo::rerun-if-changed=mathlib.c&quot;);<br>}<br>EOF<br><br>cargo run</pre><h3>References</h3><p><a href="https://doc.rust-lang.org/cargo/reference/build-script-examples.html">Build Script Examples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7129c8a1c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Llama.cpp Benchmark: CPU vs iGPU]]></title>
            <link>https://medium.com/@techhara/llama-cpp-benchmark-cpu-vs-igpu-93b3cc40ece5?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/93b3cc40ece5</guid>
            <category><![CDATA[vulkan]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[amd-ryzen]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 10:27:18 GMT</pubDate>
            <atom:updated>2025-03-31T10:27:18.704Z</atom:updated>
            <content:encoded><![CDATA[<p>I tested the inference speed of Llama.cpp on my mini desktop computer equipped with an AMD Ryzen 5 5600H APU. This processor features 6 cores (12 threads) and a Radeon RX Vega 7 integrated GPU. While neither the CPU nor GPU is particularly high-performance, I wanted to compare their capabilities in running Llama.cpp.</p><h3>CPU Benchmark: Ryzen 5 5600H (6 Cores)</h3><p>To begin, I tested Llama.cpp using the CPU only. Below are the steps I followed to build and run the benchmark:</p><pre># Download the model<br>wget https://huggingface.co/TheBloke/Llama-2-7B-GGUF/resolve/main/llama-2-7b.Q4_0.gguf<br><br># Clone the repository<br>git clone https://github.com/ggerganov/llama.cpp<br>cd llama.cpp<br>mkdir build<br>cd build<br><br># Build with Release configuration<br>cmake .. -DCMAKE_BUILD_TYPE=Release<br>make<br><br># Run benchmark<br>llama-bench -m ../../llama-2–7b.Q4_0.gguf</pre><p>The benchmark utilized all six CPU cores (without hyperthreading). Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM8PGenbWNlmfr_hHvm3vw.png" /><figcaption>llama.cpp benchmark with AMD 5 Ryzen 5600H using CPU only</figcaption></figure><h3>iGPU Benchmark: Radeon RX Vega 7</h3><p>Next, I tested Llama.cpp with GPU support enabled using Vulkan. The build process included the following modifications:</p><pre># Build with Vulkan support<br>cmake .. -DGGML_VULKAN=on -DCMAKE_BUILD_TYPE=Release<br>make<br><br># Run benchmark with layers loaded into GPU<br>llama-bench -m ../../llama-2–7b.Q4_0.gguf -ngl 100</pre><p>Key differences from the CPU test:</p><ul><li>Vulkan support was enabled using the -DGGML_VULKAN=on flag.</li><li>All model layers were loaded into the GPU using -ngl 100.</li></ul><p>The results were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZsvsSEfbQh7UMOshws7wQ.png" /><figcaption>llama.cpp benchmark with AMD 5 Ryzen 5600H using iGPU</figcaption></figure><h3>Observations and Analysis</h3><p><strong>Performance Gains:</strong></p><ul><li>The prompt processing test (pp512) showed a 2x speedup on the iGPU compared to the CPU (from ~34 t/s to ~76 t/s).</li><li>However, token generation (tg128) performance remained nearly identical (~10 t/s).</li></ul><p><strong>Power Efficiency:</strong></p><ul><li>The iGPU consumed noticeably less power, as evidenced by reduced fan noise during operation.</li><li>This suggests that the iGPU build is more energy-efficient than the CPU-only build.</li></ul><p><strong>System Utilization:</strong></p><ul><li>With iGPU handling inference tasks, the CPU remained largely idle, allowing other CPU-intensive processes to run concurrently.</li></ul><h3><strong>Conclusion</strong></h3><p>While the iGPU provided significant improvement in prompt processing speed, its impact on token generation was minimal — contrary to expectations of a proportional gain across both metrics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93b3cc40ece5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Multilingual Code Conundrum]]></title>
            <link>https://medium.com/@techhara/the-multilingual-code-conundrum-3c4609e6655b?source=rss-8c4660af51b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c4609e6655b</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[multilingual]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[TechHara]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 10:02:07 GMT</pubDate>
            <atom:updated>2025-03-28T10:02:07.377Z</atom:updated>
            <content:encoded><![CDATA[<p>In the bustling tech hub of Silicon Valley, two brilliant but stubborn developers find themselves thrust into an unexpected collaboration. Meet Tessa, a TypeScript enthusiast with a penchant for strong typing and compile-time checks, and Pablo, a Python aficionado who swears by the language’s simplicity and readability.</p><p>Tessa and Pablo are tasked with building a financial data analysis application — a project requiring two distinct components: data pre-processing and machine learning algorithms. Tessa excels in data pre-processing, while Pablo possesses unparalleled expertise in machine learning. The challenge, however, lies in their unwavering dedication to their respective languages; they resolutely refuse to write code in anything other than TypeScript or Python.</p><p>This scenario plays out as a familiar tale within the developer community. It’s widely acknowledged that developers rarely thrive when forced to utilize a language they aren’t particularly fond of. Such a situation not only diminishes morale but also demonstrably reduces productivity. As their manager, what course of action would you recommend?</p><h3>Subprocess to Spawn Work</h3><p>One language could act as the primary driver, spawning subprocesses to execute code written in the other language when needed. For example, Pablo could call Tessa’s code</p><pre>def preprocess_data(input_file, output_file):<br>    try:<br>        # Call Tessa&#39;s TypeScript script using subprocess<br>        subprocess.run([&#39;ts-node&#39;, &#39;preprocess.ts&#39;, input_file, output_file], check=True)<br>        print(&quot;Pre-processing completed successfully.&quot;)<br>    except subprocess.CalledProcessError as e:<br>        print(f&quot;Error during pre-processing: {e}&quot;)<br>        sys.exit(1)</pre><p>However, I would <strong>not recommend</strong> this approach:</p><ul><li>Introduces overhead for process creation and inter-process communication</li><li>Can be difficult to manage shared state and data transfer between processes</li><li>Error handling and debugging across process boundaries can be complex</li><li>May lead to inefficient resource utilization</li></ul><h3>Language Binding</h3><p>Language binding involves creating interfaces that allow code written in one language to interact with code written in another. In this case, we could use TypeScript bindings for Python or vice versa.</p><p>For example, the following code allows Python to call Javascript</p><pre>from javascript import require, globalThis<br><br>chalk, fs = require(&quot;chalk&quot;), require(&quot;fs&quot;)<br><br>print(&quot;Hello&quot;, chalk.red(&quot;world!&quot;), &quot;it&#39;s&quot;, globalThis.Date().toLocaleString())<br>fs.writeFileSync(&quot;HelloWorld.txt&quot;, &quot;hi!&quot;)</pre><p>However, I would <strong>not recommend</strong> this approach for three reasons</p><ul><li>Introduces complexity and potential performance overhead</li><li>Requires maintenance of binding libraries</li><li>May not fully leverage the strengths of each language</li></ul><h3>Polyglot Programming</h3><p>This approach involves using a runtime that supports multiple languages, such as GraalVM, which can run both TypeScript (via Node.js) and Python.</p><pre>import polyglot<br>array = polyglot.eval(language=&quot;js&quot;, string=&quot;[1,2,42,4]&quot;)</pre><p>Again, I would <strong>not recommend</strong> this approach either</p><ul><li>Requires a specific runtime environment</li><li>May have compatibility issues with certain libraries</li><li>Can be challenging to debug and maintain</li></ul><h3>Microservice Architecture</h3><p>Finally, this is the <strong>recommended approach</strong>. A microservice architecture separates the application into independent services, each written in the most suitable language. Here’s how it works:</p><ul><li>Each service implements a client-server model</li><li>Services communicate via agreed-upon message interfaces</li><li>Each codebase is completely decoupled and can be maintained separately</li></ul><p>Let’s look at a simple example of how Tessa and Pablo could implement this solution. First, Tessa creates a TypeScript microservice for data pre-processing:</p><pre>import express, { Request, Response } from &#39;express&#39;;<br>import bodyParser from &#39;body-parser&#39;;<br><br>const app = express();<br>const port: number = 3000;<br><br>app.use(bodyParser.json());<br><br>interface RequestData {<br>  [key: string]: any;<br>}<br><br>app.post(&#39;/api/preprocess&#39;, (req: Request&lt;{}, {}, RequestData&gt;, res: Response) =&gt; {<br>  const rawData: RequestData = req.body;<br>  // Implement pre-processing logic here<br>  const processedData = { /* ... */ };<br>  <br>  res.json({<br>    message: &#39;Data pre-processed successfully&#39;,<br>    data: processedData<br>  });<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Pre-processing service running on http://localhost:${port}`);<br>});</pre><p>Pablo can then call this service from his Python code:</p><pre>import requests<br><br>def preprocess_data(raw_data):<br>    url = &#39;http://localhost:3000/api/preprocess&#39;<br>    headers = {&#39;Content-Type&#39;: &#39;application/json&#39;}<br>    <br>    response = requests.post(url, json=raw_data, headers=headers)<br>    return response.json()[&#39;data&#39;]<br><br># Use the pre-processed data in machine learning algorithms<br>raw_data = ...<br>processed_data = preprocess_data(raw_data)<br># Implement machine learning logic here</pre><p>Benefits of the approach include</p><ul><li>Language Independence: Each developer can work in their preferred language, maximizing productivity and code quality</li><li>Scalability: Microservices can be scaled independently based on demand</li><li>Maintainability: Services can be updated or replaced without affecting the entire system</li><li>Autonomy: Tessa and Pablo can work independently on their respective services</li><li>Technology Flexibility: Each service can use the most appropriate tools and libraries for its specific task</li><li>Easier Integration: Services communicate via well-defined APIs, simplifying integration</li><li>Future-Proofing: New services in different languages can be added as needed without major refactoring</li></ul><p>Unfortunately, however, there is no free lunch. There exists some drawback with this approach</p><ul><li>Communication challenges: Inter-service communication can be complex, leading to potential latency issues and increased network traffic</li><li>Debugging and testing difficulties: With multiple services, each with its own set of logs, debugging becomes more complicated. Global testing is also challenging due to service dependencies</li><li>Data management and consistency issues: Maintaining data consistency across multiple databases and services can be problematic</li><li>Deployment challenges: Coordinating deployments across multiple services can be more complicated than deploying a single monolithic application</li><li>Potential performance issues: While individual services may be optimized, the overall system performance can suffer due to network latency and communication overhead</li></ul><p>What do you think is the best solution here?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c4609e6655b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>