<?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 Srivarshagowthu on Medium]]></title>
        <description><![CDATA[Stories by Srivarshagowthu on Medium]]></description>
        <link>https://medium.com/@srivarshagowthu?source=rss-389b3a849836------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1p53Qxk59GpNSEHE</url>
            <title>Stories by Srivarshagowthu on Medium</title>
            <link>https://medium.com/@srivarshagowthu?source=rss-389b3a849836------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:22:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srivarshagowthu/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[Google OR-Tools: The Complete Guide (Beginner to Advanced) — With Real world examples]]></title>
            <link>https://medium.com/@srivarshagowthu/google-or-tools-the-complete-guide-beginner-to-advanced-with-real-world-examples-a1e0d0ec8dc1?source=rss-389b3a849836------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e0d0ec8dc1</guid>
            <category><![CDATA[constraint-programming]]></category>
            <category><![CDATA[cp-sat]]></category>
            <category><![CDATA[engine-optimization]]></category>
            <category><![CDATA[optimizational-tools]]></category>
            <category><![CDATA[google-or-tools]]></category>
            <dc:creator><![CDATA[Srivarshagowthu]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 12:53:38 GMT</pubDate>
            <atom:updated>2026-07-03T12:53:38.992Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Everything you need to understand, use, and build with Google’s optimization engine.</em></p><h3>Introduction: Why This Guide Exists</h3><p>If you’ve ever tried to figure out the cheapest way to deliver 200 packages with 12 trucks, the fairest way to build an <strong>employee shift schedule</strong>, or the most efficient way to pack boxes into a container — you’ve run into a class of problems called <strong>combinatorial optimization problems</strong>. These problems look simple on the surface but explode in complexity as the input grows, because the number of possible solutions grows exponentially.</p><p>Recently, I spent a lot of time trying to solve an employee roster automation problem using a naive approach. Despite investing significant effort, the solution eventually failed due to its complexity and inefficiency. While searching for a more optimized and scalable approach, I discovered my rescue — Google OR-Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*2d2PugJZBGLwV9DibX7COA.png" /></figure><p>That’s when I realized that some problems are not meant to be solved with brute force or traditional logic alone. They require optimization, constraints, and intelligent decision-making — exactly where Google OR-Tools shines.</p><p><strong>Google OR-Tools</strong> is a free, open-source software suite built specifically to solve these problems fast. It’s used inside Google itself for large-scale logistics and scheduling, and it’s used by thousands of companies and students worldwide for everything from delivery routing to exam timetabling.</p><p>This guide takes you from “what even is OR-Tools” all the way to building a working, portfolio-ready project. By the end, you’ll be able to write your own Medium post <em>and</em> ship a project that actually solves something real. <br>“dont miss part 5!!”</p><h3>Part 1: The Fundamentals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*6DjJYlJrMCaer0CE" /></figure><h3>1.1 What Is OR-Tools, Exactly?</h3><p>OR-Tools (short for <strong>Operations Research Tools</strong>) is an open-source suite created by Google for solving combinatorial optimization problems — problems where you’re searching for the best solution out of a huge (often astronomically huge) number of possibilities, subject to constraints.</p><p>A few key facts worth knowing:</p><ul><li>It’s written in <strong>C++</strong> at its core, with official wrappers for <strong>Python, Java, and .NET (C#)</strong>.</li><li>It’s distributed under the <strong>Apache License 2.0</strong>, so it’s free to use commercially.</li><li>It was created by Laurent Perron and first released publicly in 2010, and has grown into a massive codebase used internally at Google for real production systems.</li><li>It bundles <strong>multiple solvers</strong> under one roof instead of forcing you to pick a single algorithm — this is one of its biggest strengths.</li></ul><h3>1.2 What Problems Does It Actually Solve?</h3><p>OR-Tools isn’t one algorithm — it’s a toolbox of specialized solvers, each suited to a different problem <em>shape</em>:</p><p>Problem Type What It’s For OR-Tools Module <strong>Linear &amp; Mixed-Integer Programming (LP/MIP)</strong> Maximize/minimize a linear objective under linear constraints linear_solver <strong>Constraint Programming (CP)</strong> Find feasible/optimal solutions where logic and feasibility matter more than a formula sat (CP-SAT) <strong>Vehicle Routing (VRP)</strong> Plan optimal routes for fleets of vehicles constraint_solver (routing library) <strong>Bin Packing / Knapsack</strong> Pack items into containers efficiently algorithms <strong>Network Flow / Graph Algorithms</strong> Shortest paths, min-cost flow, max flow, assignment graph <strong>Scheduling</strong> Job-shop scheduling, employee rostering, resource allocation CP-SAT (intervals, no-overlap)</p><p>If you only remember one thing from this section: <strong>OR-Tools gives you the right hammer for several different nails, all in one package.</strong></p><p>OKAY!! now what solvers we should use at what use case?? <br>pls refer to part 7.. their i’ve mentioned <strong>thumb rule for selecting solver</strong></p><h3>1.3 Real-World Use Cases</h3><p>To ground this in reality, here’s where these techniques show up:</p><ul><li><strong>Logistics</strong>: Delivery route optimization for courier and food-delivery companies</li><li><strong>Manufacturing</strong>: Job-shop scheduling on factory floors, minimizing makespan</li><li><strong>Workforce management</strong>: Building shift schedules that respect labor laws, availability, and fairness</li><li><strong>Supply chain</strong>: Bin packing for container/truck loading, warehouse slotting</li><li><strong>Telecom &amp; networking</strong>: Shortest-path and flow problems on networks</li><li><strong>Finance</strong>: Portfolio and resource-allocation problems modeled as MIP</li></ul><h3>Part 1.5: A Quick Tour of the Classic Problems (before we go deep)</h3><p>Before diving into code, it helps to meet the “famous” problems that OR-Tools is known for solving. Think of this as a movie trailer — just enough to recognize each one later when we build it for real.</p><h3>🎒 Knapsack Problem</h3><p>You have a backpack with limited space, and a pile of items each with a weight and a value. You want the combination of items that gives you the <em>most value</em> without going over the weight limit. <strong>How OR-Tools helps:</strong> instead of you checking every possible combination by hand (which explodes fast), OR-Tools’ solvers (via CP-SAT or the algorithms module) search smartly and hand you the best combination in seconds.</p><h3>🗺️ Maps / Shortest-Path Problems</h3><p>You have a network of locations connected by roads, each with a distance or travel time. You want the cheapest way to get from A to B, or to move something through the network. <strong>How OR-Tools helps:</strong> its graph module has ready-made shortest-path and flow algorithms — you just feed it the network, and it tells you the cheapest route through it.</p><h3>📦 Bin Packing</h3><p>You have boxes of different sizes and containers of a fixed size. You want to use the <em>fewest</em> containers possible. <strong>How OR-Tools helps:</strong> it searches for packing arrangements that minimize wasted space and the number of bins used, instead of you guessing arrangements by trial and error.</p><h3>🚚 Vehicle Routing Problem (VRP)</h3><p>You have a fleet of delivery vehicles and a list of customers to visit. You want the routes that get everyone served with the least total driving. <strong>How OR-Tools helps:</strong> it has a dedicated routing engine built exactly for this — it can juggle multiple vehicles, capacity limits, and delivery time windows all at once.</p><h3>♛ N-Queens</h3><p>Classic puzzle: place N chess queens on an N×N board so that no two queens attack each other (same row, column, or diagonal). <strong>How OR-Tools helps:</strong> this is a pure logic/constraint puzzle — a perfect job for CP-SAT, which just needs the “no two queens can attack each other” rule and finds valid placements almost instantly.</p><h3>🔢 Sudoku Solver</h3><p>Classic puzzle: fill a 9×9 grid so every row, column, and 3×3 box contains the digits 1–9 exactly once. <strong>How OR-Tools helps:</strong> again, this is a constraint-satisfaction problem — CP-SAT takes the grid rules as constraints and fills in the missing numbers for you, guaranteed correct.</p><p>We’ll come back to a couple of these in more depth later. For now, just notice the <em>pattern</em>: every one of these problems is really just “variables + rules + (sometimes) a goal,” which is exactly the three-step skeleton from Part 2. Let’s go deep.</p><h3>Part 2: Installing and Getting Started</h3><h3>2.1 Installation</h3><p>For Python (the most common entry point and the recommended starting language):</p><pre>pip install ortools</pre><p>That’s it — no separate solver licenses, no compiling from source, no API keys. This is one of the reasons OR-Tools is such a popular starting point compared to commercial solvers like Gurobi or CPLEX.</p><p>Verify it works:</p><pre>from ortools.sat.python import cp_model<br>print(&quot;OR-Tools is ready&quot;)</pre><h3>2.2 The Mental Model You Need Before Writing Code</h3><p>Every OR-Tools model — no matter which solver you use — follows the same three-step skeleton (if u exceled in this thats it u can play with OR solvers):</p><ol><li><strong>Declare variables</strong> — the unknowns you’re trying to find values for.</li><li><strong>Add constraints</strong> — the rules those variables must obey.</li><li><strong>Define an objective (optional) and solve</strong> — tell the solver what “best” means, then let it search.</li></ol><p>Keep this pattern in your head. Every example below is a variation of it.</p><h3>Part 3: Linear &amp; Mixed-Integer Programming (the linear_solver)</h3><p>This is the most classical form of optimization: you have variables, a linear objective function, and linear constraints.</p><h3>3.1 A Simple Example</h3><p>Imagine a small furniture workshop that makes chairs and tables from a limited supply of wood, and wants to maximize revenue.</p><pre>from ortools.linear_solver import pywraplp</pre><pre>solver = pywraplp.Solver.CreateSolver(&quot;GLOP&quot;)  # GLOP = Google&#39;s LP solver</pre><pre># Variables: number of chairs and tables to produce<br>chairs = solver.NumVar(0, solver.infinity(), &quot;chairs&quot;)<br>tables = solver.NumVar(0, solver.infinity(), &quot;tables&quot;)</pre><pre># Constraint: total wood used cannot exceed 21 sq. meters<br>solver.Add(6 * chairs + 7 * tables &lt;= 21)</pre><pre># Objective: maximize revenue ($12 per chair, $13 per table)<br>solver.Maximize(12 * chairs + 13 * tables)</pre><pre>status = solver.Solve()</pre><pre>if status == pywraplp.Solver.OPTIMAL:<br>    print(f&quot;Chairs: {chairs.solution_value()}&quot;)<br>    print(f&quot;Tables: {tables.solution_value()}&quot;)<br>    print(f&quot;Max revenue: {solver.Objective().Value()}&quot;)</pre><h3>3.2 LP vs. MIP</h3><ul><li><strong>LP (Linear Programming)</strong>: variables can take any real value (like 2.5 chairs). Solved with <strong>GLOP</strong>, Google’s linear solver.</li><li><strong>MIP (Mixed-Integer Programming)</strong>: some or all variables must be whole numbers (you can’t build half a chair). Solved with solvers like <strong>SCIP</strong> or <strong>CBC</strong>, which OR-Tools wraps.</li></ul><p>Switching solvers is often a one-line change:</p><pre>solver = pywraplp.Solver.CreateSolver(&quot;SCIP&quot;)  # for MIP problems</pre><h3>3.3 When to Reach for linear_solver</h3><p>Use it when your problem can genuinely be expressed as: <em>maximize/minimize a linear formula, subject to linear inequalities/equalities.</em> Classic examples: production planning, diet/nutrition optimization (the famous “Stigler diet” problem), blending problems, resource allocation.</p><h3>Part 4: Constraint Programming with CP-SAT (the star of the show)</h3><p>If you learn only one solver deeply, make it <strong>CP-SAT</strong>. It’s the primary constraint programming solver in OR-Tools and, according to the community and Google’s own documentation, it’s generally faster and more beginner-friendly than the older MIP-based workflow for a huge range of problems — especially ones with lots of logical (if/then, all-different, no-overlap) constraints rather than purely arithmetic ones.</p><h3>4.1 What Makes CP-SAT Different</h3><ul><li>CP-SAT combines classic <strong>Constraint Programming</strong> with modern <strong>SAT (Boolean satisfiability)</strong> solving techniques.</li><li>Constraint Programming cares about <strong>feasibility</strong> first — “does a valid solution even exist?” — and optimization second. This is different from LP/MIP, which is fundamentally built around an objective function.</li><li><strong>Everything must be an integer.</strong> If your problem has decimals, you scale them up (e.g., multiply money values by 100 to work in cents) before modeling.</li></ul><h3>4.2 Your First CP-SAT Model</h3><p>Here’s the “hello world” of CP-SAT — three variables, one constraint, find any valid solution:</p><pre>from ortools.sat.python import cp_model</pre><pre>model = cp_model.CpModel()</pre><pre># Three variables, each can be 0, 1, or 2<br>x = model.new_int_var(0, 2, &quot;x&quot;)<br>y = model.new_int_var(0, 2, &quot;y&quot;)<br>z = model.new_int_var(0, 2, &quot;z&quot;)</pre><pre># Constraint<br>model.add(x != y)</pre><pre>solver = cp_model.CpSolver()<br>status = solver.solve(model)</pre><pre>if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:<br>    print(f&quot;x={solver.value(x)}, y={solver.value(y)}, z={solver.value(z)}&quot;)</pre><h3>4.3 Adding an Objective</h3><p>To turn this from “find <em>a</em> solution” into “find the <em>best</em> solution,” add maximize/minimize:</p><pre>model.add(2 * x + 7 * y + 3 * z &lt;= 50)<br>model.add(3 * x - 5 * y + 7 * z &lt;= 45)<br>model.add(5 * x + 2 * y - 6 * z &lt;= 37)<br>model.maximize(2 * x + 2 * y + 3 * z)</pre><pre>solver = cp_model.CpSolver()<br>status = solver.solve(model)</pre><pre>if status == cp_model.OPTIMAL:<br>    print(f&quot;Best value: {solver.objective_value}&quot;)</pre><h3>4.4 Finding ALL Solutions (not just one)</h3><p>Sometimes you don’t want the best solution — you want to enumerate every valid one. This is common for puzzles (N-Queens, Sudoku, cryptarithmetic).</p><pre>class SolutionPrinter(cp_model.CpSolverSolutionCallback):<br>    def __init__(self, variables):<br>        cp_model.CpSolverSolutionCallback.__init__(self)<br>        self.variables = variables<br>        self.count = 0</pre><pre>def on_solution_callback(self):<br>        self.count += 1<br>        print([self.value(v) for v in self.variables])</pre><pre>solver = cp_model.CpSolver()<br>solver.parameters.enumerate_all_solutions = True<br>printer = SolutionPrinter([x, y, z])<br>solver.solve(model, printer)</pre><h3>4.5 The Key CP-SAT Building Blocks You’ll Actually Use</h3><p>Concept What it’s for new_int_var(lb, ub, name) Declare an integer variable within a range new_bool_var(name) Declare a true/false decision variable add(expr) Generic linear constraint add_all_different([...]) All variables must take distinct values new_interval_var(...) Represents a task with a start, duration, end (crucial for scheduling) add_no_overlap([...]) Tasks/intervals can&#39;t run at the same time on the same resource maximize(expr) / minimize(expr) Define the objective solver.parameters.max_time_in_seconds Cap solve time for large problems</p><h3>4.6 Where CP-SAT Shines</h3><p><strong>Scheduling and rostering problems</strong> are its bread and butter — job-shop scheduling (multiple machines, multiple jobs, minimize total completion time), employee shift rostering with coverage and labor-rule constraints, and classic constraint puzzles like N-Queens or cryptarithmetic.</p><p>A production-grade rostering system, for instance, models each employee-shift-day combination as a boolean decision variable, then layers on coverage constraints (enough people per shift), availability constraints, and workload limits — all things CP-SAT is built to express cleanly.</p><h3>4.7 Two Classic Puzzles, Solved with CP-SAT</h3><p><strong>N-Queens</strong> — place N queens on an N×N board so none attack each other. The trick: represent each queen’s column position as one variable per row, then add “all different” rules for columns and both diagonal directions.</p><pre>from ortools.sat.python import cp_model</pre><pre>n = 8<br>model = cp_model.CpModel()</pre><pre># queens[i] = column position of the queen in row i<br>queens = [model.new_int_var(0, n - 1, f&quot;q{i}&quot;) for i in range(n)]</pre><pre>model.add_all_different(queens)                                  <br># no shared column<br>model.add_all_different([queens[i] + i for i in range(n)])       <br># no shared &quot;/&quot; diagonal<br>model.add_all_different([queens[i] - i for i in range(n)])       <br># no shared &quot;\&quot; diagonal</pre><pre>solver = cp_model.CpSolver()<br>status = solver.solve(model)<br>if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:<br>    print([solver.value(q) for q in queens])</pre><p>Notice there’s no maximize/minimize here at all — this is CP in its purest form: just find <em>any</em> arrangement that satisfies every rule.</p><p><strong>Sudoku Solver</strong> — same idea, scaled up: one variable per cell (1–9), then “all different” across every row, column, and 3×3 box.</p><pre>model = cp_model.CpModel()<br>cells = [[model.new_int_var(1, 9, f&quot;c{r}{c}&quot;) for c in range(9)] for r in range(9)]</pre><pre>for row in cells:<br>    model.add_all_different(row)<br>for col in zip(*cells):<br>    model.add_all_different(col)<br>for box_row in range(3):<br>    for box_col in range(3):<br>        box = [cells[r][c]<br>               for r in range(box_row * 3, box_row * 3 + 3)<br>               for c in range(box_col * 3, box_col * 3 + 3)]<br>        model.add_all_different(box)</pre><pre># Then add model.add(cells[r][c] == given_value) for every pre-filled clue</pre><p>The same “all different” building block from N-Queens does almost all the work here too — that’s the beauty of constraint programming: a handful of reusable rule-types cover a surprising number of real puzzles.</p><h3>Part 5: Vehicle Routing — Explained in the Easy Way</h3><h3>5.1 The Idea</h3><p>Imagine you run a small pizza delivery shop.</p><ul><li>You have <strong>1 shop (depot)</strong> — where all drivers start and end.</li><li>You have <strong>a few delivery addresses</strong> for tonight.</li><li>You have <strong>2 or 3 delivery drivers (vehicles)</strong>.</li></ul><p>The question is simple: <strong>“Who should deliver to which houses, and in what order, so that total driving is as short as possible?”</strong></p><p>That’s it. That’s the whole Vehicle Routing Problem (VRP). Everything else is just “extra rules” layered on top, like:</p><ul><li>Each driver’s bike basket can only hold 10 pizzas → <strong>capacity limit</strong></li><li>A customer wants their pizza between 7–8 PM → <strong>time window</strong></li></ul><h3>5.2 Why Is This Hard?</h3><p>With 1 driver and a few stops, you could just guess the best order. But with many stops and many drivers, the number of possible combinations becomes <em>huge</em> — too many for a human (or even brute-force computer) to check one by one. That’s why we need a smart solver like OR-Tools to search through possibilities intelligently instead of trying everything.</p><h3>5.3 VRP (vehicle Routing Problem) Is Just TSP With More Trucks</h3><p>The <strong>Traveling Salesman Problem (TSP)</strong> asks: with one vehicle, what’s the shortest route that visits every city once and returns home? VRP generalizes this to <strong>multiple vehicles</strong>, then adds real-world constraints on top: capacity limits, time windows, multiple depots, or pickup-and-delivery pairs for more advanced variants.</p><h3>5.4 Walking Through the Code</h3><p>Think of the code as answering four questions in order.</p><p><strong>1️⃣ “What are the distances between places?”</strong></p><pre>data[&quot;distance_matrix&quot;] = [<br>    [0, 9, 6, 4],<br>    [9, 0, 5, 3],<br>    [6, 5, 0, 7],<br>    [4, 3, 7, 0],<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qF6Ux81WrpCbxOIbK4CRNw.png" /></figure><p>This is just a <strong>table of distances</strong> between every pair of locations (like a mileage chart on an old road map). Location 0 is the depot (the shop). Row 0, column 1 says “distance from shop to stop 1 = 9.” <br>pls refer to the image</p><p><strong>2️⃣ “How many drivers do we have, and where do they start?”</strong></p><pre>data[&quot;num_vehicles&quot;] = 2<br>data[&quot;depot&quot;] = 0</pre><p>Simple — 2 drivers, everyone starts/ends at location 0 (the shop).</p><p><strong>3️⃣ “Set up the problem for OR-Tools to understand”</strong></p><pre>manager = pywrapcp.RoutingIndexManager(<br>    len(data[&quot;distance_matrix&quot;]), data[&quot;num_vehicles&quot;], data[&quot;depot&quot;]<br>)<br>routing = pywrapcp.RoutingModel(manager)</pre><p>Don’t overthink these two lines — they’re just <strong>boilerplate setup</strong>. Think of manager as a translator between &quot;real location numbers&quot; and &quot;the solver&#39;s internal numbering,&quot; and routing as the actual problem OR-Tools will solve. You&#39;ll write these two lines almost the same way in every VRP project.</p><p><strong>4️⃣ “Tell OR-Tools how to calculate cost between any two points”</strong></p><pre>def distance_callback(from_index, to_index):<br>    from_node = manager.IndexToNode(from_index)<br>    to_node = manager.IndexToNode(to_index)<br>    return data[&quot;distance_matrix&quot;][from_node][to_node]</pre><pre>transit_callback_index = routing.RegisterTransitCallback(distance_callback)<br>routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)</pre><p>This is a little helper function that says: <em>“if you want to know the cost of going from point A to point B, look it up in the distance table.”</em> OR-Tools calls this function internally, over and over, while it searches for good routes.</p><p><strong>5️⃣ “Solve it, then read the answer”</strong></p><pre>search_parameters = pywrapcp.DefaultRoutingSearchParameters()<br>search_parameters.first_solution_strategy = (<br>    routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC<br>)<br>solution = routing.SolveWithParameters(search_parameters)</pre><p>SolveWithParameters is the magic button — OR-Tools searches for the best set of routes.</p><pre>if solution:<br>    for vehicle_id in range(data[&quot;num_vehicles&quot;]):<br>        index = routing.Start(vehicle_id)<br>        route = []<br>        while not routing.IsEnd(index):<br>            route.append(manager.IndexToNode(index))<br>            index = solution.Value(routing.NextVar(index))<br>        route.append(manager.IndexToNode(index))<br>        print(f&quot;Vehicle {vehicle_id} route: {route}&quot;)</pre><p>This part just <strong>walks through each driver’s route and prints it</strong>. Think of it like: <em>“Start at the depot. Ask ‘where does this driver go next?’ Keep asking until they’re back home. Write down every stop along the way.”</em></p><h3>5.5 The Two “Extra Rules” You’ll Add Most Often</h3><p><strong>Capacity (turns VRP into CVRP — Capacitated VRP):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-N83ANel63c4rUEUjHxR6w.png" /></figure><pre>def demand_callback(from_index):<br>    from_node = manager.IndexToNode(from_index)<br>    return data[&quot;demands&quot;][from_node]</pre><pre>demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)<br>routing.AddDimensionWithVehicleCapacity(<br>    demand_callback_index,<br>    0,                          # no slack<br>    data[&quot;vehicle_capacities&quot;], # max capacity per vehicle<br>    True,                       # start cumulative count at zero<br>    &quot;Capacity&quot;,<br>)</pre><p>In plain English: <em>“add up the demand at every stop the driver visits so far, and don’t let it go over the vehicle’s max capacity.”</em></p><p><strong>Time windows (turns it into VRPTW — VRP with Time Windows):</strong></p><pre>routing.AddDimension(<br>    transit_callback_index,<br>    30,     # allow waiting time<br>    30,     # max time per vehicle<br>    False,  # don&#39;t force cumulative start at zero<br>    &quot;Time&quot;,<br>)<br>time_dimension = routing.GetDimensionOrDie(&quot;Time&quot;)<br>for location_idx, time_window in enumerate(data[&quot;time_windows&quot;]):<br>    index = manager.NodeToIndex(location_idx)<br>    time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])</pre><p>In plain English: <em>“each stop has an allowed time range — don’t schedule a visit outside that range.”</em></p><p>You don’t need to memorize the exact syntax right now — just understand: <strong>these are add-on constraints stacked on top of the same basic route-finding skeleton</strong> from 5.4.</p><h3>5.6 One Practical Reality Check</h3><p>For real deployments, you generally want <strong>actual road distances/times</strong>, not straight-line distance — usually sourced from a mapping/routing API (like the Google Distance Matrix API) or an open-source alternative like OpenStreetMap-based tools. OR-Tools solves the <em>assignment and sequencing</em> problem — it doesn’t compute geographic distances for you. That’s a separate step.</p><h3>Part 6: Bin Packing, Knapsack, and Graph Algorithms — Explained the Easy Way</h3><p>These are three more “problem shapes” OR-Tools can solve. You don’t need to master them right now — just know they exist and roughly what each one is for.</p><h3>📦 Bin Packing</h3><p><strong>Easy version:</strong> You have a bunch of boxes of different sizes, and containers (bins) of a fixed size. How do you pack the boxes using the <em>fewest</em> containers possible?</p><p>Think: a shipping company trying to fit all today’s packages into the fewest number of delivery trucks, or a cloud company trying to fit customer workloads onto the fewest number of servers. That’s bin packing.</p><h3>🎒 Knapsack Problem</h3><p><strong>Easy version:</strong> You’re going on a hike with a backpack that can only hold, say, 10kg. You have a list of items, each with a weight and a “value” to you. Which items do you take to get the <em>most value</em> without going over 10kg?</p><p>This is the classic “knapsack problem.” In business terms: which projects/features should we invest in given a limited budget, to get the most value? Same shape of problem, different words.</p><pre># Rough idea, not full code:<br># items have (weight, value)<br># constraint: total weight &lt;= capacity<br># objective: maximize total value</pre><h3>🕸️ Graph Algorithms</h3><p><strong>Easy version:</strong> Imagine a map made of dots (locations) connected by lines (roads/connections), each line having a “cost” (distance, time, etc). OR-Tools can answer questions like:</p><ul><li>What’s the <em>shortest path</em> from A to B?</li><li>What’s the cheapest way to move the <em>maximum amount of stuff</em> through a network of pipes/roads? (max flow / min cost flow)</li><li>Who should be matched with whom, at lowest total cost? (assignment problem — e.g., matching workers to tasks)</li></ul><p><strong>Why this section matters for you:</strong> if your project ever turns into “match X to Y at lowest cost” or “find shortest path through a network,” you now know OR-Tools already has a tool for that — you don’t need to build it from scratch.</p><h3>Part 7: Choosing the Right Solver — Explained the Easy Way</h3><p>This is basically a <strong>decision tree</strong> — a flowchart in your head for “which OR-Tools tool do I even use?”</p><p>Think of it like a doctor doing a quick diagnosis:</p><ol><li><strong>“Is my problem just a formula I’m maximizing/minimizing, with simple math rules (add, multiply by constants, compare)?”</strong> → Yes → Use linear_solver (Part 3). <em>Example: &quot;maximize profit given limited raw materials.&quot;</em></li><li><strong>“Is my problem more about logic and rules — scheduling, ‘these two things can’t happen at the same time,’ ‘all these must be different values’?”</strong> → Yes → Use <strong>CP-SAT</strong> (Part 4). <em>Example: “assign shifts so no one works two shifts at once.”</em></li><li><strong>“Am I sending vehicles to visit multiple locations?”</strong> → Yes → Use the <strong>routing library / VRP</strong> (Part 5). <em>Example: “plan delivery routes for 3 trucks.”</em></li><li><strong>“Am I packing items into containers, or finding paths/flows through a network?”</strong> → Yes → Use algorithms or graph (Part 6).</li></ol><p><strong>The practical shortcut:</strong> if you’re ever unsure, <strong>start with CP-SAT</strong>. It’s flexible enough to handle a lot of MIP-style problems too, and it’s the friendliest to learn on. Think of it as the “default tool” until you have a specific reason to reach for something else.</p><h3>Part 8: Learning Resources Worth Bookmarking</h3><p>Just a simple list of “where to go next” if you want to go deeper than this guide:</p><ul><li><strong>Official docs</strong> (developers.google.com/optimization) — the source of truth, always up to date.</li><li><strong>GitHub repo</strong> (github.com/google/or-tools) — the actual source code and more examples than any single guide could cover.</li><li><strong>CP-SAT Primer</strong> by Dominik Krupke — a free book specifically about CP-SAT, going deeper than this guide into advanced modeling.</li><li><strong>Language-specific references</strong> — if you switch from Python to Java or C#, there are dedicated docs for each.</li></ul><p>Think of these as your “next steps” once you’ve built your first project and want to go further.</p><h3>Happy to help!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e0d0ec8dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Mastery: The Complete Handbook Every Developer Needs (With Commands You’ll Actually Use Daily)]]></title>
            <link>https://medium.com/@srivarshagowthu/git-mastery-the-complete-handbook-every-developer-needs-with-commands-youll-actually-use-daily-d6cdedd790c1?source=rss-389b3a849836------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cdedd790c1</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[git-merge-conflict]]></category>
            <category><![CDATA[git-cherry-pick]]></category>
            <dc:creator><![CDATA[Srivarshagowthu]]></dc:creator>
            <pubDate>Fri, 15 May 2026 11:59:00 GMT</pubDate>
            <atom:updated>2026-05-15T11:59:00.440Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A no-fluff, everything-included guide — from your first <em>git init</em> to resolving merge conflicts like a pro.</blockquote><h2>Before We Begin: Why Git?</h2><p>If you’re a developer — junior, senior, or somewhere in between — Git is not optional. It’s the air your codebase breathes.</p><p>In short: <strong>Git is a distributed version control system</strong> that tracks changes in your code. Think of it as a <em>save-point mechanism</em> for your entire project. Every change you make, Git happily records it. Forever.</p><p>But why Git specifically? Here’s the honest answer:</p><ol><li><strong>Collaboration</strong> — Multiple developers can work on the same project simultaneously without overwriting each other’s work.</li><li><strong>History</strong> — You can see every single change ever made to your code and revert to any previous version if needed.</li><li><strong>Branching</strong> — Work on new features completely independently without touching the main production code.</li><li><strong>Backup</strong> — Your code is safely stored in remote repositories (GitHub, GitLab, Bitbucket, etc.).</li></ol><h2>The Three Stages of Git (Non-Negotiable Knowledge)</h2><p>Before touching a single command, understand this mental model. Git operates in <strong>three distinct stages</strong>:</p><pre>┌─────────────────────────────────────────────────────────┐<br>│                                                         │<br>│   Working Directory  →  Staging Area  →  Repository    │<br>│   (local files,         (changes you&#39;ve    (official    │<br>│    untracked)            prepared)          record)     │<br>│                                                         │<br>└─────────────────────────────────────────────────────────┘</pre><p>Files don’t jump straight from your editor into Git history. They pass through the staging area first — and this is intentional. It lets you control <em>exactly</em> what goes into each commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Wtgi3LRCRlGpC9GrbXuMIQ.png" /></figure><h2>Part 1: Setting Up &amp; Your First Commit</h2><h3>Initializing a Git Repository</h3><p>Navigate to your project folder, then:</p><pre>git init</pre><p>This creates a hidden .git folder — the brain of your repository. Everything Git knows about your project lives here.</p><h3>The Commit Workflow (The Most Important Flow in Git)</h3><pre># Step 1 — Make changes to your files<br># Step 2 — Stage them<br>git add &lt;filename&gt;       # Stage a specific file<br>git add .               # Stage ALL changed files<br># Step 3 - Commit them<br>git commit -m &quot;your commit message&quot;</pre><p><strong>Where do staged files go?</strong> Not directly into Git history — they land in the <strong>staging area</strong> first. Only when you commit do they become part of the official record.</p><blockquote>💡 <strong>Write good commit messages.</strong> A message like <em>&quot;fix bug&quot;</em> is useless. Write <em>&quot;fix login redirect on expired session&quot;</em> — describe what the commit does, not that it does something. and using “fixed bug” is also wrong the more professional way is “fixes bug”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*UqqbI-lquBp6DGsFOAOztw.png" /></figure><h3>The New Repository Shortcut</h3><pre>git init<br>git add .<br>git commit -m &quot;initial commit&quot;</pre><p>This is your boilerplate for every new project.</p><h2>Part 2: Viewing History &amp; Understanding SHAs</h2><h3>Viewing Commit History</h3><pre>git log</pre><p>This shows you the full commit log including:</p><ul><li><strong>SHA Hash</strong> (unique ID for each commit, e.g., a376b2d)</li><li><strong>Author</strong></li><li><strong>Date</strong></li><li><strong>Commit message</strong></li></ul><p>Each commit has a unique identifier called a <strong>SHA Hash</strong>. You only need the first 6–7 characters to reference it.</p><pre>git log --oneline</pre><p>One clean line per commit. Output looks like:</p><pre>a376b2d  add login page<br>f29c11a  fix navbar styling<br>3b8d002  initial commit</pre><blockquote>💡 <strong>Does Git track empty folders?</strong> No — Git tracks files, not folders. If you need to track an empty folder, create a file called <em>.gitkeep</em> inside it.</blockquote><h2>Part 3: Staging, Restoring &amp; Differences</h2><h3>Restoring Staged Files</h3><p>Made a mistake? Remove a file from the staging area without losing your changes:</p><pre>git restore --staged file.txt</pre><p>Restore the file to its last committed version (discard working directory changes):</p><pre>git restore file.txt</pre><blockquote>⚠️ <em>git restore file.txt</em> is destructive — it throws away uncommitted local changes permanently.</blockquote><h3>Viewing Differences</h3><pre>git diff</pre><p>Shows the difference between your <strong>working directory</strong> and the <strong>staging area</strong>.</p><pre>git diff --word-diff --color</pre><p>Highlights exact word-level changes — much easier to understand precisely what changed.</p><h3>The Staging Area in Depth</h3><p>Think of the staging area as a <strong>draft folder</strong>. You can add, remove, and reorganize what you’re about to commit before making it official. This is what separates Git from simpler systems.</p><pre>┌──────────────────────────────────────────────────────────────┐<br>│  git add file.txt  →  Staging Area  →  git commit  →  Repo  │<br>│                                                              │<br>│  git restore --staged file.txt  ←  (remove from staging)    │<br>└──────────────────────────────────────────────────────────────┘</pre><h2>Part 4: Deleting, Cleaning &amp; Amending</h2><h3>Deleting a File</h3><pre>git rm file.txt<br>git commit -m &quot;delete file.txt&quot;</pre><p>This removes the file from both your working directory and stages the deletion.</p><h3>Cleaning Untracked Files</h3><pre>git clean -n    # Dry run — shows what WOULD be deleted (safe preview)<br>git clean -f    # Actually removes untracked files</pre><blockquote>💡 Always run <em>git clean -n</em> first before <em>git clean -f</em>. No take-backs after <em>-f</em>.</blockquote><h3>Amending the Last Commit</h3><p>Forgot to add a file? Typo in your commit message?</p><pre>git commit --amend</pre><p>This lets you modify the most recent commit — update the message or add missing files — without creating a new commit.</p><blockquote>⚠️ Never amend commits that have already been pushed to a shared remote repository. It rewrites history and causes problems for collaborators.</blockquote><h2>Part 5: .gitignore — What Git Should Never See</h2><p>Some files should <strong>never</strong> enter your repository:</p><ul><li>.env files (API keys, passwords)</li><li>Database credentials</li><li>node_modules/</li><li>Temp/cache files</li><li>OS files (.DS_Store, Thumbs.db)</li></ul><p>Create a .gitignore file in your project root:</p><pre># .gitignore<br>.env<br>node_modules/<br>*.log<br>.DS_Store<br>database.sql<br>dist/</pre><p>Git will completely ignore everything listed here — they’ll never appear in git status or be staged accidentally.</p><h2>Part 6: Restoring from Repo &amp; git revert</h2><h3>Restore from Repo (Specific Commit)</h3><pre>git restore --source &lt;SHA&gt; file.txt</pre><p>Brings back a specific file as it existed at that commit.</p><h3>Revert a Commit</h3><pre>git revert &lt;SHA&gt;</pre><p>Creates a <strong>new commit</strong> that undoes the changes from a previous commit. This is the <em>safe</em> way to undo — it doesn’t rewrite history.</p><pre>Before: A → B → C<br>After:  A → B → C → C&#39; (reverts C)</pre><blockquote>✅ Use <em>git revert</em> when the commit has already been pushed to remote. It&#39;s safe for shared branches.</blockquote><h2>Part 7: Branches — The Real Power of Git</h2><h3>What Are Branches?</h3><p>Branches let developers work on features, bug fixes, or experiments completely independently — without affecting the main codebase.</p><pre>main:     ●───●───●───●───●<br>                  \<br>feature:           ●───●───●</pre><h3>Understanding HEAD</h3><p><strong>HEAD</strong> is a pointer that tracks your current position in the commit history. It always points to the latest commit of your current branch.</p><ul><li>HEAD → Points to the current commit</li><li>HEAD~1 → One commit before HEAD</li><li>HEAD~2 → Two commits before HEAD</li></ul><pre>git keep    # keeps track of empty files</pre><h3>Viewing Branches</h3><pre>git branch          # Show all local branches (* marks current)<br>git branch -a       # Show local + remote branches</pre><h3>Creating &amp; Switching Branches</h3><pre># Method 1 — Two steps<br>git branch new-feature<br>git switch new-feature</pre><pre># Method 2 — One step (recommended)<br>git switch -c new-feature</pre><blockquote>⚠️ <strong>Critical:</strong> Before switching branches, always <strong>commit</strong> or <strong>stash</strong> your changes. Git will stop you from switching if you have uncommitted work that would conflict.</blockquote><h3>Renaming a Branch</h3><pre>git branch -m old-name new-name</pre><h3>Deleting a Branch</h3><pre>git branch -d branch-name     # Safe delete (won&#39;t delete if unmerged)<br>git branch -D branch-name     # Force delete</pre><h3>Branch Workflow Diagram</h3><pre>1. git switch -c feature/login<br>2. Make changes<br>3. git add . &amp;&amp; git commit -m &quot;add login form&quot;<br>4. git switch main<br>5. git merge feature/login<br>6. git branch -d feature/login</pre><h2>Part 8: Merging Branches</h2><h3>Basic Merge</h3><pre>git switch main<br>git merge feature-branch</pre><p>This brings all commits from feature-branch into main.</p><h3>Merge Commit with a Message</h3><pre>git merge -m &quot;merge: adds login, 2nd file, and 3rd file commits&quot;</pre><p>A merge commit combines all changes from the feature branch into the target branch. It preserves <strong>all history</strong>.</p><h3>What Happens During a Merge</h3><pre>Before:<br>main:    A → B → C<br>feature:       → D → E</pre><pre>After git merge feature:<br>main:    A → B → C → M (merge commit)<br>                 ↗<br>feature:       D → E</pre><h2>Part 9: Resolving Merge Conflicts</h2><p>Conflicts happen when two branches change the <strong>same lines</strong> in the same file. Git can’t decide which to keep — so it asks you.</p><h3>What a Conflict Looks Like</h3><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD<br>This is from the main branch<br>=======<br>This is from the feature branch<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; feature-branch</pre><ul><li>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD — Your current branch&#39;s version</li><li>======= — The divider q q q q qq q q qqq c c c c c c c c c c c c cc cccccc</li><li>&gt;&gt;&gt;&gt;&gt;&gt;&gt; feature-branch — The incoming branch&#39;s version</li></ul><h3>Conflict Colour Codes (in UI tools like VS Code)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*99YlDhhKOwcY8j51B7ZEmg.png" /></figure><h3>Steps to Resolve a Conflict</h3><ol><li>Open the conflicting file</li><li>Decide which version to keep (or combine both)</li><li>Delete the conflict markers (&lt;&lt;&lt;&lt;&lt;&lt;&lt;, =======, &gt;&gt;&gt;&gt;&gt;&gt;&gt;)</li><li>git add &lt;file&gt;</li><li>git commit</li></ol><h3>Choosing a Side via CLI</h3><pre>git diff SHA1...SHA2      # See differences between two commits<br>git merge --abort         # Abort the merge entirely if needed</pre><h2>Part 10: Stashing — Save Work Without Committing</h2><p>Need to switch branches but aren’t ready to commit?</p><pre>git stash           # Stash current changes<br>git stash pop       # Re-apply stashed changes<br>git stash list      # See all stashes</pre><p>Stashing saves your work-in-progress to a temporary area and gives you a clean working directory.</p><h2>Part 11: git diff Deep Dive</h2><pre>git diff                          # Working dir vs staging area<br>git diff --staged                 # Staging area vs last commit<br>git diff SHA1 SHA2                # Between two commits<br>git diff --word-diff --color      # Word-level highlighting<br>git diff --stat                   # Summary of files changed</pre><h2>Part 12: Remote Repositories &amp; Collaboration</h2><h3>Local vs Remote</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hsO5etwO72pnS8J9bAoFbA.png" /></figure><h3>Connecting to Remote</h3><pre>git remote add origin &lt;url&gt;</pre><h3>Push &amp; Pull</h3><pre>git push origin branch-name     # Push local branch to remote<br>git pull                         # Fetch + merge from remote<br>git fetch                        # Download changes (don&#39;t merge yet)</pre><blockquote>💡 <em>git fetch</em> vs <em>git pull</em>: <em>fetch</em> downloads changes but doesn&#39;t apply them. <em>pull</em> = <em>fetch</em> + <em>merge</em>. Use <em>fetch</em> when you want to review before merging.</blockquote><h3>Common Collaboration Flow</h3><pre>git fetch<br>git switch main<br>git merge origin/main<br>git switch product-branch<br>git merge origin/product-branch<br>git add .<br>git commit -m &quot;your message&quot;<br>git push origin product-branch</pre><h2>Part 13: Cherry-Picking</h2><p>Apply a specific commit from one branch onto another — without merging the whole branch:</p><pre>git cherry-pick &lt;SHA&gt;</pre><p><strong>When to use it:</strong> You have a hotfix commit on a feature branch that you need on main immediately, without waiting for the full feature to be ready.</p><h2>Part 14: Rebase — Cleaner History</h2><h3>What Is Rebase?</h3><p>Rebase re-applies your commits on top of another branch, creating a <strong>linear, cleaner history</strong> — as if you branched off from the latest commit.</p><pre>Before rebase:<br>main:    A → B → C<br>feature:     → D → E</pre><pre>After git rebase main (from feature):<br>main:    A → B → C<br>feature:           → D&#39; → E&#39;</pre><p>Compare with merge:</p><ul><li><strong>Merge</strong> → Preserves full history, creates merge commits</li><li><strong>Rebase</strong> → Rewrites history to be linear, no merge commits</li></ul><pre>git rebase main</pre><blockquote>⚠️ Never rebase commits that have already been pushed to a shared remote branch. It rewrites history and breaks collaborators’ copies.</blockquote><h2>Part 15: Organisation Workflow (Real-World Team Flow)</h2><p>This is how professional teams actually work:</p><pre>1.  git clone &lt;repo-url&gt;             # Get the repo<br>2.  cd repo                          # Enter it<br>3.  git switch -c feature/your-task  # Create your branch<br>4.  # ... make changes ...<br>5.  git status                       # Check what changed<br>6.  git add .                        # Stage everything<br>7.  git commit -m &quot;feat: add X&quot;      # Commit with clear message<br>8.  git push origin feature/your-task # Push your branch<br>9.  # In GitHub UI → click &quot;Create Pull Request&quot;<br>10. # Team reviews → approves → merges</pre><h2>Part 16: Pull Requests &amp; Forking (Open Source Flow)</h2><h3>Collaborating on a Public Project</h3><ol><li><strong>Fork the repo</strong> — creates your own copy on GitHub</li><li><strong>Clone your fork</strong> locally</li><li><strong>Create a branch</strong> and do your work</li><li><strong>Push</strong> to your fork</li><li><strong>Raise a Pull Request</strong> from your fork to the original repo</li><li>Maintainers review → if satisfied, they merge it</li></ol><h3>Cherry Picking From a Specific Branch</h3><pre>git cherry-pick &lt;SHA&gt;</pre><h2>Part 17: git log Power Tricks</h2><pre>git log --oneline               # Compact one-line view<br>git log --oneline --all         # All branches<br>git log --graph                 # Visual branch graph<br>git log --graph --oneline       # Compact graph view<br>git log -n 10                   # Last 10 commits only<br>git log --author=&quot;Name&quot;         # Filter by author<br>git log --since=&quot;2 weeks ago&quot;   # Filter by date<br>git log -p                      # Show diff with each commit</pre><p>The --graph flag shows a visual representation of branch history — incredibly useful for understanding where branches diverged and merged.</p><h2>Part 18: The Commands Cheat Sheet</h2><pre># ── SETUP ──────────────────────────────────────────────<br>git init                         # Initialize repo<br>git clone &lt;url&gt;                  # Clone remote repo</pre><pre># ── STAGING &amp; COMMITTING ───────────────────────────────<br>git status                       # Show current state<br>git add &lt;file&gt;                   # Stage a file<br>git add .                        # Stage all changes<br>git commit -m &quot;message&quot;          # Commit staged changes<br>git commit --amend               # Edit last commit</pre><pre># ── HISTORY ────────────────────────────────────────────<br>git log                          # Full commit history<br>git log --oneline                # Compact history<br>git log --graph --oneline --all  # Visual branch graph</pre><pre># ── DIFFERENCES ────────────────────────────────────────<br>git diff                         # Working dir vs staging<br>git diff --staged                # Staging vs last commit<br>git diff SHA1 SHA2               # Between two commits</pre><pre># ── UNDOING ────────────────────────────────────────────<br>git restore &lt;file&gt;               # Discard working dir changes<br>git restore --staged &lt;file&gt;      # Unstage a file<br>git revert &lt;SHA&gt;                 # Safely undo a commit<br>git clean -n                     # Preview what clean removes<br>git clean -f                     # Remove untracked files</pre><pre># ── BRANCHES ───────────────────────────────────────────<br>git branch                       # List branches<br>git branch -a                    # List all (incl. remote)<br>git switch -c &lt;name&gt;             # Create + switch branch<br>git switch &lt;name&gt;                # Switch branch<br>git branch -m old new            # Rename branch<br>git branch -d &lt;name&gt;             # Delete (safe)<br>git branch -D &lt;name&gt;             # Delete (force)</pre><pre># ── MERGING &amp; REBASING ─────────────────────────────────<br>git merge &lt;branch&gt;               # Merge branch into current<br>git merge --abort                # Abort a conflicted merge<br>git rebase &lt;branch&gt;              # Rebase onto branch<br>git cherry-pick &lt;SHA&gt;            # Apply single commit</pre><pre># ── STASHING ───────────────────────────────────────────<br>git stash                        # Save uncommitted changes<br>git stash pop                    # Re-apply stashed changes<br>git stash list                   # List stashes</pre><pre># ── REMOTE ─────────────────────────────────────────────<br>git remote add origin &lt;url&gt;      # Connect to remote<br>git push origin &lt;branch&gt;         # Push to remote<br>git pull                         # Fetch + merge<br>git fetch                        # Fetch only (don&#39;t merge)</pre><h2>Part 19: The “Every Single Time” Workflow Bookmark This</h2><p>This is the exact sequence you run <strong>every time</strong> you work on a project. No exceptions. Tattoo it in your brain.</p><h3>🆕 Starting Fresh (New Project → New Remote Repo)</h3><pre># Step 1 — Go into your project folder via terminal / git cmd<br>cd your-project-folder</pre><pre># Step 2 — Initialize Git<br>git init</pre><pre># Step 3 — Stage all your files<br>git add .</pre><pre># Step 4 — Make your first commit<br>git commit -m &quot;initial commit&quot;</pre><pre># Step 5 — Connect to your remote repo (copy URL from GitHub)<br>git remote add origin &lt;your-repo-url&gt;</pre><pre># Step 6 — Set upstream and push for the first time<br>git branch --set-upstream-to=origin/main m</pre><pre># Step 1 initialize git</pre><pre>git init</pre><pre># Step 2 — Make your changes in the code editor</pre><pre>git add .</pre><pre># Step 3 — Check what changed<br>git status</pre><pre># Step 4— Commit with a clear message</pre><pre>git commit -m &quot;describe what you changed&quot;</pre><pre>git remote add origin (cloned url)</pre><pre>git branch -M main</pre><pre>git push --set -upstream origin main</pre><pre># if it shows pull error then <br> <br>git pull origin main --rebase</pre><pre># Step 5 — Push<br>git push --set -upstream origin main</pre><h3>🌿 Feature Branch Workflow (Team / Production Projects)</h3><pre># Step 1 — Always start from an updated main<br>git pull origin main</pre><pre># Step 2 — Create and switch to a new branch<br>git switch -c feature/your-feature-name</pre><pre># Step 3 — Make changes, then stage and commit<br>git add .<br>git commit -m &quot;feat: add your feature&quot;</pre><pre># Step 4 — Push your branch to remote<br>git push origin feature/your-feature-name</pre><pre># Step 5 — On GitHub/GitLab UI → Create Pull Request<br># Step 6 — After PR is merged → clean up<br>git switch main<br>git pull origin main<br>git branch -d feature/your-feature-name</pre><h3>🔧 Fixing a Pull Request Conflict (While It’s Open)</h3><pre># Step 1 — Switch to main and pull latest<br>git switch main<br>git pull origin main</pre><pre># Step 2 — Switch back to your feature branch<br>git switch feature/your-feature-name</pre><pre># Step 3 — Merge main into your branch to get latest changes<br>git merge main</pre><pre># Step 4 — Resolve conflicts in your editor, then<br>git add .<br>git commit -m &quot;resolve merge conflicts&quot;</pre><pre># Step 5 — Push again (PR updates automatically)<br>git push origin feature/your-feature-name</pre><blockquote>💡 <strong>The Golden Rule:</strong> Always <em>git pull</em> before you start working. Always. This saves you from 90% of merge conflicts.</blockquote><h3>📋 Quick Reference Card</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SF-GzVzvNqWb27YXQUlqHA.png" /></figure><h2>Closing Thoughts</h2><p>Git feels intimidating at first — but it’s just a small set of concepts applied consistently. The three stages (working directory → staging → repository), the branching model, and the push/pull remote flow cover 90% of everything you’ll ever do.</p><p>Start with the basics. Commit often. Write meaningful messages. Branch for every feature. And never fear the merge conflict — it’s just Git asking for your opinion.</p><p>Happy committing! 🚀</p><p><em>Found this useful? Follow me on Medium for more developer tooling deep-dives. Drop a comment if there’s a Git concept you want me to cover next.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cdedd790c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>