<?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 Victor Grygorchuk on Medium]]></title>
        <description><![CDATA[Stories by Victor Grygorchuk on Medium]]></description>
        <link>https://medium.com/@vvgrygorchuk?source=rss-d7605075cbbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MHzvTFjR6BZrpo4BsH4OZQ.jpeg</url>
            <title>Stories by Victor Grygorchuk on Medium</title>
            <link>https://medium.com/@vvgrygorchuk?source=rss-d7605075cbbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:34:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vvgrygorchuk/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[How to see Images the way Computer sees — Python Pandas tricks]]></title>
            <link>https://vvgrygorchuk.medium.com/how-to-see-images-the-way-computer-sees-python-pandas-tricks-374ebcc9a12b?source=rss-d7605075cbbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/374ebcc9a12b</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Victor Grygorchuk]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 14:03:43 GMT</pubDate>
            <atom:updated>2021-03-23T16:15:21.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to see Images the way Computer sees — Python Pandas tricks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1JyAwFjqiB2M8Sk5Y3ESg.png" /></figure><p>Imagine you explain to a kid how a computer processes an image.</p><p>YOU: <em>“The image is a bunch of numbers for the computer.”</em></p><p>KID: <em>“How is it possible to see an image with numbers?”</em></p><p>YOU: <em>“Well... There are numbers from 0 to 255, where 0 is dark and 255 is white, and to represent one dot on the image you need a number for red, green, and blue…”</em></p><p>You may do better, but it is still complicated.</p><p><strong>The best way to explain is to show.</strong></p><p>Python library pandas has a great instrument to bring a human and machine representation of the image as close as possible.</p><p>We downloaded a smiley emoji (<a href="https://toppng.com/uploads/preview/emoji-emojis-emoticonos-emoticono-feliz-happy-reir-happy-face-emoji-115630245952vdezktgff.png">link</a> — no copyright infringement intended, Google said the image has the Creative Common License).</p><p>Get Python library Pillow to work with an image in a code.</p><pre>from PIL import Image</pre><p><em>Don’t be confused, we installed </em><em>Pillow but we </em><em>import PIL, as </em><em>Pillow is a fork for the original </em><em>PIL (and </em><em>PIL is no longer supported).</em></p><p>Let’s start coding: img = Image.open(&#39;image.png&#39;)</p><p>This is how human see images: img.show()</p><p>Later we would like to print the image, perhaps, it’s good to downsize the image to something smaller, e.g. 32x32 pixels, as a big image might not fit our displays.</p><pre>img = img.resize((32, 32), )</pre><p>Right, the image is a bunch of numbers. The first step is to see those numbers. We do it with numpy :</p><pre>import numpy as np<br><br>img_as_arr = np.asarray(img)<br>print(img_as_arr)</pre><p>And result is:</p><pre>[[[247 247 247 255]<br>  [245 245 245 255]<br>  [245 245 245 255]<br>  ...<br>  [246 246 246 255]<br>  [245 245 245 255]<br>  [247 247 247 255]]<br># and so on</pre><p>I agree, it’s not excellent visualization for a kid. Let’s do better!</p><p>Print the shape of the image: print(img_as_arr.shape). As you can see the shape is (32, 32, 4), what means we have 32 by 32 pixels in 4 channels.</p><p>Print those 4 channels by the command: print(img.mode), what outputs us RGBA: Red, Green, Blue, Alpha.</p><p>We separate those channels into four different images:</p><pre>red = img_as_arr[:,:,:1] # get 32x32 pixels and first color channel<br>green = img_as_arr[:, :, 1:2] # second channel for green<br>blue = img_as_arr[:, :, 2:3] # third channel for blue<br>alpha = img_as_arr[:, :, 3:] # forth for alpha</pre><p>We’re almost there! The last step is to squeeze images into 2-d array. Now, if print any image shape, we get (32, 32, 1). We need to make it just 32 by 32, basically, what we want is a table of 32 columns and 32 rows.</p><pre>red = np.squeeze(red, 2)<br>print(red.shape)<br># output must be (32, 32)<br>blue = np.squeeze(blue, 2)<br>green = np.squeeze(green, 2)<br>alpha = np.squeeze(alpha, 2)</pre><p>Let’s create a table of digits with pandas:</p><pre>import pandas as pd<br><br>df_red = pd.DataFrame(red)<br>df_green = pd.DataFrame(green)<br>df_blue = pd.DataFrame(blue)<br>df_alpha = pd.DataFrame(alpha)</pre><p>We’ve arrived at our final step before we can show results.</p><p>Now, we have the tables with numbers. How does it help to explain the concept of image with digits? We can paint each digit with appropriate color!</p><pre>style_r = df_red.style.set_properties(**{&#39;font-size&#39;: &#39;8pt&#39;}).background_gradient(&#39;Reds_r&#39;)<br>style_g = df_green.style.set_properties(**{&#39;font-size&#39;: &#39;8pt&#39;}).background_gradient(&#39;Greens_r&#39;)<br>style_b = df_blue.style.set_properties(**{&#39;font-size&#39;: &#39;8pt&#39;}).background_gradient(&#39;Blues_r&#39;)<br>style_a = df_alpha.style.set_properties(**{&#39;font-size&#39;: &#39;8pt&#39;}).background_gradient(&#39;Greys&#39;)</pre><p>When we use IPython/ Jupiter Notebook we can simply look at each style_* to see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*3eA27HoKBrGiDfMkhb3prA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*_hDg68xwClarFCFOxbIIxA.png" /><figcaption>red zoomed</figcaption></figure><p>If we work in any other IDE or in plain notepad — just save the style_* to the html:</p><pre>with open(&#39;image.html&#39;, &#39;w&#39;) as html:<br>    html.write(style_r.render())<br>    html.write(style_g.render())<br>    html.write(style_b.render())<br>    html.write(style_a.render())</pre><p>Have a fun with explaining things (I tried to explain it to my wife, but she replied it’s boring :-)</p><p>Find here the full code <a href="https://gist.github.com/VicGrygorchyk/b2af7cd939a4ab887dcbd875b6d7bc7d">https://gist.github.com/VicGrygorchyk/b2af7cd939a4ab887dcbd875b6d7bc7d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374ebcc9a12b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Selenium WebElement with Python in 5 Minutes, or the Magic of “getattr()”]]></title>
            <link>https://vvgrygorchuk.medium.com/lazy-selenium-webelement-with-python-in-5-minutes-or-the-magic-of-getattr-62d6b84636e0?source=rss-d7605075cbbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/62d6b84636e0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Victor Grygorchuk]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 10:30:35 GMT</pubDate>
            <atom:updated>2020-11-29T10:30:35.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMGWL300CK9bpHv_WrifOw.png" /><figcaption>Image by <a href="https://pixabay.com/users/ralfdesign-2031934/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=5120273">Ralf Designs</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=5120273">Pixabay</a></figcaption></figure><p>What is the most irritating about Selenium WebElement? I bet you named “waiting for an element on a webpage” among the biggest headache.</p><p>Let me ask how do you solve it? It might be something similar to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b3a1c90f55f0ee2ae489bbfe184b23/href">https://medium.com/media/66b3a1c90f55f0ee2ae489bbfe184b23/href</a></iframe><p>What is not bad, except it doesn’t provide a whole solution for the problem: when you declared a WebElement in the page object before this WebElement actually appears in the webpage’s DOM.</p><pre>class MyPage:<br>    def __init__(self, webdriver):<br>        self.webdriver = webdriver<br>        self.some_button = wait_for_element(&#39;.my-button&#39;)</pre><pre>    def open(self):<br>        self.webdriver.get(&#39;url&#39;)</pre><pre>def test(driver):<br>    page = MyPage(driver) # &lt;-- the test breaks here<br>    page.open()<br>    page.some_button.click()</pre><p>Of course, the test fails before we open the page and click the button, ’cause I’m fool enough to initialize the some_button before the page is fully rendered.</p><p>And I am sure you know the answer — “don’t assign a value to an element in __init__(), use properties and/or getter methods”.</p><p>Well, when I write a test itself, I know I should not click a button before the page is loaded. But, it’s not a test, what’s wrong with the above code, it’s the page object. So, why I should care about such thing while writing a page object? Let’s use Python to eliminate the very existence of the problem.</p><p>Fortunately, Python is so great and flexible, that it allows you in less than 5 minutes to develop a WebElement lazy loading of <a href="https://en.wikipedia.org/wiki/Lazy_loading">https://en.wikipedia.org/wiki/Lazy_loading</a>.</p><p>I mean, we can declare the WebElement wherever we want, even in __init__() , but the element is lazy, it does nothing and its actual initialization is deferred until we interact with the WebElement.</p><p>Less talk and more code for the god of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0ff4961d290a8bf2b0e7070e09c1775/href">https://medium.com/media/c0ff4961d290a8bf2b0e7070e09c1775/href</a></iframe><p>The magic is done by __getattr__() method.</p><p>The greatest thing is that our LazyWebElement behaves the same way as Selenium WebElement when we need a default behavior. We don’t need to change the tests if they have been written with Selenium original WebElement. And all our problems are solved:</p><pre>class MyPage:<br>    def __init__(self, webdriver):<br>        self.webdriver = webdriver<br>        self.some_button = LazyWebElement(self.webdriver, &#39;.my-button&#39;)</pre><pre>def open(self):<br>        self.webdriver.get(&#39;url&#39;)</pre><pre>def test(driver):<br>    page = MyPage(driver) # &lt;-- the test doesn&#39;t break here<br>    page.open()<br>    page.some_button.click()</pre><p>You see, we don’t implement click() for the LazyWebElement, it just knows to pass the click method to the original WebElement.</p><p>Well, that’s it.</p><p>If you’re interested, you may take a look into my Github repo <a href="https://github.com/VicGrygorchyk/selen_kaa">https://github.com/VicGrygorchyk/selen_kaa</a>, where I implemented everything I was telling here and a little more.</p><p>Ah, one more thing! We can implement our own Selenium wrapper (adapter pattern) using a magic __getattr__(). And yes, you may find it in the same Github repo mentioned in the previous paragraph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5595dfe2965e9f5e3a98485801eb7d10/href">https://medium.com/media/5595dfe2965e9f5e3a98485801eb7d10/href</a></iframe><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62d6b84636e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you shouldn’t be afraid of sleep() in your Selenium auto-tests.]]></title>
            <link>https://vvgrygorchuk.medium.com/why-you-shouldnt-be-afraid-of-sleep-in-your-selenium-auto-tests-af72056d9404?source=rss-d7605075cbbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/af72056d9404</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[selenium-test-automation]]></category>
            <category><![CDATA[auto-test]]></category>
            <dc:creator><![CDATA[Victor Grygorchuk]]></dc:creator>
            <pubDate>Sun, 16 Jun 2019 20:32:22 GMT</pubDate>
            <atom:updated>2020-02-01T22:33:33.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*F8QbzWg5XhaafWn2HbCHrA.jpeg" /><figcaption>credits <a href="https://ichef.bbci.co.uk/news/660/cpsprodpb/D4E0/production/_104369445_0b19b561-f45c-479e-bb41-501094d14f19.jpg">https://ichef.bbci.co.uk/news/660/cpsprodpb/D4E0/production/_104369445_0b19b561-f45c-479e-bb41-501094d14f19.jpg</a></figcaption></figure><p><strong>TL;DR:</strong> you might already know it, if so, I spare you from reading through this flow of words, we all use sleep() in our Selenium tests, we just don’t talk about it. Selenium waits are nothing but sleep().</p><p>This is how it starts: you write a first test to interact with browser and dream to eliminate manual testing from the planet face. Such test might look like this:</p><pre>login_input = driver.find_element_by_css_selector(&quot;#log&quot;)<br>login_input.send_keys(&quot;Superuser&quot;)</pre><pre>big_button = driver.find_element_by_css_selector(&quot;#bug_btn&quot;)<br>big_button.click()</pre><p>Till you hit the wall of errors: “ no such element”, “element not visible”, “another element received a click”.</p><h3>Wait magic is dark and full of terror:</h3><p>What is the problem? The code might try to send text to login_input before this element appears in DOM, or try to click big_button before the web element is either visible, or some animation is blocking a click. There might be another reason for error. The first instinct is to make your script slower, to freeze it for a second or two, basically, to make a script to sleep.</p><p>At this point, the good fellows enter our story, they are called Seniors and Leads, but they are not in their 60th, as my mum would expect from a person called Senior.</p><p>Those experts tell the only truth you should know to become a test hero:</p><blockquote>Use wait and expected conditions, and never use sleep! And burn every person in code reviews, who has sleep in their code.</blockquote><p>Is sleep such a big sin, that we claim to fight it?</p><p>Basically, yes, you freeze your code, keeping valuable machine resources idle for some time period.</p><p>And biggest problem, you don’t know how long the code should be freezed before you can interact with element safely. Let it be 2 seconds? What if 2 seconds are not enough for some long load animation. Or you neglect the fact most users hate waiting longer than 4 seconds and you raise stakes to 15 seconds? What if the element is visible sometimes at 4th second but another time at 7th? Let’s sleep 7 seconds for not getting error?</p><p>Nope, Seniors reply you, there is a better way: use Selenium “wait for 7 seconds” and if element is visible / present / has text / etc at any point before 7 seconds end, your code detects it and would perform a desired action.</p><p>Okay, we all are aware of it, ain’t we? What is this post about?</p><p>I’ve never found a method in standard Selenium, what could help me to wait until element can receive a click without being blocked by some overlay animation. And I came up with next solution:</p><pre>timeout = 5 #  five seconds to wait<br>start_time = time.time()<br>while True:<br>    try:<br>        web_element.click()<br>        break<br>    except WebDriverException: <br>        if time.time() - start_time &gt; timeout:<br>                raise WebDriverException(&quot;Element is not clickable&quot;)<br>        continue<br>    time.sleep(0.1)</pre><p>I know you probably write Java Selenium tests, and here is Python. Let me guide you though. We click web_element, what is an instance of WebElement object and, obviously, can handle click(). If we click it without Exception, we break from while loop, otherwise, catch the WebDriverException, what shall be thrown when the web element is not clickable. Repeat this loop while elapsed time isn’t bigger than our maximum wait time represented by the variable timeout.</p><p>Stop! Here we have time.sleep() (makes the same as Java Thread.sleep()).</p><p>Ladies and Gentleman, before jump to conclusions, let me speak for myself! Just look into Selenium implementation for until method of Wait object:</p><pre>def until(self, method, message=&#39;&#39;):<br>       <br>        while True:<br>...<br>            time.sleep(self._poll)<br>            if time.time() &gt; end_time:<br>                break<br>        raise TimeoutException(message, screen, stacktrace)</pre><p><a href="https://github.com/SeleniumHQ/selenium/blob/d5a93cc0559fa27c367b71a212b0e613e1d9a7dd/py/selenium/webdriver/support/wait.py#L83">SeleniumHQ/selenium</a></p><p>WUT!? They use sleep! How dare they!</p><p>Maybe it’s all about Python, hope Java is better.</p><pre>while (true) {<br>     ...<br><br>      try {<br>        sleeper.sleep(interval);<br>      } catch (InterruptedException e) {</pre><p><a href="https://github.com/SeleniumHQ/selenium/blob/d5a93cc0559fa27c367b71a212b0e613e1d9a7dd/java/client/src/org/openqa/selenium/support/ui/FluentWait.java#L238">SeleniumHQ/selenium</a></p><p>Yes, you’ve seen it, they use sleep as well!</p><p>What am I talking about?</p><ul><li>You’re okay to use sleep (Selenium core devs do it!), if you are not blocking your code for N seconds, but constantly checking for web element readiness to handle an event or an action. These requires you to have the break case fo your loop and throw an error when timeout is over.</li><li>Use sleep in those cases, when you can’t find a proper Selenium method to wait.</li><li>Use sleep with care, it should be not a replacement for wait, but a mean (a part of your own “wait” method) to reduce flakiness, and I consider it’s justified only if your code sleeps for 0.1–0.5 seconds and not longer!</li></ul><p>Keep safe and sleep well!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af72056d9404" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>