<?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 Flávio Brito on Medium]]></title>
        <description><![CDATA[Stories by Flávio Brito on Medium]]></description>
        <link>https://medium.com/@flaviobritodata?source=rss-7775a14eeed6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t_4Wr33QWrqs943mJ6VIng.jpeg</url>
            <title>Stories by Flávio Brito on Medium</title>
            <link>https://medium.com/@flaviobritodata?source=rss-7775a14eeed6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:17:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@flaviobritodata/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[Freeing Disk Space in Docker: Beyond Volumes — Understanding and Managing Build Cache]]></title>
            <link>https://flaviobritodata.medium.com/freeing-disk-space-in-docker-beyond-volumes-understanding-and-managing-build-cache-086b5c0c4073?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/086b5c0c4073</guid>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Thu, 15 May 2025 13:52:28 GMT</pubDate>
            <atom:updated>2025-05-15T13:52:28.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Freeing Disk Space in Docker: Beyond Volumes — Understanding and Managing Build Cache</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCClsuOFCjJ0Z8ZG4BX_gg.png" /></figure><p>When working with Docker, many developers focus on cleaning up unused volumes to reclaim disk space. However, another major space consumer is often overlooked: the Docker build cache. In this article, I’ll not only show how to safely remove unused volumes but also explain what the build cache is, why it matters, and how to manage it without compromising your workflow or data.</p><h3>What Is the Docker Build Cache?</h3><p>Every time you build a Docker image, Docker creates intermediate layers for each instruction in your Dockerfile. These layers are stored locally as the build cache. The cache allows Docker to reuse unchanged layers in subsequent builds, dramatically speeding up the process and reducing bandwidth usage.</p><p>How does it work?</p><ul><li>If a Dockerfile instruction and its dependencies (like files copied in a COPY command) haven’t changed, Docker reuses the cached layer instead of rebuilding it.</li><li>If something changes (for example, you update a file that gets copied), Docker invalidates the cache for that and all subsequent layers, rebuilding them from scratch</li></ul><p>Why is this cache useful?</p><ul><li>Faster builds: Reusing layers means Docker only rebuilds what’s necessary.</li><li>Less data transfer: Cached layers don’t need to be downloaded or rebuilt if they already exist locally.</li></ul><h3>Why Clean the Build Cache?</h3><p>Over time, especially in active development environments, the build cache can grow to tens of gigabytes. In my case, running docker system df revealed that the build cache alone was consuming nearly 31GB:</p><p>Use docker system df</p><pre>❯ docker system df<br>TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE<br>Images          9         7         13.35GB   4.533GB (33%)<br>Containers      16        4         356.7MB   740.4kB (0%)<br>Local Volumes   21        7         100.1GB   4.266MB (0%)<br>Build Cache     648       0         30.98GB   30.98GB</pre><pre>TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE<br>Build Cache     648       0         30.98GB   30.98GB</pre><p>If left unchecked, this cache can fill up your disk, impacting performance and potentially causing builds to fail due to a lack of space.</p><h3>How to Safely Remove Build Cache</h3><p>Docker provides a straightforward way to clean up this cache:</p><pre>docker builder prune</pre><p>You’ll see a warning before deletion. Confirming will remove all dangling (unused) build cache, freeing up space without affecting your images or running containers.</p><pre>❯ docker system df<br>TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE<br>Images          9         7         13.35GB   4.533GB (33%)<br>Containers      16        4         356.7MB   740.4kB (0%)<br>Local Volumes   16        7         100.1GB   3.026MB (0%)<br>Build Cache     163       0         0B        0B</pre><p>Advanced options:</p><ul><li>docker builder prune --all removes all unused cache, not just dangling ones.</li><li>docker builder prune --keep-storage &lt;size&gt; lets you specify how much cache to keep</li></ul><blockquote>Caution:<br>Pruning the build cache will not delete your images or containers, but it does mean your next build may take longer, as Docker will need to rebuild layers that were previously cached.</blockquote><h3>Can You Avoid Excessive Build Cache?</h3><p>Yes! Here are some best practices to optimise cache usage and avoid unnecessary buildup:</p><ul><li>Order Dockerfile instructions wisely: Place the least frequently changed instructions at the top. This maximises cache reuse for heavy steps like installing system packages.</li><li>Keep your build context small: Only include necessary files in your build context to avoid invalidating the cache with unrelated changes.</li><li>Use cache mounts and bind mounts: For package managers (like pip or apt), cache mounts persist downloaded packages between builds, further speeding up builds and reducing cache churn.</li><li>Regularly prune the cache: Make it a habit to run docker builder prune In your development workflow, especially after major changes or when disk space runs low.</li></ul><h3>Don’t Forget the Volumes — But Be Careful!</h3><p>While the build cache is a silent disk hog, volumes can also consume hundreds of gigabytes, especially if you run databases or data-heavy services in Docker. Before deleting a volume, always check if it’s in use:</p><pre>docker ps -a --filter volume=&lt;volume_name&gt;</pre><pre>❯ docker volume ls<br>DRIVER    VOLUME NAME<br>local     rythm_docker_5f3db004-d930-436b-bc64-81b04859fbe0<br>local     rythm_docker_6c81265a-d71c-42ac-a568-c1bb6fb2775a<br>local     rythm_docker_11c32c30-81d6-4078-a5fd-64950a06d19c<br>local     rythm_docker_71f7c6fa-2ac6-4bf9-b3ec-86216ad4d017</pre><p>If the result is empty, the volume is safe to remove:</p><pre>❯ docker ps -a --filter volume=rythm_docker_5f3db004-d930-436b-bc64-81b04859fbe0<br><br>CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES</pre><p>Use the following command to remove the volume:</p><pre>docker volume rm &lt;volume_name</pre><pre>❯ docker volume rm rythm_docker_5f3db004-d930-436b-bc64-81b04859fbe0</pre><p>Warning:<br>Deleting a volume that is still in use by a container will irreversibly erase all data stored in it. Always double-check!</p><h3>Conclusion</h3><p>Managing disk space in Docker is not just about removing unused volumes. The build cache can be an even bigger culprit. Regularly monitoring and pruning both volumes and building a cache will keep your environment healthy, build fast, and disk space under control. Just remember:</p><ul><li>Always check what you’re deleting.</li><li>Understand the impact on your workflow.</li><li>Use Docker’s cache wisely to balance speed and storage.</li></ul><p>By combining these strategies, you’ll avoid nasty surprises and keep your development environment running smoothly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=086b5c0c4073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe-Coding vs. Clean Code: The Battle Between Creativity and Consistency in Software Development]]></title>
            <link>https://flaviobritodata.medium.com/vibe-coding-vs-clean-code-the-battle-between-creativity-and-consistency-in-software-development-6e477cfa0c33?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e477cfa0c33</guid>
            <category><![CDATA[chatgtp]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Mon, 12 May 2025 14:29:12 GMT</pubDate>
            <atom:updated>2025-05-13T10:14:28.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDPWNP1dXmLLUtM-FHbDEQ.png" /></figure><h3>The Rise of a Controversial Coding Philosophy</h3><p>Imagine two chefs preparing the same dish in a professional kitchen. One follows a traditional recipe meticulously, measuring each ingredient with precision. The other cooks by intuition, adding a bit of this, a touch of that, guided by momentary creativity. This is exactly how we can visualise the clash between Clean Code and Vibe-Coding in the software development universe.</p><h3>What Exactly is Vibe-Coding?</h3><p>Vibe-coding is a programming approach that prioritises intuition and creative expression over rigid methodologies. It’s like a jazz musician improvising, in contrast to a classical musician strictly following the sheet music. “Vibe” developers believe that code should reflect the programmer&#39;s emotional and creative state.</p><h3>Clean Code: The Discipline of Programming</h3><p>Clean Code, popularised by Robert C. Martin, is the equivalent of a symphonic orchestra. Each line of code is a carefully positioned note, and each function is a precise movement. The methodology advocates for principles such as:</p><ul><li>Clean and readable code</li><li>Small functions with a single responsibility</li><li>Clear and meaningful naming</li><li>Consistent structure</li></ul><h3>Database Design: A Practical Comparison</h3><p>Database design is perhaps the most critical arena where the philosophical differences between Vibe-Coding and Clean Code become starkly apparent.</p><h3>Vibe-Coding: The Wild West of Data Modelling</h3><p>Imagine a database as a sprawling, unplanned city. Vibe-Coding is like urban development without zoning laws:</p><pre>-- Vibe-Coding Database: Chaos Embodied<br>CREATE TABLE users (<br>    id VARCHAR(255),  -- No consistent format<br>    name TEXT,        -- Unlimited, unvalidated text<br>    random_data JSONB -- Catch-all for any data<br>);<br><br>CREATE TABLE connections (<br>    user_id VARCHAR(255),  -- Inconsistent typing<br>    connected_user VARCHAR(255),  -- No constraints<br>    connection_type TEXT  -- Undefined, free-form<br>);</pre><p>Real-World Consequences:</p><ul><li>Data inconsistency: No guarantee of data quality</li><li>Performance nightmares: Unpredictable query performance, inefficient indexes, increased storage overhead</li><li>Scalability challenges: Difficult to enforce business rules, increased risk of data corruption</li></ul><h3>Clean Code: Architectural Precision</h3><p>Contrast this with a meticulously planned database ecosystem:</p><pre>-- Clean Code Database: Structured Excellence<br>CREATE TYPE user_status AS ENUM (&#39;active&#39;, &#39;inactive&#39;, &#39;suspended&#39;);<br>CREATE TYPE connection_category AS ENUM (&#39;professional&#39;, &#39;personal&#39;, &#39;academic&#39;);<br><br>CREATE TABLE users (<br>    id UUID PRIMARY KEY,<br>    email VARCHAR(255) NOT NULL UNIQUE,<br>    name VARCHAR(100) NOT NULL,<br>    status user_status DEFAULT &#39;active&#39;,<br>    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,<br>    last_login TIMESTAMP WITH TIME ZONE,<br>    CONSTRAINT valid_email CHECK (email ~* &#39;^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$&#39;),<br>    CONSTRAINT name_length CHECK (LENGTH(name) BETWEEN 2 AND 100)<br>);<br><br>CREATE TABLE user_connections (<br>    id UUID PRIMARY KEY,<br>    user_id UUID REFERENCES users(id),<br>    connected_user_id UUID REFERENCES users(id),<br>    connection_type connection_category NOT NULL,<br>    connected_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,<br>    UNIQUE(user_id, connected_user_id),<br>    CHECK (user_id != connected_user_id)<br>);</pre><p>Benefits:</p><ul><li>Strong data validation and integrity</li><li>Predictable performance and easier indexing</li><li>Enforceable business rules and reliable scalability</li></ul><h3>Real-World Scenario: E-commerce Platform</h3><p>Vibe-Coding Implementation:</p><pre>CREATE TABLE orders (<br>    id VARCHAR(255),<br>    product_details JSONB,<br>    customer_info TEXT<br>);</pre><p>Fast to launch, but hard to scale and maintain.</p><p>Clean Code Implementation:</p><pre>CREATE TYPE order_status AS ENUM (&#39;pending&#39;, &#39;processing&#39;, &#39;shipped&#39;, &#39;delivered&#39;, &#39;cancelled&#39;);<br><br>CREATE TABLE orders (<br>    id UUID PRIMARY KEY,<br>    customer_id UUID REFERENCES customers(id),<br>    total_amount NUMERIC(10,2) NOT NULL CHECK (total_amount &gt;= 0),<br>    status order_status DEFAULT &#39;pending&#39;,<br>    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,<br>    CONSTRAINT valid_total CHECK (total_amount &gt;= 0)<br>);<br><br>CREATE TABLE order_items (<br>    id UUID PRIMARY KEY,<br>    order_id UUID REFERENCES orders(id),<br>    product_id UUID REFERENCES products(id),<br>    quantity INTEGER CHECK (quantity &gt; 0),<br>    unit_price NUMERIC(10,2) NOT NULL<br>);</pre><p>Validated, scalable, and secure from the start.</p><h3>Comparative Analysis Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65sRZgEbPiCV-GZvcnYABA.png" /></figure><h3>The Real Cost of Maintenance</h3><p>A dish prepared by intuition might be delicious in the moment, but is hardly reproducible at scale. Similarly, Vibe-Coding carries significant costs:</p><h3>Costs of Vibe-Coding:</h3><ul><li>Difficult maintenance by other developers</li><li>High onboarding costs for new team members</li><li>Higher probability of unforeseen bugs</li><li>Inconsistent documentation</li><li>Scalability challenges</li></ul><h3>Advantages of Clean Code:</h3><ul><li>Easy project handover between teams</li><li>Reduced long-term maintenance costs</li><li>Greater predictability in development</li><li>More sustainable code structure</li><li>Easier debugging and testing</li></ul><h3>Additional Considerations</h3><h3>Performance Impact</h3><p>Clean Code isn’t just about readability, but also impacts:</p><ul><li>Code optimization</li><li>Resource utilization</li><li>System performance</li><li>Easier refactoring</li></ul><h3>Security Implications</h3><p>Vibe-Coding can introduce:</p><ul><li>Inconsistent input validation</li><li>Potential security vulnerabilities</li><li>Unpredictable error handling</li></ul><h3>Famous Failures Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oe_-O4eZ0p7C0vqxbK97fQ.png" /></figure><h3>Finding the Right Balance</h3><p>It’s not about eliminating creativity but channelling it intelligently. Clean Code doesn’t mean rigid code, but rather intelligently organised structure.</p><h3>Practical Tips for a Middle Ground</h3><ul><li>Use design patterns as a guide, not a straitjacket</li><li>Allow small “creative signatures” within a consistent framework</li><li>Document non-obvious design decisions</li><li>Keep clarity as the primary objective</li></ul><h3>Emerging Trends and Future Outlook</h3><p>As AI and machine learning evolve, the tension between creative coding and structured development will likely intensify. Tools are emerging that can:</p><ul><li>Automatically refactor code</li><li>Suggest clean code improvements</li><li>Detect potential maintenance issues</li></ul><h3>Conclusion</h3><p>In the real world of software development, Clean Code isn’t a villain killing creativity. It’s a framework that allows multiple brains to collaborate efficiently, reducing costs and increasing final product quality.</p><p>Vibe-Coding might be fun in personal or experimental projects. But when stakes are high-whether in startups, tech companies, or critical projects-Clean Code isn’t just a choice; it’s a strategic necessity.</p><blockquote>Where do you see the balance in your own projects? Have you experienced the thrill-or pain-of vibe-coding or the peace of mind from clean code? Share your stories in the comments!</blockquote><h3>References</h3><ol><li>Vibe Coding (Wikipedia)<br><a href="https://en.wikipedia.org/wiki/Vibe_coding">https://en.wikipedia.org/wiki/Vibe_coding</a></li><li>What Is Vibe Coding? (DataCamp)<br><a href="https://www.datacamp.com/blog/vibe-coding">https://www.datacamp.com/blog/vibe-coding</a></li><li>What is Vibe Coding? (IBM)<br><a href="https://www.ibm.com/think/topics/vibe-coding">https://www.ibm.com/think/topics/vibe-coding</a></li><li>Clean Code: A Handbook of Agile Software Craftsmanship — Robert C. Martin<br>[Book Reference]</li><li>The Art of Clean Code: Best Practices to Eliminate Complexity and Simplify Your Life — Christian Mayer<br>[Book Reference]</li><li>Software Development Best Practices in 2025 (Eluminous Technologies Blog)<br><a href="https://eluminoustechnologies.com/blog/software-development-best-practices/">https://eluminoustechnologies.com/blog/software-development-best-practices/</a></li><li>Database Design Basics (Microsoft Support)<br><a href="https://support.microsoft.com/en-us/office/database-design-basics-eb2159cf-1e30-401a-8084-bd4f9c9ca1f5">https://support.microsoft.com/en-us/office/database-design-basics-eb2159cf-1e30-401a-8084-bd4f9c9ca1f5</a></li><li>Case Study: The $440 Million Software Error at Knight Capital (Henrico Dolfing)<br><a href="https://www.henricodolfing.com/2019/06/project-failure-case-study-knight-capital.html">https://www.henricodolfing.com/2019/06/project-failure-case-study-knight-capital.html</a></li><li>How a Bug Cost Knight Capital Group $440 Million in 45 Minutes (LinkedIn Pulse)<br><a href="https://www.linkedin.com/pulse/how-bug-cost-knight-capital-group-440-million-45-june-katei-reeves-eejgf">https://www.linkedin.com/pulse/how-bug-cost-knight-capital-group-440-million-45-june-katei-reeves-eejgf</a></li><li>The Heartbleed Bug: Lessons Learned for System Administrators (TuxCare Blog)<br><a href="https://tuxcare.com/blog/heartbleed-bug/">https://tuxcare.com/blog/heartbleed-bug/</a></li><li>Mars Orbiter | Root Cause Analysis Case Study (ThinkReliability)<br><a href="https://www.thinkreliability.com/case_studies/root-cause-analysis-the-loss-of-the-mars-climate-orbiter/">https://www.thinkreliability.com/case_studies/root-cause-analysis-the-loss-of-the-mars-climate-orbiter/</a></li><li>Understanding the Failure of Software: Causes and Implications (Kodezi Blog)<br><a href="https://blog.kodezi.com/understanding-the-failure-of-software-causes-and-implications/">https://blog.kodezi.com/understanding-the-failure-of-software-causes-and-implications/</a></li><li>The Art of Clean Code by C. Mayer vs Clean Code by R. Martin (Reddit Discussion)<br><a href="https://www.reddit.com/r/SoftwareEngineering/comments/11edp3t/the_art_of_clean_code_by_c_mayer_vs_clean_code_by/">https://www.reddit.com/r/SoftwareEngineering/comments/11edp3t/the_art_of_clean_code_by_c_mayer_vs_clean_code_by/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e477cfa0c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Stakeholder Engagement in Requirement Management for IT Projects: Practical…]]></title>
            <link>https://flaviobritodata.medium.com/the-importance-of-stakeholder-engagement-in-requirement-management-for-it-projects-practical-aad047349ff8?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad047349ff8</guid>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[requirements]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[backlog]]></category>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 19:00:36 GMT</pubDate>
            <atom:updated>2024-09-12T19:00:36.643Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Importance of Stakeholder Engagement in Requirement Management for IT Projects: Practical Problems and Solutions</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QViwqpzmhFjHo7LMHuCijw.jpeg" /></figure><p>In IT project management, one of the biggest challenges for teams and managers is ensuring that requirements are well-defined, understood, and correctly prioritized. This is critical to the success of any project. However, backlogs often focus solely on technical or functional features, neglecting the necessary <strong>stakeholder engagement</strong>. This involvement ensures that requirements are mapped to real business needs. In this article, we’ll explore the importance of this engagement, discuss common problems that arise in requirement management, and offer practical solutions to avoid pitfalls that could compromise project success.</p><h3>Problem 1: Poorly Defined or Ambiguous Requirements</h3><p>One of the most common problems in IT projects is a lack of clarity in requirements. This usually happens when stakeholders are not sufficiently involved in the definition process, resulting in ambiguous or incomplete requirements. Imagine a development team that receives a request to create a “user-friendly interface.” Without a clear understanding of what “user-friendly” means for the end users, this specification becomes vague, leading to misinterpretations and delivery failures.</p><h4>Practical Solution:</h4><p>To avoid this issue, it’s essential to <strong>involve stakeholders</strong> from the outset. Running collaborative workshops or brainstorming sessions with end users, managers, and developers can help define detailed, aligned requirements. Tools like <strong>User Stories</strong> and <strong>Use Cases</strong> help describe the needs clearly and objectively, avoiding ambiguities.</p><p>For example, instead of requesting a “user-friendly interface,” the team could define it more clearly: “the interface should allow a user to complete a purchase process in three clicks or less.” This sets a measurable and tangible goal.</p><h3>Problem 2: Misaligned Priorities with Business Objectives</h3><p>Another recurring issue is the misprioritization of requirements. Often, development teams become overwhelmed with feature requests that don’t deliver immediate business value or are low in relevance. This happens when there’s no clear vision of strategic goals and which requirements are most important for achieving them.</p><h4>Practical Solution:</h4><p>Here, <strong>active backlog management</strong> based on business value criteria is essential. Prioritization tools like the <strong>MoSCoW method (Must have, Should have, Could have, Won’t have)</strong> ensure that the most important features are addressed first. It’s also vital to engage <strong>key stakeholders</strong> to ensure the backlog is continuously aligned with the company’s strategic goals.</p><p>One practical way to do this is by organizing regular <strong>backlog review meetings</strong> with the product team, where items are revisited and reordered based on continuous feedback. This prevents the team from focusing on low-impact tasks and ensures that resources are allocated to what brings the most business value.</p><h3>Problem 3: Lack of Flexibility for Changing Requirements</h3><p>The IT market is dynamic, and changing business needs are inevitable. However, teams that are not prepared to quickly adapt to these changes often face delays, rework, and stakeholder dissatisfaction. This happens when requirements are defined too rigidly, and there’s no clear process for continuous review and adjustment.</p><h4>Practical Solution:</h4><p>Implementing agile methodologies like <strong>Scrum</strong> or <strong>Kanban</strong> can help resolve this problem. These methodologies promote short development cycles (sprints) and frequent backlog reviews, ensuring that requirements can be adjusted quickly as new information arises.</p><p>For example, at the end of each sprint, holding a <strong>Sprint Review</strong> with all stakeholders helps validate if the deliveries meet expectations. If new requirements or adjustments are needed, they can be incorporated into the backlog for the next sprint, keeping the project dynamic and adaptable.</p><h3>Problem 4: Misalignment Between Technical and Business Teams</h3><p>There is often a lack of understanding between technical and business teams. This leads to situations where the delivered features don’t meet business expectations, or the development team underestimates the complexity of certain requirements. This misalignment can result in delays, rework, and frustration for both the team and stakeholders.</p><h4>Practical Solution:</h4><p>The solution is to ensure <strong>continuous and transparent communication</strong> between teams. Involving <strong>Product Owners</strong> or <strong>Business Analysts</strong> in the development process helps bridge this gap. They act as intermediaries, translating business needs into technical terms and vice versa, ensuring that everyone is on the same page.</p><p>Daily <strong>Scrum meetings</strong> (Daily Stand-ups) are also useful to keep everyone informed about project progress and challenges. These meetings ensure that misunderstandings can be resolved quickly before they negatively impact the project.</p><h3>Problem 5: Unidentified or Underestimated Risks</h3><p>Often, project risks are not adequately identified during the planning and requirement definition stages. This can lead to unpleasant surprises during execution, such as delays due to technical limitations or rework due to unforeseen requirement changes.</p><h4>Practical Solution:</h4><p>A well-prepared <strong>Business Case</strong> is essential to identify and mitigate risks from the beginning. It helps the team understand the potential challenges and obstacles — such as technological constraints, resource limitations, or regulatory changes — and define contingency plans to handle these risks.</p><p>Additionally, performing a <strong>continuous risk analysis</strong> throughout the project allows the team to proactively respond to new threats. Using <strong>risk management tools</strong>, like impact and probability matrices, facilitates risk prioritization and the definition of mitigation strategies.</p><h3>Problem 6: Growing Backlog Without Strategic Alignment</h3><p>As a project progresses, it’s common for the backlog to grow. However, without properly mapping and aligning requirements with project objectives, this growth can become <strong>uncontrolled</strong>. The backlog starts to include tasks and features that aren’t a priority or don’t bring direct business value, turning into a <strong>wish list</strong>. When this happens, the development team becomes overwhelmed with tasks that seem urgent but are not strategically aligned with expected results.</p><p>This type of bloated, disorganized backlog can:</p><ul><li>Increase project management complexity.</li><li>Distract from the most important deliverables.</li><li>Cause delays and frustrate stakeholders who don’t see tangible value being delivered.</li></ul><h4>Practical Solution:</h4><p>To prevent the backlog from becoming a list of ad-hoc tasks, it’s crucial to ensure <strong>continuous strategic alignment</strong>. This can be done in several ways:</p><ol><li><strong>Periodic backlog reviews</strong>: Regularly review the backlog with all stakeholders to reassess the relevance and priority of each item. Requirements that are no longer aligned with project objectives should be removed or deprioritized.</li><li><strong>Clear prioritization criteria</strong>: Use frameworks like <strong>Value vs. Effort</strong> or <strong>Impact vs. Urgency</strong> to identify which items should be prioritized. This prevents the backlog from becoming bloated with low-value tasks.</li><li><strong>Focus on the MVP (Minimum Viable Product)</strong>: In many cases, a large backlog results from trying to anticipate all possible scenarios and solutions at once. Focusing on delivering an <strong>MVP</strong> and evolving from there ensures the backlog grows organically and is more aligned with real project needs.</li><li><strong>Task Admission Filter</strong>: Create a filter for new items being added to the backlog, where each task goes through a rigorous analysis: Does it truly meet a strategic need, or is it a feature that can wait? This process ensures the backlog remains lean and efficient.</li></ol><h3>Problem 7: Lack of Monitoring of Feature Usage</h3><p>A significant issue that often arises is the <strong>lack of monitoring of the actual usage</strong> of features requested by business areas. Features may be delivered, but without tracking their real adoption or usage, the team may continue to receive new feature requests without evidence of their value. This leads to an <strong>overload of demands</strong> that may not be truly necessary, overwhelming development teams with work that doesn’t generate impactful results.</p><h4>Practical Solution:</h4><p>To address this, it’s important to implement <strong>post-delivery monitoring</strong> of features. By using tools like <strong>analytics dashboards</strong> or <strong>usage metrics</strong>, teams can track which features are being used and to what extent. If a feature is rarely or never used, it raises a red flag for future prioritization.</p><p>Additionally, incorporating <strong>feedback loops</strong> with business stakeholders ensures that new feature requests are based on evidence and real business needs, not just assumptions. This helps prevent the backlog from becoming overloaded with low-value items.</p><h3>Conclusion</h3><p>Managing requirements in IT projects goes far beyond simply listing features in a backlog. <strong>Engaging stakeholders</strong>, aligning with business objectives, and quickly adapting to changes are critical to success. When the backlog grows without control or strategic alignment, it can become a collection of ad-hoc tasks that delay the project and divert the team’s focus.</p><p>To avoid these problems, it’s crucial to continuously review the backlog, prioritize based on business value, and ensure that each added item has a clear strategic justification. This way, IT projects can be managed efficiently, delivering value and staying focused on the most important objectives for the business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad047349ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Data Engineers Can Build More Efficient Solutions Using BigQuery and Python to Help Data…]]></title>
            <link>https://flaviobritodata.medium.com/how-data-engineers-can-build-more-efficient-solutions-using-bigquery-and-python-to-help-data-2be4875cc4a2?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be4875cc4a2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 17:52:26 GMT</pubDate>
            <atom:updated>2021-08-17T17:52:26.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Data Scientists Can Increase Their Productivity With the Aid of Data Engineers Solutions Using BigQuery, Google Colab and Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gh5FqYu-0b_qaLLPvj6HfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@robwingate?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rob Wingate</a> on <a href="https://unsplash.com/s/photos/tour-de-france?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article aims to bring a set of solutions in Python used by Data Engineers that will increase the productivity of Data Scientists that needs to use Google BigQuery in daily operations and just want this thing to work!</p><p>Before we start, I would like to talk about an amazing tool that is helping many Data Engineers and Data Scientists in their daily projects.</p><p>Did you hear about Google Colab? No, this is a spectacular online notebook based platform that provides you with a free cloud service environment to develop powerful solutions using Python or R that brings you superpowers to deal with your Data in BigQuery and Google Cloud Storage. But you can also connect AWS S3 buckets with it, for example.</p><blockquote>Grab a cup of coffee and let’s type cool Python codes.</blockquote><h3>Set up your Google Colab Notebook</h3><p>Considering that you already have a Google account, go to</p><pre><a href="https://drive.google.com/">https://drive.google.com</a></pre><p>There you can create a <strong>folder ( Click on + New, then Foder) </strong>to keep the notebooks or to create a notebook if you are already in your Google Drive, click in <strong><em>+New &gt; Folder &gt; More &gt; Google Colaboratory, </em></strong>as shown in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*uCzXrBvkNnEkAtDGlLvJbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0BoBR7RrGQAiOO_XEvzag.png" /></figure><p>Following the numbers, you can see:</p><ol><li>Code — to add a new <strong>code</strong> notebook cell. And Text to add a <strong><em>text</em></strong> notebook cell</li><li>Notebook cell with a play button in the beginning to run the code</li><li>RAM and Disk spaces. Google Colab has a good start in the free version that offers you 12 GB of RAM to process your code. Nice! You can continue working on your local machine and let Google Colab do the hard work!</li><li>Notebook cell tool- Arrows (Up/Down) used to organize moving each cell up and down, link — a URL linking the cell content, gear — cell settings, mirror the cell, trash — delete cell</li><li>Folders and Files — place to create folder and store files to be used by the Notebook.</li></ol><p>In a free option you can import/ export data from Google Drive, Google Cloud Storage, BigQuery and also use GPU!</p><p>A GPU can be used to improve the code performance.</p><h4>Colab provides GPU and it’s totally free!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*GINMDPkHQ0Pdc7uE1ydVXg.png" /></figure><p>Go to the main menu and click on <strong><em>Runtime / Change Runtime Type. </em></strong>By default, no hardware accelerator is provided.</p><p>Do you need more power? Google also offers a Google Colab Pro version.</p><h4>Python Packages</h4><p>Many packages are pre-installed and others you can install by running:</p><pre>!pip install package_name</pre><p>or if you need to forcefully remove and install again the package from a specific version you can do:</p><pre>!pip install ‘package_name==1.2.5’ —- force-reinstall</pre><p>where package_na is the name of the package that you need and 1.2.5 is a specific version and <em>force-reinstall </em>is the parameter option to force the package reinstallation if it already had installed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05cab7b949be6666114676e2b3b66f30/href">https://medium.com/media/05cab7b949be6666114676e2b3b66f30/href</a></iframe><p>To use BigQuery from python code it&#39;s necessary to import bigquery from <em>google.cloud. </em>In the case of running code from Google Colab, there is no need to install it, but it probably will be necessary outside. A good practice is to install from requirements.txt file, defining the package name or package name==version_ number.</p><p><em>requirements.txt</em></p><pre>google-cloud-bigquery==2.24.0</pre><p>Before installing some packages, list the python packages offered by Google Colab running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PV9wqzdZjis5PTOE3rmFhg.png" /></figure><h4>Troubleshooting</h4><p>If you have some issues trying to install python packages, check the Google Colab python version provided running in the notebook cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*Ta4HTrwpvdFjyIIs_HzEWQ.png" /></figure><h3>Google Colab Authentication</h3><p>Running the imports previously described, the Google Colab authentication process will be invoked — auth method from google.colab. It will prompt a message given you an Authentication URL, asking you to return a verification code generated by the authorization session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*XCfJaewmGjzy0lChXc58oQ.png" /></figure><p>Click on the link and return the code from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*f6SZ-r-A91lsi25PES7q5A.png" /></figure><p>This process will be necessary whenever you connect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*u62ZYUTMYxGu1CH5uIDyzA.png" /></figure><p>Copy the code, and paste in a box &quot;<strong>Enter verification code</strong>&quot;.</p><p>Now that you have your credentials valid let&#39;s do our job.</p><h3>HOW TO …</h3><h3>List Tables from a Dataset using BigQuery CLI</h3><p>Google Colab give you a set of pre-installed tools to work with BigQuery. The most important is the Python script for interacting with it — <em>bq</em> <br>You can call running:</p><p>!bq --global_flags] &lt;command&gt; [--command_flags] [args]</p><p>To check all commands run on Google Colab cell:</p><p>!bq --help</p><p>To check all flags run:</p><p>!bq --helpful</p><p>To list all tables in BigQuery you can run the <em>bq</em> client command with 3 parameters, in this example:</p><ul><li>ls: for list</li><li>project: data-analytics-live</li><li>dataset_id: silver_raw</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*w24u8tGsaHj_DG7GKMzAwQ.png" /></figure><h3>Use BigQuery via magics</h3><p>The `google.cloud.bigquery` library also includes a magic command which runs a query and either displays the result or saves it to a variable as a `DataFrame`.</p><pre>%%bigquery</pre><p>The magics command (%%) lets the notebook knows you are about to load BigQuery data.</p><pre>%%bigquery --project datasyncbq</pre><pre>SELECT table_schema,table_name</pre><pre>FROM datasyncbq.datasync.INFORMATION_SCHEMA.TABLES</pre><pre>WHERE table_type=&#39;VIEW&#39;;</pre><p>The code above will return the table schema and table name attributes from BigQuery information schema tables where the table type is a view from the project datasyncbq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*kUto7n2If0787snywmEzIA.png" /></figure><p>Add a DataFrame name to export the query outcome:</p><pre>%%bigquery --project datasyncbq <strong>df</strong></pre><pre>SELECT table_schema,table_name</pre><pre>FROM datasyncbq.datasync.INFORMATION_SCHEMA.TABLES</pre><pre>WHERE table_type=&#39;VIEW&#39;;</pre><h3>List Tables from BigQuery Dataset using Python</h3><p>BigQuery python library has many features and to access it, you need to import bigquery from google.cloud package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*g8C1hsKD-RDISNGlmldZ4A.png" /></figure><p>To add the project name, you can include in the format:</p><p><em>table.project</em></p><pre>for table in tables:<br>   print(&quot;{}.{}.{}&quot;.format(table.project, table.dataset_id, table.table_id))</pre><h3>BigQuery Metadata — List All Tables From BigQuery</h3><p>BigQuery contains these views for table metadata:</p><ul><li>TABLES and TABLES_OPTIONS — metadata about TABLES and VIEWS.</li><li>COLUMNS andCOLUMNS_FIELDS_PATHS metadata about columns and fields.</li><li>For metadata about table partitions — PARTITIONS</li></ul><pre>SELECT * FROM PROJECT_ID.DATASET_ID.INFORMATION_SCHEMA.TABLES</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*TevQMLRibes4vRSSmdujjQ.png" /></figure><p>The image above is part of the command output. In this case, I would like to get the table name, column name, and if it&#39;s null or not, the data type of the field, and if it is a field used in a partition of a specific table(<em>data_sync_data</em>).</p><p>So far so good, you learned in this first part:</p><ul><li>How you create a Google Colab notebook,</li><li>Enable a GPU power,</li><li>Connect Google Colab and BigQuery using python code and magic command to process SQL queries</li><li>How to retrieve metadata from BigQuery</li></ul><h3>Read BigQuery Data Using Pandas</h3><p>The pandas-gbq the library covers basic functionality, such as writing a DataFrame to BigQuery and running a query, but as a third-party library, it may not handle all BigQuery features or use cases.</p><p>In the below example we call read_gbq function passing the query that uses public data from bigquery-public-data.</p><blockquote>The table contains the number of applicants for a Social Security card by year of birth and sex. The number of such applicants is restricted to U.S. births where the year of birth, sex, State of birth (50 States and District of Columbia) are known, and where the given name is at least 2 characters long. source: <a href="http://www.ssa.gov/OACT/babynames/limits.html">http://www.ssa.gov/OACT/babynames/limits.html</a></blockquote><p>We defined the dialect parameter as &#39;standard&#39;, that uses BigQuery&#39;s standard SQL, which is compliant with the SQL 2011 standard and the default<strong><em> ‘legacy’ </em></strong>that<strong> </strong>uses BigQuery’s legacy SQL dialect. Another parameter that we pass is project_id that came from a variable with the same name. The outcome is a sum of occurrences of a specific name from the state = &#39;TX&#39;, Texas, grouping then by name and organising in descending order by the count value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*yo_MujRUJ0p1iSjJx4poZg.png" /></figure><h3>Convert DataFrame to JSON</h3><p>Exporting a Data Frame to a JSON string or file can be done using a special functionto_json .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*7BQoY6jAb4R-9YvQc-6Kvw.png" /></figure><p>Here we created a pandas Data Frame based on the SQL query outcome. The bq_credentials came from a:</p><pre>bq_credentials = service_account.Credentials.from_service_account_info (<br>{ JSON - Credentials}<br>)</pre><p>See more in the Credentials session of this tutorial.</p><p>The pandas DataFrame has a function to_json(oriented=&quot;records&quot;) that converts a Data Frame object to JSON string using the parameter oriented to indicate of expected JSON string format. In this case:</p><pre>records : list like [{column -&gt; value}, … , {column -&gt; value}]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Xc-2mG9GZAlws0zQrHXkzQ.png" /></figure><p>BigQuery and Google Colab are amazing solutions, but what if you want to get data from a spreadsheet? There are some options, like using pandas to read a Microsoft Excel file from Google Drive or read Google Sheets as a data source.</p><h3>Load Data From Google Sheet to Pandas</h3><p>In this tutorial, I will explain how to connect and read data from Google Sheets. here we will use a package named <em>gspread</em>. This package is a Python API for Google Sheets. There are interesting features like:</p><ul><li>Google Sheets API v4.</li><li>Open a spreadsheet by title, key or URL.</li><li>Read, write, and format cell ranges.</li><li>Sharing and access control.</li><li>Batching updates.</li></ul><p>To install it in other projects, including in the <em>requirements.txt</em></p><pre>gspread==3.0.1      </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*RdPTutqh6jFe6RY_tA743w.png" /></figure><p>In this example, we are importing these modules to authenticate on Google Colab and using them on GoogleCredentials.</p><pre>from google.colab import auth<br>auth.authenticate_user()<br>import gspread<br>from oauth2client.client import GoogleCredentials</pre><pre>import pandas as pd</pre><p>A pandas data frame will be created to store the data read. The code snippet below is the core of the setup, where we pass the credentials and the defined Google Sheet, in this example, the name is &#39;BigQuery - DataSync - First Cleaning&#39; and sheet1 is the first sheet to be considered.</p><pre>gc = gspread.authorize(GoogleCredentials.get_application_default())<br>worksheet = gc.open(&#39;BigQuery - DataSync - First Cleaning&#39;).sheet1</pre><h3>Getting All Values from a Google Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*ynuvQquCXKT6dGsyULRRCA.png" /></figure><p>To get all values from the defined sheet, we need to use the get_all_values() function associated with the worksheet object already defined passing to a variable data. We usedpop(0) function passing 0 to retrieve all headers of the Google Sheet.</p><p>Now having data and header, it&#39;s possible to create a pandas(<em>pd</em>) DataFrame passing data to the data parameter and headers to columns. As we are using Google Colab we don&#39;t need to print the DataFrame (df), only invoke in a separate line.</p><pre>data = worksheet.get_all_values()<br>headers = data.pop(0)<br>df = pd.DataFrame(data, columns=headers)<br>df</pre><h3>Create a Function to Delete Multiple Tables in Batch from BigQuey Using Google Sheet</h3><p>In Data Engineering it&#39;s important to automate procedures, one of them is to delete tables in batch in BigQuery. We can use Google Sheet to store tables metadata that we will use in the delete procedure.</p><p>In the code below there is a function that expects to receive two parameters, table_path which is a concatenation of dataset_id and table_id and the project_id, that identifies the BigQuery project name. We created an instance of BigQuery client and call delete_table(table_id, not_found_ok=True) a function that deletes a table (table_id) and ignores if a table is not found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHXsFUoP0eEMowV19-Etow.png" /></figure><p>After that we created a for-loop that for all DataFrame df rows, concatenate a dataset_id and table_id with a point connecting both strings and passed to project_dataset_tabel_path variable, calling delete_tables function passing the project_dataset_tabel_path and the project_id for each row retrieved.</p><h3>Create Multiple Tables Delete Command Using BigQuery CLI command and BigQuery Compose Interface</h3><p>BigQuery can also be accessed and operated using the <em>bq</em> command. Is it possible to create BigQuery console commands using the BigQuery Compose interface.</p><p>the command is bq rm -f -twhere:</p><ul><li><em>bq</em> is BigQuery command</li><li><em>rm</em> is to remove the tables</li><li>- f is to force without ask</li><li>- t is a table name</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*EpDtr4qYmw5TePSpWcf3IQ.png" /></figure><p>Generating commands in batch using SQL is very useful in Data Engineering to avoid typos, missing quotes and to improve productivity. The outcome can be saved to Google Drive as CSV, JSON and also to the local file if you click on Save Query Results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*arRCUYP2YEBhz8SR6ZFzng.png" /></figure><p>You can run the exported commands from a BASH file to remove the tables.</p><p>For more details about BigQuery CLI, visit the following page</p><p><a href="https://cloud.google.com/bigquery/docs/reference/bq-cli-reference">https://cloud.google.com/bigquery/docs/reference/bq-cli-reference</a></p><h3>Create a SQL Command for Dropping Tables BigQuery Metadata</h3><p>Using the same idea it&#39;s possible to create SQL commands using BigQuery metadata. We can concatenate a &quot;DROP TABLE&quot; statement with table_schema and table_name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*nIPmV-w2STKkrDZhEV33rw.png" /></figure><h3>Export BigQuery Table Schema to JSON using BigQuery CLI</h3><p>Export BigQuery table schema is very useful if you need to reprocess a complex table schema. To demonstrate it, use <em>show</em> to display information about a resource with --schemato display only the table’s schema with a flag prettyjson: easy-to-read JSON format.</p><pre>!bq show --schema --format=prettyjson data-analytics-live:datasync.daily_sync_data &gt; daily_sync_data.json<br>!cat daily_sync_data.json</pre><h3>Create a Table with Partition based on a SELECT</h3><p>A partition table is a large table that is divided into small segments (partitions) to make it easier to manage by BigQuery. Using it we can reduce the cost of a query processed because we are reducing the number of rows processed. If the query filters on the value of the partitioned column, BigQuery will skip the partitions that don&#39;t match the filter.</p><p>Steps</p><ol><li>Create a SELECT casting and added new fields</li><li>Create a CREATE TABLE command adding PARTITION BY statement with the field name. Partition by field need to be CAST as DATE</li><li>Compose a query with both</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*LX1kMO8ELxN8aH2jtUaIhQ.png" /></figure><p>So far so good, you learned in the second part:</p><ul><li>List Tables from a Dataset using BigQuery CLI</li><li>Use BigQuery via magics</li><li>List Tables from BigQuery Dataset using Python</li><li>BigQuery Metadata — List All Tables From BigQuery</li><li>Use BigQuery through pandas-gbq</li><li>Read BigQuery Data Using Pandas</li><li>Load Data From Google Sheet to Pandas</li><li>Create a Function to Delete Multiple Tables in Batch from BigQuey Using Google Sheet</li><li>Create Multiple Tables Delete Command Using BigQuery CLI command and BigQuery Compose Interface</li><li>Create a SQL Command for Dropping Tables BigQuery Metadata</li><li>Export BigQuery Table Schema to JSON using BigQuery CLI</li><li>Create a Table with Partition based on a SELECT</li></ul><h3>BigQuery Credentials</h3><h3>Reading BigQuery Credentials from Dictionary</h3><p>BigQuery credentials can be passed as a Python dictionary or by JSON File, in the following example, we used theservice_account.Credentials.from_service_account_info() function passing a Python dictionary. You need to replace the values in uppercase with your BigQuery credential values.</p><pre>bq_credentials = service_account.Credentials.from_service_account_info (<br>{ <strong>Credentials</strong>}<br>)</pre><p>where <em>Credentials</em><strong> </strong>is the dictionary (key and values) that you downloaded from Google Cloud Platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*eFl1NRhwoOAoDptmq_nYiQ.png" /></figure><p>replace, PROJECT_NAME, PRIVATE_ID,PRIVATE_ID_KEY,EMAIL,CLIENT_ID with the value of your credentials.</p><h3>Reading BigQuery Credentials from JSON File</h3><p>BigQuery credentials can be stored in a JSON file, the most common way to use it, and can be read using thefrom_service_account_fileto authenticate with a service account key file or passing a dictionary through <em>service_account.Credentials.from_service_account_info</em> function</p><p>In the following example, we illustrate how to do it using a JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zx4ZZW4qUufjtNf9ktlBuQ.png" /></figure><pre>service_account_json_file_name = &quot;app/config/credentials/bigquery_credentials.json&quot;</pre><p>create a variable credentials that received the service account credential got from the functionfrom_service_account_file(file, scope) that expects the file name with path and the scope of the credential.</p><pre>credentials = service_account.Credentials.from_service_account_file(<br>service_account_json_file_name, scopes[&quot;https://www.googleapis.com/auth/cloud-platform&quot;],)</pre><p>So far so good, you learned in the last part:</p><ul><li>Read BigQuery credentials from a dictionary and from a JSON file</li></ul><h3>Conclusion</h3><p>In this article, we showed focused solutions using BigQuery and Google Colab using Python to improve Data Scientists and Data Engineers productivity.</p><p>You can check the author’s <a href="https://github.com/flaviobrito"><strong>GitHub repositories</strong></a><strong> </strong>for code, ideas, and resources in data science and data engineering. Please feel free to add me on <a href="https://www.linkedin.com/in/flaviobrito/">LinkedIn</a> or follow me on <a href="https://twitter.com/flaviobritodata/">Twitter</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be4875cc4a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Super-Fast and Sharp Way to Send E-mails from an ETL Pipeline Python Code Using Gmail API —…]]></title>
            <link>https://flaviobritodata.medium.com/a-super-fast-and-sharp-way-to-send-e-mails-from-an-etl-pipeline-python-code-using-gmail-api-ebe041881756?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe041881756</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 16:55:02 GMT</pubDate>
            <atom:updated>2021-08-09T17:21:46.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Super-Fast and Sharp Way to Send E-mails from an ETL Pipeline Python Code Using Gmail API — Starting with Setting the Credentials all the way to Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhW-IR7S3z9xkTWPHbY0cg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@carlheyerdahl?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carl Heyerdahl</a> on <a href="https://unsplash.com/s/photos/e-mail?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Gmail is undoubtedly a great e-mail service from Google, to use it to its fullest capacity requires some knowledge of how to configure the service’s API as well as enable authentication via OAuth2. All these steps are well documented here:</p><p><a href="https://developers.google.com/gmail/api/quickstart/python">https://developers.google.com/gmail/api/quickstart/python</a></p><p>Good practice in the case of an ETL Pipeline is to not use a username and password for authentication.</p><p>I’ll take a two-step approach, the first one demonstrating how to set up credentials and the last one how to use a library that encapsulates the complexity of the API code and does what has to be done with a few lines of code.</p><h3>Enabling Gmail API</h3><p>To develop a solution using the GMAIL API is necessary that your GCP user has permission to enable the API service before start.</p><p>Check-in <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a></p><p>If you don’t have permissions you will receive a message like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*6R759uuJdvmHWSYWEwYxTQ.png" /></figure><p>Ask the GCP administrator to give access to your user to enable the API and also create the credentials.</p><p>The GMAIL service has its own API, you need to enable it by going to <strong>APIs &amp; Services</strong> menu and then click on <strong>API Library</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZM1Ck0UGurzdYbPQj9UYA.png" /></figure><p>Then you will find a button to ENABLE. If it is already enabled you will see the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Mz7RUJ7WmxgoXik_9HMdew.png" /></figure><h3>Creating Credentials</h3><p>This step aims to create a new OAuth 2.0 Client ID to be used in our code. To do it, click on + CREATE CREDENTIALS link on the top of the page and select OAuth Client ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*J_AcamRVRBJZ_hd-CsDJIw.png" /></figure><p>Now that GMAIL API was enabled, you need to configure the scope and also the OAuth process Application type and select Web application. In our case, we will use it in a pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVxXqZJWqmAaVEjyE0u2mA.png" /></figure><p>You can choose a name to the OAuth 2.0 client and add in Authorized redirect URIs a:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yifkhSCFVyemEUXf-ddxUg.png" /></figure><p>Select Web application and redirect URI is</p><p><a href="https://developers.google.com/oauthplayground">https://developers.google.com/oauthplayground</a></p><p>Copy and save the credentials and Go to this URL and follow the steps that will appear on the right side of the page. Download the JSON credential file from the link on the top of the page.</p><h3>OAuth 2.0 Configuration</h3><p>Click in the <strong>gear</strong> icon on the top right and mark <strong>Use your own OAuth credentials</strong> filling ****the <strong>OAuth Client ID</strong> and ****the <strong>OAuth Client secret.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*vXaaqJaexIX0ZbRnw8RvpA.png" /></figure><p>In the step Select &amp; Authorize APIs, select Gmail API v1 and click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*9ycD4nRDosCvHY8uOQRkgA.png" /></figure><p>Then click the “Authorize APIs” button.</p><p>There is no need to add domain verification and page usage.</p><p>Now is the time to talk more about how we can simplify the sender code.</p><p>SMTP Client Library</p><p>There are some interesting libraries as SMTP client but one that caught my attention was <em>yagmail</em>. This library is easy to install and use. In an ETL process, we need a solution that can use Gmail OAuth2 credentials and accept attaches. Touchê, <em>yagmail</em> do it elegantly.</p><p>As <em>yagmail</em> in the requirements.txt file, I am using the version:0.14.256</p><pre>yagmail==0.14.256</pre><p>if you want you can install it on Google Collab to test. In a cell you can run:</p><pre>!pip install yagmail</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhtlSBVpyGzMx9BitFM5Ng.png" /></figure><p>If you are still using Google Collab, you need to upload the JSON credential file, otherwise, the yagmail will ask for the user&#39;s mail. If it happens you can have an odd behaviour and there is no guarantee that the e-mail will be sent.</p><p>Moving on, the main page of the library you will find a small but important demo code that will give an idea of basic use.</p><p><a href="https://pypi.org/project/yagmail/">https://pypi.org/project/yagmail/</a></p><h3>Implementation</h3><p>We must have an implementation to keep it sharp and dry. To do it let&#39;s create a file into a common code folder that we can call whenever we want.</p><p><em>gmail_client.py</em></p><pre><strong>import </strong>yagmail<br><br><br><strong>class </strong>Gmail(yagmail.SMTP):<br>    <strong>def </strong>__init__(self):<br>        super().__init__(oauth2_file=<strong>&quot;app/apis/gmail_credentials.json&quot;</strong>)<br><br>    <strong>def </strong>send_mail(self, toaddr, subject, message, attachment_files=<strong>None</strong>):<br>        self.send(to=toaddr, subject=subject, contents=message, attachments=attachment_files)</pre><p>In this code, I created a Gmail class that inherits <em>yagmail</em>.SMTP. As I am passing to oauth2_file parameter a JSON credential&#39;s filename instead of user and password, that is stored, in this case, in app/apis folder project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*ptsy9ydEMi-N7P5rsi5rgg.png" /></figure><p>You can use the <em>yagmail</em> send method,</p><p>Instance of Gmail</p><pre>mail = Gmail()</pre><p>calling send method</p><pre>mail.send(&quot;TARGET_EMAIL&quot;,&quot;SUBJECT TEXT&quot;,&quot;BODY TEXT&quot;,attachments=&quot;./report_.pdf&quot;)</pre><p>In this case, there are some important parameters that you need to consider. If don&#39;t need to add attachments, remove this parameter from the method call.</p><pre>mail.send(&quot;TARGET_EMAIL&quot;,<br>          &quot;SUBJECT TEXT&quot;,<br>          &quot;BODY TEXT&quot;,<br>          attachments=&quot;FILE_PATH_NAME&quot;)</pre><p>but in my case, I was replacing a send_mail method used by all ETL Pipelines, this is a nice example of how to do it if you need it.</p><pre><strong>def </strong>send_mail(self, toaddr, subject, message,attachment_files=<strong>None</strong>):<br>        self.send(to=toaddr, subject=subject, contents=message, attachments=attachment_files)</pre><p>Now you need to import the class into the pipeline code as:</p><pre><strong>from </strong>app.data_integration.gmail_client <strong>import Gmail</strong></pre><p>In this case, the pipeline path that will invoke the Gmail client features is:</p><p><em>app/data_integration /</em></p><p>and into this folder, we created the <em>gmail_client.py</em> as described previously.</p><p>As we want to only invoke if the pdf file was generated to be attached, we need to check if the variable is empty, if not we will call the send_mail method.</p><pre>if pdf_file_name:<br>   gmail = Gmail()<br>   gmail.send_mail(email_receiver, email_subject, email_contents, [pdf_file_name])</pre><p>The code below demonstrates how you can replace dynamically the email contents parameters between @@ symbols (a way to avoid mysterious characters) that came from a SQL result where</p><ul><li>@@start-date@@ will be replaced by custom_start_date</li><li>@@end-date@@ will be replaced by custom_end_date</li></ul><p>for example, if <em>csv_created</em> ( a variable that has a value different from <em>None</em> if a CSV was created successfully).</p><pre>if csv_created:<br>               <br>   gmail = Gmail()<br>   <br>   email_contents = email_contents.replace(&#39;@@start-date@@&#39;, custom_start_date).replace(&#39;@@end-date@@&#39;, custom_end_date)<br>   <br>   gmail.send_mail(email_receiver, email_subject, email_contents, [pdf_file_name, csv_file_name])<br>   <br>   logging.info(f&quot;Email for {customer_name} sent to {str(email_receiver)}&quot;)</pre><p>A logging message will be printed in the ETL pipeline log telling each user the send_mail method was called.</p><h3>Summary</h3><p>In this article, we are focused on how we implement, set up and use Gmail API service with few lines of code from an ETL Pipeline, and how to improve your productivity.</p><p>Please feel free to add me on <a href="https://www.linkedin.com/in/flaviobrito/">LinkedIn</a> or follow me on <a href="https://twitter.com/flaviobritodata/">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe041881756" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering and Data Science Bulletproof using Git and GitHub]]></title>
            <link>https://flaviobritodata.medium.com/data-engineering-and-data-science-bulletproof-using-git-and-github-77e1b737c9d2?source=rss-7775a14eeed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e1b737c9d2</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Flávio Brito]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 18:28:12 GMT</pubDate>
            <atom:updated>2021-08-13T06:57:56.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN-WosGeloEJvVvoK2Iyew.jpeg" /></figure><h3>Introduction</h3><p>GitHub is an online language agnostic platform, based on git, capable of tracking and save the project code and data as private or public projects.</p><p>Before version control era, multiple backup files kept many complete copies of the same project directory, named like this: version_01, ver_01.10. Seemed to be a mess, yes it really was. But as developers we needed to find a way to control the changes, using a simple file or put some comments on code. When something went wrong we needed to search into many folders to check if we figure out the differences. I don’t need to say that was many hours redoing tasks.</p><p>After many years, others version control solutions were create to help developers control better projects code. Git started to become popular when a well developed portal created a set of features to help open source community to develop and share, inspired in a bazar idea, everybody could download a project and start to collaborate.</p><p>The idea of this article is to bring you some kind of integration with the GIT and GitHub solutions, and also bring out some ideas for you to keep under your utility belt. Let’s rock!</p><h3>Install GH CLI</h3><p>There is a visual way to create a remote repository in GH</p><p>To do it, you need to login in you GH account and click on the (+) at the top right of the GH page as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*IINbncDF_gA0nSew2hty0A.png" /></figure><p>As a Data guy, probably you will be curious about how to do things from command line. Let’s talk about how to do it.</p><p>Another way is to do it by GH cli command. To do it, you need to install the GH CLI. Using a MAC you can download the client from <a href="https://cli.github.com/">https://cli.github.com/</a> page or run.</p><pre>brew install gh</pre><h3>Authentication</h3><p>After installing it, you need to authenticate doing this:</p><pre>gh auth login<br>? What account do you want to log into?  [Use arrows to move, type to filter]<br>&gt; <strong>GitHub.com</strong><br>  GitHub Enterprise Server</pre><p>The <a href="http://github.com/">GitHub.com</a> site is per default, you can only hit &lt;ENTER&gt;</p><p>After it, GH cli will ask you which protocol you will prefer to use for authentication. Let’s use HTTPS</p><pre>? What is your preferred protocol for Git operations?  [Use arrows to move, type to filter]<br>&gt; <strong>HTTPS</strong><br>  SSH</pre><p>Now, you need to inform about the credentials</p><pre>? How would you like to authenticate GitHub CLI?  [Use arrows to move, type to filter]<br>&gt; <strong>Login with a web browser</strong><br>  Paste an authentication token</pre><p>Let’s accept the default, “Login with a web browser”</p><pre>! First copy your one-time code: E2**-****<br>- Press Enter to open github.com in your browser...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*vku7U-9BNW-iJE-yN6BzTQ.png" /></figure><p>Copy the code to clipboard and hit &lt;<strong>ENTER</strong>&gt;</p><p>Your default browser will open asking you to enter the code</p><p>Paste the code and click in &lt;<strong>Continue</strong>&gt;</p><p>After it a new page asking you to Authorize GitHub CLI will appear. You can check what kind of services you will give rights to access. In this we can keep all as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dg5eLdrplNq_N3g0" /></figure><p>The following step you will need to confirm the access typing your GH account password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*RaRGkYqiZurF3llP" /></figure><p>Congratulations, your device is now recognized by GH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rVIohB8-ftVZdQ8D" /></figure><p>Check in your terminal if you received this message</p><pre>✓ Authentication complete. Press Enter to continue...</pre><pre>- gh config set -h github.com git_protocol https<br>✓ Configured git protocol<br>✓ Logged in as flaviobrito</pre><h3>Let’s Start!</h3><h3>Create a Remote Repository</h3><pre>gh repo create data_eng</pre><p>You can decide if this repository will be public, private or internal. For this article purpose I will keep it public per default.</p><pre>? Visibility  [Use arrows to move, type to filter]<br>&gt; <strong>Public</strong><br>  Private<br>  Internal</pre><p>Now GH will ask you if you want to add some files like .gitignore, license</p><p>I will keep the default (N)</p><pre>? Would you like to add a .gitignore? (y/N)</pre><pre>? Would you like to add a license? (y/N)</pre><p>Now we can add origin git remote to our local repository.</p><pre>? This will add an &quot;origin&quot; git remote to your local repository. Continue? (Y/n)</pre><p>Done!</p><pre>✓ Created repository flaviobrito/data_eng on GitHub<br>✓ Added remote &lt;https://github.com/flaviobrito/data_eng.git&gt;</pre><p>This is the starting point of all projects. A remote repository. Yes, you can control everything without creating a remote repository, but think that it is not a good practice to keep only a local copy of everything that you are doing. If you want to keep your project private and then open it to the community, it’s also possible. No matter if you want to open to keep it private, the most important is to have a remote version to guarantee that tomorrow everything will be fine.</p><h3>Check the Remote Repository</h3><p>Before start working remotely it is good to test if your machine can see the remote repository. To do it, run:</p><pre>git remote show origin</pre><p>The follow outcome will be expected:</p><pre>* remote origin<br>  Fetch URL: &lt;https://github.com/flaviobrito/data_eng.git&gt;<br>  Push  URL: &lt;https://github.com/flaviobrito/data_eng.git&gt;<br>  HEAD branch: (unknown)</pre><h3>Manage Repositories on GitHub</h3><p>GitHub will check your credentials every time you try to write remotely in the project, before starting to give git commands, you need to identify yourself in git.</p><pre>$ git config --global user.name &quot;YOUR NAME&quot;<br>$ git config --global user.email &lt;your email&gt;</pre><p>Your name need to be in double quotes (&quot;) and your email doesn’t need &lt;&gt; symbols.</p><h3>Edit Repository Config</h3><p>It’s possible to edit the repository configuration doing:</p><pre>git config -e</pre><p>A text editor like vim will be available for you, like this:</p><pre>[core]<br>        repositoryformatversion = 0<br>        filemode = true<br>        bare = false<br>        logallrefupdates = true<br>        ignorecase = true<br>        precomposeunicode = true<br>[remote &quot;origin&quot;]<br>        url = &lt;https://github.com/flaviobrito/data_eng.git&gt;<br>        fetch = +refs/heads/*:refs/remotes/origin/*<br>~<br>~<br>~</pre><p>to see more information about the repository use :</p><pre>git config -l</pre><p>to see something like this:</p><pre>core.excludesfile=~/.gitignore<br>core.legacyheaders=false<br>core.quotepath=false<br>mergetool.keepbackup=true<br>push.default=simple<br>color.ui=auto<br>color.interactive=auto<br>repack.usedeltabaseoffset=true<br>alias.s=status<br>alias.a=!git add . &amp;&amp; git status<br>alias.au=!git add -u . &amp;&amp; git status<br>alias.aa=!git add . &amp;&amp; git add -u . &amp;&amp; git status<br>alias.c=commit<br>alias.cm=commit -m<br>alias.ca=commit --amend<br>alias.ac=!git add . &amp;&amp; git commit<br>alias.acm=!git add . &amp;&amp; git commit -m<br>alias.l=log --graph --all --pretty=format:&#39;%C(yellow)%h%C(cyan)%d%Creset %s %C(white)- %an, %ar%Creset&#39;<br>alias.ll=log --stat --abbrev-commit<br>alias.lg=log --color --graph --pretty=format:&#39;%C(bold white)%h%Creset -%C(bold green)%d%Creset %s %C(bold green)(%cr)%Creset %C(bold blue)&lt;%an&gt;%Creset&#39; --abbrev-commit --date=relative<br>alias.llg=log --color --graph --pretty=format:&#39;%C(bold white)%H %d%Creset%n%s%n%+b%C(bold blue)%an &lt;%ae&gt;%Creset %C(bold green)%cr (%ci)&#39; --abbrev-commit<br>alias.d=diff</pre><p>As you can see it is possible to work with alias on git, as on the next example:</p><p>The command to check the repository status is</p><pre>git status</pre><p>or following the alias list, <strong>alias.s=status</strong></p><pre>git s</pre><p>The git will store the username and e-mail in a .gitconfig file under your home folder. To check it, you can open the file using vi or another text editor.</p><pre>vi ~/.gitconfig</pre><h3>Ignoring Unwanted Files Globally</h3><p>Git check inside of .gitignore file inside the repository if you want top ignore a specify directory or some files. But you can do it globally, to do it, you need to create a file under your home directory named .gitignore_global</p><pre>vi ~/.gitignore_global</pre><p>with the contents:</p><pre>*~<br>.*.swp<br>.DS_Store</pre><p>To apply this new setting, run</p><pre>git config --global core.excludesfile ~/.gitignore_global</pre><h3>Validate Important Commands Rights</h3><p>Create a very simple file named <a href="http://readme.md/">README.md</a> with a simple markdown line like:</p><pre>echo &quot;# data_eng&quot; &gt;&gt; README.md</pre><h3>Initialize Git Repository Locally</h3><p>initialize your repository if you&#39;re not already done. Doing this git will start keep the changes locally.</p><pre>git init</pre><h3>Add a File to be Versionable.</h3><p>Doing this you guarantee that git will log all the changes in this file when you commit.</p><pre>git add README.md</pre><h3>Branches</h3><p>Nice to start with the right foot on Git. A git branch brings the idea of a tree, where you can derivate many branches as you always need pointing to a snapshot of your changes.</p><p>With branches you can work in your changes without needing to wait for another developer. Others features like releases can be also used to expand the use of it.</p><p>The list of branches can be seen using:</p><pre>git branch</pre><pre>flaviobrito@brito data_eng % git branch<br>* master<br>flaviobrito@brito data_eng %</pre><p>that is the same of git branch — list.</p><p>the outcome in this case is:</p><pre>* master</pre><h3>Rename a Branch</h3><p>It’s important to know how to rename a branch. Sometimes we need to change the name because of a typo for example. Let’s do it, changing the current branch (master) to main using -M option that it’s equal to — — move — force. Following the git documentation this is a Move/rename a branch and the corresponding reference log.</p><pre>git branch -M main</pre><pre>git branch</pre><p>the outcome will be:</p><pre>* main</pre><p>What happened, the master branch name was changed to main.</p><h3>The Repo Structure and Files</h3><p>A list of all directories and files inside of each one is a good idea to follow a complex project and document it outside of git. Using ls-tree command and following the branch name, in this case main, will be printed a tree with only the names.</p><pre>git ls-tree -r main --name-only README.md</pre><p>In our case, there is only one file, a more complex structure will be created to demonstrate the tree.</p><pre>git ls-tree -r BI-2316-Bigquery_Uploader --name-only</pre><pre>Makefile<br>README.md<br>common/__init__.py<br>config/__init__.py<br>db/__init__.py<br>module/__init__.py<br>tests/__init__.py</pre><h3>Create a Branch</h3><p>A best practices is to commit codes in the main (master) branch that are already tested and approved for production, until it is good to work in another branch to avoid introduce not approved / tested features or a bug.</p><p>Before creating a new branch, let’s talk about how it can be named. Avoid creating a branch name using a mnemonic, code or numbers. I recommend you follow this syntax:</p><p>&lt;JIRA TICKET NUMBER&gt;-&lt;TITLE&gt;</p><pre>BI-2316-Bigquery Uploader</pre><p>where BI-2316 is the ticket number on Jira where you can easily find more information about the features or issues related with this branch. A better practice is to give a small title. Important to known that it cannot have space between words.</p><p>Avoid titles like these:</p><pre>new-pre-merge<br>master-new-last<br>BI-1371</pre><p>This probably brings a lot of confusion and brings the need to search for more information to clarify what does it mean.</p><pre>git checkout -b BI-2316-Bigquery_Uploader</pre><p>In this case, git will create a new branch pointing the current branch to the checkout branch name.</p><p>Listing the branches</p><pre>* BI-2316-Bigquery_Uploader<br>  main</pre><p>The current branch now is marked with a start.</p><p>To see local and remote branches you need — — all option:</p><pre>git branch --all<br>* BI-2316-Bigquery_Uploader<br>  main<br>  remotes/origin/BI-2316-Bigquery_Uploader<br>  remotes/origin/main</pre><h3>Create a Branch From a Another Branch</h3><p>Creating a new branch from another has special cases, like test merge for example. To do it, run:</p><p>Syntax: git branch new old</p><pre>git branch BI-2316-Bigquery_Uploader_GCS BI-2316-Bigquery_Uploader</pre><h3>Change to another branch</h3><p>To move to another branch, type the name of the target branch, like:</p><pre>git checkout main</pre><p>In this case the current branch will be the branch: main</p><h3>How Do I Clean Outdated Branches?</h3><p>In a corporate environment it is a good practice that after merged successfully a branch is removed. The <em>fetch</em> command is to fetch all remote branches and remove references that are no longer in use, keeping only local references. This safely leaves local work in local/origin.</p><pre>git fetch --all --prune</pre><h3>Delete a Branch</h3><p>It is possible to delete a branch, typing <em>git branch</em> command with -D and the branch name. You cannot delete a branch that you are inside.</p><pre>git branch -D branch_name</pre><p>To delete a branch BI-2316-Bigquery_Uploader is necessary to jump to another branch. In this case main, and only after it will be possible to delete a BI-2316-Bigquery_Uploader.</p><pre>git checkout main<br>Switched to branch &#39;main&#39;<br>Your branch is up to date with &#39;origin/main&#39;.</pre><pre>git branch -D BI-2316-Bigquery_Uploader<br>Deleted branch BI-2316-Bigquery_Uploader (was e9cf5ec).</pre><h3>Push the Changes</h3><p>We already added a file and did a commit, but in this case all changes are still local. To push all of them into the remote branch:</p><p>Syntaxe:</p><p>git push &lt;remote&gt; &lt;branch&gt;</p><pre>git push -u origin main</pre><p>where <em>-u push</em> local content to remote (GitHub).</p><h3>Always check the Status</h3><p>Before start working in a branch it is good to check the status doing this:</p><pre>git status</pre><p>the outcome is</p><pre>On branch main<br>Your branch is up to date with &#39;origin/main&#39;.</pre><h3>Pull</h3><p>To bring the changes from remote repository to your local repository you need to use git push command.</p><p>Syntax: git pull remote_name branch_name</p><pre>git push origin main</pre><h3>Merge</h3><p>Working into a branch and after test all, it’s time to merge the new features from master into the branch that you are working on.</p><h3>Merge a Master/Main to a Branch</h3><p>You can do:</p><pre>git checkout BI-2316-Bigquery_Uploader<br>git pull<br>git merge main</pre><p>or</p><pre>git merge origin/BI-2316-Bigquery_Uploader main</pre><p>In this case all changes in main will be merged into BI-2316-Bigquery_Uploader. This will create a “merge commit”. Merging is nice because it’s a non-destructive operation. You can abort it. Check the topic below.</p><h3>Merge a Branch to Master/Main</h3><pre>git checkout main<br>git pull<br>git merge origin/BI-2316-Bigquery_Uploader<br>git push -u origin main</pre><pre>git merge --no-ff --no-commit BI-2316-Bigquery_Uploader</pre><p>Test merge before commit, avoid a fast-forward commit by --no-ff<em>,</em></p><h3>What Changed?</h3><p>Alway check log. To verify the history of all changes run:</p><pre>git log</pre><p>the outcome is</p><pre>commit e8b2e09e09486e56bd25d1486cd487ca02637bd7 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 16:44:19 2021 +0200</pre><pre>    structure</pre><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><p>Relax!!, the e9cf5ec40c683fd38316ca589ee4c46088ea743a will be different in your case.</p><p>Do you want more details? Try add --stat</p><pre>git log --stat<br>commit e8b2e09e09486e56bd25d1486cd487ca02637bd7 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Thu Sun 1 16:44:19 2021 +0200</pre><pre>    structure</pre><pre> Makefile           | 27 +++++++++++++++++++++++++++<br> common/__init__.py |  0<br> config/__init__.py |  0<br> db/__init__.py     |  0<br> module/__init__.py |  0<br> tests/__init__.py  |  0<br> 6 files changed, 27 insertions(+)</pre><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><pre> README.md | 1 +<br> 1 file changed, 1 insertion(+)</pre><p>A short log version</p><pre>git shortlog<br>flaviobrito (2):<br>      first commit<br>      structure</pre><p>Or a graph version</p><pre>git log --graph --oneline --decorate<br>* e8b2e09 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader) structure<br>* e9cf5ec (origin/main) first commit</pre><h3>Filter Log</h3><p>In a long project a simple log check can have a huge output.</p><p>Last <em>3</em> commits. In our case, it will be the same outcome.</p><pre>commit e8b2e09e09486e56bd25d1486cd487ca02637bd7 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 16:44:19 2021 +0200</pre><pre>    structure</pre><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><h3>Filter by Date</h3><pre>git log --after=&quot;2021-7-1&quot;</pre><p>the outcome is</p><pre>commit e8b2e09e09486e56bd25d1486cd487ca02637bd7 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 16:44:19 2021 +0200</pre><pre>    structure</pre><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><h3>Filter by Author</h3><pre>git log --author=&quot;flaviobrito&quot;</pre><p>the outcome is</p><pre>commit e8b2e09e09486e56bd25d1486cd487ca02637bd7 (HEAD -&gt; main, origin/BI-2316-Bigquery_Uploader, BI-2316-Bigquery_Uploader)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 16:44:19 2021 +0200</pre><pre>    structure</pre><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><h3>Filter by File</h3><p>It’s important to check what happened to a particular file or a list of files. To do it you can add -- and a list of files.</p><pre>git log -- README.md</pre><p>the outcome is</p><pre>commit e9cf5ec40c683fd38316ca589ee4c46088ea743a (origin/main)<br>Author: flaviobrito &lt;EMAIL&gt;<br>Date:   Sun Aug 1 15:11:56 2021 +0200</pre><pre>    first commit</pre><p>or</p><pre>git log --follow --all -p .</pre><p>where the . is current directory.</p><h3>Log what were Merged or Not</h3><p>There are 2 options to verify what was merged or no-merged.</p><pre>git log --no-merges</pre><p>and what were the merged files</p><pre>git log --merges</pre><h3>Troubleshooting</h3><h3>Can’t push to GitHub because of large file which I already deleted</h3><p>This occurred to me when a large file was generated without me realizing it. After trying to do another push I received a message telling me that every push was blocked. No fix if you only remove the file after trying to push it, git has a great memory, in that case I also removed it from git history.</p><p>This case can be used to avoid keeping a huge list of unwanted files into git repository.</p><p>Supposed that you are reading 200MB of JSON files and don’t want git to track them and you didn’t put the data/request folder into the .gitignore. Bam! Git tracks them. Now how we can remove from git cache:</p><pre>git rm --cached data/requests/2015/* -r</pre><p>the option -ris recursive. All subdirectories will be removed from cache. This is not a physical remove, only from git context.</p><h3>Undo a Merge</h3><p>A wrong merge can bring a lot of work if we didn’t check previously if there are conflicts after it. In case of a big merge, an advice to keep things simple, don’t wait so long to do a merge into the <em>master</em>. But in the case that you do, a best practice is to create a new branch to be merged with the target branch and then if it’s is clear do it in <em>master</em>. In case of many conflicts you can UNDO it by doing:</p><pre>git merge --abort</pre><h3>Summary</h3><p>In this article, we showed a focused analysis on git and GitHub daily use and how to improve your productivity.</p><p>You can check the author’s <strong>GitHub repositories </strong>for code, ideas, and resources in data science and data engineering. Please feel free to add me on <a href="https://www.linkedin.com/in/flaviobrito/">LinkedIn</a> or follow me on <a href="https://twitter.com/flaviobritodata/">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e1b737c9d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>