<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>emre şahin's digital garden 🍃 - Python</title>
    <link>https://emresahin.net/categories/python/</link>
    <description>Posts in the Python category</description>
    <language>en</language>
    <managingEditor>contact@emresahin.net (Emre Şahin)</managingEditor>
    <lastBuildDate>Tue, 15 Sep 2026 19:46:32 +0000</lastBuildDate>
    <atom:link href="https://emresahin.net/categories/python/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>devlog 25</title>
      <published>2025-04-24T02:57:26+00:00</published>
      <updated>2025-04-24T02:57:26+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Thu, 24 Apr 2025 02:57:26 +0000</pubDate>
      <link>https://emresahin.net/devlog-25/</link>
      <guid isPermaLink="true">https://emresahin.net/devlog-25/</guid>
      <description>🐢 I want to update xvc.py to the latest version. 🐇 It should only be needed to update the dependency versions in Cargo.toml , right? 🐢 Let’s start with that. 🐇 We have interface changes regarding aliases; let’s start using uv for building. 🦊 Added requirements to pyproject.toml by running: uv add...</description>
      <category>XVC</category>
      <category>Python</category>
      <category>Development</category>
      <category>XVC</category>
      <category>Python</category>
      <category>uv</category>
      <category>Package Management</category>
      <category>Requirements</category>
      <content:encoded><![CDATA[<p>🐢 I want to update <code>xvc.py</code> to the latest version.</p>
<p>🐇 It should only be needed to update the dependency versions in <code>Cargo.toml</code>, right?</p>
<p>🐢 Let’s start with that.</p>
<p>🐇 We have interface changes regarding aliases; let’s start using <code>uv</code> for building.</p>
<p>🦊 Added requirements to <code>pyproject.toml</code> by running:</p>
<pre><code class="language-bash">uv add -r requirements.txt
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Converting MNIST and Fashion-MNIST IDX format to NumPy</title>
      <published>2021-07-01T20:46:12+00:00</published>
      <updated>2021-07-01T20:46:12+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Thu, 01 Jul 2021 20:46:12 +0000</pubDate>
      <link>https://emresahin.net/convert-mnist-data-to-numpy/</link>
      <guid isPermaLink="true">https://emresahin.net/convert-mnist-data-to-numpy/</guid>
      <description>MNIST and the newer Fashion-MNIST datasets are among the most well-known datasets for testing Machine Learning models. Although the original MNIST dataset is considered solved, it will likely remain a staple for a long time. These datasets are provided in a binary format. There are four files—two...</description>
      <category>Python</category>
      <category>Machine Learning</category>
      <category>MNIST</category>
      <category>Fashion-MNIST</category>
      <category>IDX</category>
      <category>IDX3</category>
      <category>NumPy</category>
      <content:encoded><![CDATA[<p>MNIST and the newer Fashion-MNIST datasets are among the most well-known datasets for testing Machine Learning models. Although the original MNIST dataset is considered solved, it will likely remain a staple for a long time.</p>
<p>These datasets are provided in a binary format. There are four files—two for the training set and two for the test set—in gzipped <code>IDX</code> and <code>IDX3</code> formats. Although it is a simple format, it is non-standard and requires custom code to parse.</p>
<p>For a professional project, I wrote the following two functions to load these files into NumPy arrays.</p>
<pre><code class="language-python">
import struct
import gzip
import numpy as np

def mnist_images_idx_to_array(images_filename):
    images_f = gzip.open(images_filename, mode="rb")
    images_f.seek(0)
    magic = struct.unpack('&gt;I', images_f.read(4))[0]
    if magic != 0x00000803:
        raise Exception(f"Format error: Need an IDX3 file: {images_filename}")
    n_images = struct.unpack('&gt;I', images_f.read(4))[0]
    n_row = struct.unpack('&gt;I', images_f.read(4))[0]
    n_col = struct.unpack('&gt;I', images_f.read(4))[0]

    n_bytes = n_images * n_row * n_col  # each pixel is 1 byte

    images_data = struct.unpack(
        '&gt;' + str(n_bytes) + 'B', images_f.read(n_bytes))

    images_array = np.asarray(images_data, dtype='uint8')
    images_array.shape = (n_images, n_row, n_col)

    return images_array


def mnist_labels_idx_to_array(labels_filename):
    labels_f = gzip.open(labels_filename, mode="rb")
    labels_f.seek(0)
    magic = struct.unpack('&gt;I', labels_f.read(4))[0]
    if magic != 0x00000801:
        raise Exception(f"Format error: Need an IDX file: {labels_filename}")
    n_labels = struct.unpack('&gt;I', labels_f.read(4))[0]
    labels_data = struct.unpack(
        '&gt;' + str(n_labels) + 'B', labels_f.read(n_labels))
    labels_array = np.asarray(labels_data, dtype='uint8')
    return labels_array


</code></pre>
<p>You can use these functions by passing the appropriate filenames, as shown below:</p>
<pre><code class="language-python">

training_images = mnist_images_idx_to_array(
    os.path.join(input_dir, "train-images-idx3-ubyte.gz"))
training_labels = mnist_labels_idx_to_array(
    os.path.join(input_dir, "train-labels-idx1-ubyte.gz"))
testing_images = mnist_images_idx_to_array(
    os.path.join(input_dir, "t10k-images-idx3-ubyte.gz"))
testing_labels = mnist_labels_idx_to_array(
    os.path.join(input_dir, "t10k-labels-idx1-ubyte.gz"))

</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Fixing Pip Timeout Problems</title>
      <published>2018-11-16T18:58:31+00:00</published>
      <updated>2018-11-16T18:58:31+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Fri, 16 Nov 2018 18:58:31 +0000</pubDate>
      <link>https://emresahin.net/pip-default-timeout-14371-8665/</link>
      <guid isPermaLink="true">https://emresahin.net/pip-default-timeout-14371-8665/</guid>
      <description>When installing a large package like TensorFlow , I encountered the following error in pip : pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. v = self._sslobj.read(len, buffer) socket.timeout: The read operation timed o...</description>
      <category>Python</category>
      <category>DevOps</category>
      <category>pip</category>
      <category>TensorFlow</category>
      <category>Troubleshooting</category>
      <content:encoded><![CDATA[<p>When installing a large package like <em>TensorFlow</em>, I encountered the following error in <code>pip</code>:</p>
<pre><code class="language-text">pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
</code></pre>
<p>I noticed that <code>pip</code> has a <code>--default-timeout</code> parameter that can be configured to avoid this issue:</p>
<pre><code class="language-bash">pip --default-timeout=1000 install package-name
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to convert NumPy image to QImage?</title>
      <published>2018-11-06T20:11:46+00:00</published>
      <updated>2018-11-06T20:11:46+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Tue, 06 Nov 2018 20:11:46 +0000</pubDate>
      <link>https://emresahin.net/converting-numpy-image-to-qimage-14359-22392/</link>
      <guid isPermaLink="true">https://emresahin.net/converting-numpy-image-to-qimage-14359-22392/</guid>
      <description>When writing Qt GUI code for a deep learning system, a common task is converting an image (read from disk or camera using OpenCV) from a NumPy array to a QImage for display in a widget. There are basically two problems to address: NumPy arrays often have data types with more than 8 bits, and Open...</description>
      <category>Python</category>
      <category>Qt</category>
      <category>NumPy</category>
      <category>QImage</category>
      <category>PySide2</category>
      <category>OpenCV</category>
      <category>Image Processing</category>
      <content:encoded><![CDATA[<p>When writing Qt GUI code for a deep learning system, a common task is converting an image (read from disk or camera using OpenCV) from a NumPy array to a QImage for display in a widget.</p>
<p>There are basically two problems to address: NumPy arrays often have data types with more than 8 bits, and OpenCV reads images in BGR format rather than the more common RGB.</p>
<p>The following Python (3.5+) code demonstrates the solution:</p>
<pre><code class="language-python">import PySide2.QtGui as qtg
import numpy as np

def get_qimage(image: np.ndarray):
    assert (np.max(image) &lt;= 255)
    image8 = image.astype(np.uint8, order='C', casting='unsafe')
    height, width, colors = image8.shape
    bytesPerLine = 3 * width

    image = qtg.QImage(image8.data, width, height, bytesPerLine,
                       qtg.QImage.Format_RGB888)

    image = image.rgbSwapped()
    return image
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Query Logging in Databases when using Parameters</title>
      <published>2018-11-06T19:41:10+00:00</published>
      <updated>2018-11-06T19:41:10+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Tue, 06 Nov 2018 19:41:10 +0000</pubDate>
      <link>https://emresahin.net/query-logging-in-python-sqlite-14359-20562/</link>
      <guid isPermaLink="true">https://emresahin.net/query-logging-in-python-sqlite-14359-20562/</guid>
      <description>We avoid constructing database queries using string formatting to prevent security issues. SQL injection attacks stem from a lack of proper escaping and building queries directly from untrusted input strings. Instead, we use parameter passing to the database engine. For example: SELECT * FROM peo...</description>
      <category>Databases</category>
      <category>Python</category>
      <category>sqlite</category>
      <category>query-logging</category>
      <category>debugging</category>
      <category>sql-injection</category>
      <category>security</category>
      <content:encoded><![CDATA[<p>We avoid constructing database queries using string formatting to prevent security issues. SQL injection attacks stem from a lack of proper escaping and building queries directly from untrusted input strings.</p>
<p>Instead, we use parameter passing to the database engine. For example:</p>
<pre><code class="language-sql">SELECT * FROM people WHERE name = ?
</code></pre>
<p>We send this query and the parameters separately to the database. Most modern database systems support this approach.</p>
<p>In SQLite 3 with Python, we use it like this:</p>
<pre><code class="language-python">query = "SELECT * FROM people WHERE name = ?"
params = (name,)
db_result = cursor.execute(query, params)
</code></pre>
<p>However, when debugging, we may need to see the actual queries sent to the database—for instance, when data types are important or when we suspect a column is receiving a string instead of an integer.</p>
<p>In these cases, rather than manually reconstructing the query, we can use the <code>set_trace_callback</code> feature available in Python 3.3 and later:</p>
<pre><code class="language-python">connection.set_trace_callback(print)
</code></pre>
<p>The argument can be any function (such as <code>print</code> or a logger function) or <code>None</code> to disable tracing. This makes it easy to integrate with Python’s standard <code>logging</code> module.</p>]]></content:encoded>
    </item>
    <item>
      <title>Numpy ValueError while using dlib's face detector</title>
      <published>2018-10-24T21:41:18+00:00</published>
      <updated>2018-10-24T21:41:18+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Wed, 24 Oct 2018 21:41:18 +0000</pubDate>
      <link>https://emresahin.net/value-error-dlib-14346-27722/</link>
      <guid isPermaLink="true">https://emresahin.net/value-error-dlib-14346-27722/</guid>
      <description>For two days, I was trying to find a bug in my code because an assertion in the code that uses numpy.max was throwing an error: ValueError: zero-size array to reduction operation maximum which has no identity , which didn’t seem reasonable. I’m building a face recognizer with dlib ’s frontal face...</description>
      <category>Machine Learning</category>
      <category>Python</category>
      <category>Debugging</category>
      <category>dlib</category>
      <category>NumPy</category>
      <category>Face Detection</category>
      <category>Python</category>
      <category>Computer Vision</category>
      <category>ValueError</category>
      <content:encoded><![CDATA[<p>For two days, I was trying to find a bug in my code because an assertion in the
code that uses <code>numpy.max</code> was throwing an error: <code>ValueError: zero-size array to reduction operation maximum which has no identity</code>, which didn’t seem
reasonable.</p>
<p>I’m building a face recognizer with <a href="https://github.com/davisking/dlib/">dlib</a>’s
frontal face detector, and today, I noticed that some of the results return
<em>negative</em> coordinates in face detection. This means the detected face is
partial, although it’s a bit of a stretch to use negative coordinates for this.</p>
<p>My code wasn’t checking for negative coordinates and was building the NumPy
array incorrectly. However, after reading <a href="https://github.com/davisking/dlib/issues/767">the
issue</a>, although I’m still not convinced
that it’s a good approach, I added a few <code>if</code> statements and the problem was solved.</p>]]></content:encoded>
    </item>
    <item>
      <title>Static Variables in Python</title>
      <published>2018-10-24T21:31:06+00:00</published>
      <updated>2018-10-24T21:31:06+00:00</updated>
      <author>Emre Şahin</author>
      <pubDate>Wed, 24 Oct 2018 21:31:06 +0000</pubDate>
      <link>https://emresahin.net/static-variables-in-python-14346-27102/</link>
      <guid isPermaLink="true">https://emresahin.net/static-variables-in-python-14346-27102/</guid>
      <description>I use this pattern frequently across different projects and would like to keep it here for reference. Python doesn’t have C-style static variables natively. (Although it supports class variables , which can be used for a similar purpose in OOP.) However, since functions are also objects in Python...</description>
      <category>Python</category>
      <category>Programming</category>
      <category>Static Variables</category>
      <category>Decorators</category>
      <category>Snippets</category>
      <content:encoded><![CDATA[<p>I use this pattern frequently across different projects and would like to keep it here for reference.</p>
<p>Python doesn’t have C-style <em>static</em> variables natively. (Although it supports
<em>class variables</em>, which can be used for a similar purpose in OOP.) However, since
functions are also objects in Python, it’s possible to <em>embed</em> variables inside
the function. An elegant solution on
<a href="https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/28401932">Stack Overflow</a>
creates a decorator for static variables.</p>
<pre><code class="language-python">def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate

@static_vars(counter=0)
def foo():
    foo.counter += 1
    print(f"Counter is {foo.counter}")
</code></pre>]]></content:encoded>
    </item>
  </channel>
</rss>
