teleren/devto huggingface dataset:
Conditional Branching with workflow_dispatch and workflow_call in GitHub Actions
Tags: githubactions, cicd
Published: 2024-03-08 17:41:05

## Introduction

There's a feature in GitHub Actions for reusing workflows. With workflow reuse, you can call another workflow from a workflow.

https://docs.github.com/en/actions/using-workflows/reusing-workflows

In doing so, there was a need to branch depending on whether the called workflow was called from another workflow, or if the workflow was executed standalone. This article describes how to do that.

## How to

In GitHub Actions, you can obtain various information from the context at runtime.

https://docs.github.com/en/actions/learn-github-actions/contexts

Among these, there exists a key named `github.event.workflow`. This value contains the file path of the workflow.

Depending on how it was called, the called workflow can obtain the following values (in the case where workflowA calls workflowB):

When executing workflowB directly (`workflow_dispatch`), the value of `github.event.workflow`
The file path of workflowB (`.github/workflows/workflow-b.yaml`)
When executed from workflowA (`workflow_call`), the value of `github.event.workflow`
The file path of workflowA (`.github/workflows/workflow-a.yaml`)
With this, you can branch your process or steps.

For example, if you want to execute a step only when workflowB is executed directly, you can add the following condition:

```yaml
if: github.event.workflow == '.github/workflows/workflow-b.yaml'
```

There's also a `github.event_name`, and I tried to see if it could be used for branching as well, but both the direct execution of workflowB and the execution from workflowA resulted in the same value as `workflow_dispatch`, so it couldn't be used for branching.

## About type: environment

In practice, I think you can use the same workflow without branching by defining inputs with the same name as below, but since `type: environment` exists only for `workflow_dispatch`, if you are using this, you'll need to add a step to absorb the difference.

```yaml
on:
  workflow_dispatch:
    inputs:
      input1:
        required: true
        type: string    
  workflow_call:
    inputs:
      input1:
        required: true
        type: string
```

The value in the environment (environment_name) can be used as is, but as shown above, this difference occurs, so it seems better to avoid it when making a `workflow_call`.

## Summary

There seem to be various methods, but by checking `github.event.workflow`, we were able to branch based on the method of executing the workflow.
Top 10 code smells every engineer should know to improve their pull requests
Tags: codereview, beginners, programming, productivity
Published: 2024-03-08 17:20:00

How to avoid difficult code reviews? Identify code smells!

According to [Wikipedia](https://en.wikipedia.org/wiki/Code_smell):

> In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem.
 
After a few years of helping developers review code, I came up with 10 code smells and how to fix them while building my project [Axolo](https://axolo.co).

### 🧐 Refactoring Large or Complex Methods

Navigating through methods that sprawl across numerous lines or twist into complexity can be daunting. Simplification is key!

The fix? Employ a linter to enforce a maximum number of lines. Deconstruct these behemoths into smaller, more focused methods, each dedicated to a singular task.

### 🤔 Addressing Long Parameter Lists

A lot of parameters can muddle method signatures, making them prone to mistakes.

The fix? Consolidate related parameters into a single object. Adopt the "parameter object" pattern to streamline your functions, enhancing their readability and maintainability.

### 🙄 Minimizing Excessive Comments

An overload of comments often signals that the code isn't speaking for itself as clearly as it should.

The fix? Strive for code that explains itself through judicious naming and structure. Reduce reliance on comments, allowing the code's purpose and function to be immediately apparent.

### 🤦 Eliminating Duplicate Code

Repetitive code fragments are not just a nuisance; they complicate updates and can introduce inconsistencies.

The fix? Seek out and consolidate repetitive code segments into common functions. Adhering to the DRY (Don't Repeat Yourself) principle simplifies future maintenance and modifications.

### 😕 Harmonizing Inconsistent Naming Conventions

Naming chaos confounds understanding and introduces potential errors.

The fix? Commit to a unified naming convention. Names that are clear and consistent pave the way for code that's more approachable and decipherable.

### 😬 Enhancing Error Handling

Neglecting comprehensive error management can lead to erratic behavior and a codebase that's tough to sustain.

The fix? Embrace thorough error management. Logically log and manage exceptions to bolster the code's stability and dependability.

### 🤯 Simplifying Overused If/Else Constructs

An abundance of if/else branches can tangle code, making it challenging to read and adjust.

The fix? Lean on data structures or design patterns, such as polymorphism, to untangle complex logic, thereby enhancing the code's legibility and adaptability.

### 👎 Refining Inheritance Usage

Inappropriate reliance on inheritance can entangle code further, reducing its adaptability.

The fix? Verify that inheritance is used judiciously. Opt for composition over inheritance to achieve a code structure that's more flexible and straightforward to maintain. 

Be honest, which one do you usually see in your PR? If you think I'm missing something, let me know in the comments!
Hello guys can you help me in this Laravel code
Tags: webdev, laravel, php, beginners
Published: 2024-03-08 17:01:45

this is the  html form in '**.blade.php' : 

```
<form action="{{ route('ruby.destroy') }}" method="POST">
      @csrf
      @method('delete')
      <button>delete</button>
</form>
```
this is the logic code in '**Controller.php' : 

```
public function destroy($MessageId)
    {
        $chat = Ruby::find($MessageId);
        dd($chat);
        //$message->delete();
        
    }
}
```

The probleme : 

```
Missing required parameter for [Route: **.destroy] [URI: ********/{**}] [Missing parameter: chat].
```

PLS contact me to give me help to solve this error
Thanks.
Problemas com Variáveis Globais: Prós e contra
Tags: go, global, variable, webdev
Published: 2024-03-08 16:46:14


**Manutenção:** Elas podem levar a código que é difícil de manter e testar. Variáveis globais podem ser modificadas por qualquer parte do programa, tornando difícil rastrear e prever o estado do programa.

**Concorrência:** Em um ambiente de execução concorrente, como é comum em Go, o acesso não sincronizado a variáveis globais pode causar condições de corrida, onde múltiplas goroutines leem e escrevem na mesma variável simultaneamente, levando a resultados inesperados e bugs difíceis de depurar.

**Dependência:** Código que depende de variáveis globais pode ser mais difícil de isolar em testes unitários, o que reduz a qualidade dos testes e pode aumentar o risco de defeitos no software.

**Benefícios e Boas Práticas:**

**Configuração Inicial:** Em certos cenários, como configuração inicial de aplicativos ou definição de constantes, as variáveis globais podem ser úteis e aceitáveis.

**Padrões de Design: **Para evitar os problemas associados com variáveis globais, padrões de design como "Singleton" ou injeção de dependência podem ser utilizados. Esses padrões permitem um maior controle sobre o acesso e a modificação do estado global.

**Sincronização:** Se o uso de uma variável global é inevitável, garantir que o acesso seja sincronizado, como utilizando mutexes, pode mitigar problemas de concorrência.

**Conclusão:**

A utilização de variáveis globais deve ser evitada quando possível. Alternativas como o uso de estruturas e métodos para encapsular estado e injeção de dependência devem ser preferidas para criar um código mais limpo, testável e manutenível. Quando necessário, seu uso deve ser cuidadosamente controlado e sincronizado para evitar condições de corrida e outros bugs relacionados à concorrência.
Can anyone help me make this code work
Published: 2024-03-08 16:44:25

# faca um programa que leia a largura e altura de uma parede em metros, calcule sua area e quantidade de tinta necessario para pintar, sabendo que cada litro de tinta pinta uma area de 2m quadrado

import random

altura = [2, 2.34, 3, 3.45, 4, 6, 10.2]
largura = [15, 100, 6.67, 3.99, 5.67, 2.67, 200]

#alturas aleatorio
new_altura = print(random.sample(altura, 1))
new_largura = print(random.sample(largura, 1))

# transforme em metros quadrado
metros_quadrado = new_altura * new_largura
 
# total da tinta
quantidade_tinta = metros_quadrado / 2

print(f'Parede uma parede de {metros_quadrado}\nVc precisara de {quantidade_tinta:.2f} de latas de tintas.')


#Resposta:
metros_quadrado = new_altura * new_largura
                      ~~~~~~~~~~~^~~~~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
How To Bet On Cricket Online? 2024
Tags: bet, cricket, ipl, india
Published: 2024-03-08 16:43:59

Are you curious to know how you can bet on cricket online? Cricket is one of the most popular sports in the world, with millions of fans. With the rise of online sports betting, more and more cricket fans are looking to bet on their favourite matches and tournaments. Betting on cricket online opens up a whole new world of opportunities to engage with the sport. In this article, we’ll walk you through everything you need to know to start betting on cricket matches online.

Choose A Reputable Betting Site
The first step is choosing a sincere online bet site. Look for websites that are certified and regulated for your vicinity. Reputable websites like Sportsx9 offer secure and secure cricket making a bet with competitive odds. Check that the website online offers betting at the cricket tournaments and matches you want. You’ll also want to recollect welcome bonuses, ongoing promos, charge options, and cell compatibility. [Continue...](https://bet.sportsx9.com/cricket-betting/how-to-bet-on-cricket-online/)
C++ Урок #7
Tags: programming, beginners, tutorial, cpp
Published: 2024-03-08 16:35:15

## Оператор Switch
Привет, друзья! Сегодня мы рассмотрим еще один полезный инструмент в языке программирования C++ - оператор `switch`. Он предоставляет возможность управлять выполнением кода в зависимости от значения определенной переменной. Давайте разберемся, как это работает.

```
#include <iostream>

using namespace std;

int main() 
{
    int day;
    cin >> day;
    string dayName;

    switch (day) 
    {
        case 1:
            dayName = "Понедельник";
            break;
        case 2:
            dayName = "Вторник";
            break;
        case 3:
            dayName = "Среда";
            break;
        case 4:
            dayName = "Четверг";
            break;
        case 5:
            dayName = "Пятница";
            break;
        default:
            dayName = "Выходные";
    }

    cout << "Сегодня " << dayName << endl;
    return 0;
}
```
Этот код проверяет значения переменного day и сравнивает с каждым case если значение day не совпадает не одному из case то код выполняет действие написанное в default.

В этом примере пользователь выбирает опцию, и программа выводит соответствующее сообщение на основе выбора с помощью оператора `switch`.

Оператор `switch` - это мощный инструмент, который делает код более читаемым, особенно когда есть множество вариантов выполнения. Это очень полезное средство в арсенале любого программиста на C++! 🚀
Learning React State
Tags: webdev, codenewbie, beginners, react
Published: 2024-03-08 16:33:28

100DaysOfCode: Day 2

Today, I dove into React state management!
Explored what state is, how it works in React, and learned to update and structure state efficiently.
Also, got a grip on controlled components for more dynamic user interfaces.
Stay tuned for more updates! 💻🚀
45 best home business ideas
Tags: home, business, ideas, money
Published: 2024-03-08 16:19:50

1. Become an Online Consultant
2. Become a Virtual Assistant
3. Start a Blog Business
4. Teach Art Online
5. Sell Online Tutorials

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57zpk6tyvtw024vouwhl.JPG)

_**=== Here is an Item for [Fastest Online Results](https://cutt.ly/profitpad-review)**_

6. Start a Freelance Writing Business
7. Become a Graphic Designer
8. Start an Etsy Shop
9. Start an amazon FBA business
10. Be a Reviewer
11. Do Bookkeeping and Accounting Work
12. Proofreading and Editing Service

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymrqqxy01dkfgjhnworw.JPG)

13. Become an Online Coach
14. Affiliate Marketing

_**=== Check For “[All-In-One 2024 Ready Email Marketing Solution](https://medium.com/r/?url=https%3A%2F%2Fcutt.ly%2Fprofitmarc-review)”
**_
15. Become an Illustrator
16. Start a Clothing Business from Home
17. Food Service Business
18. Sell Home Baked Items from Home

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7blk16ifexmi3uhe31xv.JPG)
19. Make Customized Gifts
20. Handmade Jewellry Business
21. Sewing Business
22. Kids Party Event Planner
23. Sell Paintings
24. Become a Personal Fitness Trainer
25.Sell Paintings
26. Freelance Photography
27. Voiceover Artist
28. Webinar Host
29. Become a Yoga Instructor
30. Food Truck Business
31. Start a Cleaning Service
32. Lawn care service
33. Interior Designing
34. Start a Laundry Service
35. Become an Airbnb host
36. Car Rental Business
37. Tent and Party Rentals Service
38. Event Planning Service
39. Freelance Makeup Artist
40. Freelance Hair Stylist
41. Body Care Products Business
42. Sell crafts

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xke0jys07bzmjz7r903a.JPG)
43. T-shirt Design Business
44. Become a Florist
45. Start a Youtube Channel

**_==Start Your A.I Powered YouTube™ Empire N Tap Into This USD29.2 Billion Market [For Big Business Profit!](https://cutt.ly/quantum-review)_**

                            ==The End==
Source: Collected From Social Media
Handy `git` aliases I use day to day
Published: 2024-03-08 16:08:57


![git](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6sogkxh05sq8he9bvml.png)


These aliases provide shortcuts for Git commands I commonly use, making your workflow faster and more efficient.

```shell
git config --get-regexp alias
# list of handy git aliases I use.

git config --global --unset alias.trololo
# to remove git alias you don't want any more

git config --global alias.co 'checkout'
# check out a branch

git config --global alias.new 'checkout -b'
# create a new branch

git config --global alias.ps 'push'
# push to the remote repository

git config --global alias.pl 'pull'
# pull from the remote repository

git config --global alias.st 'status -sb'
# shows the current branch, unstaged changes, and staged changes

git config --global alias.ll 'log --oneline'
# displays the git log in a single line format for each commit

git config --global alias.last 'log -1 HEAD --stat'
# shows information about the most recent commit

git config --global alias.cm 'commit -m'
# commit changes with a message

git config --global alias.rv 'remote -v'
# view information about remote repositories

git config --global alias.gl 'config --global -l'
# lists all configured git aliases and settings

git config --global alias.se '!git rev-list --all | xargs git grep -F'
# search all commits for a keyword

git config --global alias.dnm '!git branch | grep -v "master\\|main" | xargs git branch -D'
# delete all branches other than master or main

git config --global alias.fb '!git fetch && git rebase origin/main'
# fetch changes from the remote and rebase the local branch

git config --global alias.fm '!git fetch && git merge origin/main'
# fetch changes fromt he remote and merge the local branch
```
Celebrate International Women's Day with New Swag & A Sweet Surprise 💖
Tags: wecoded, womenintech, lgbtq
Published: 2024-03-08 16:00:00

It's International Women's Day! As we continue our month-long celebration of gender equity in tech with [we_coded](https://dev.to/wecoded), we're excited to unveil some fun items for you to proudly wear and show your support for the cause all year long. (Plus, they are very cute; I would know, I designed them!)

Without further ado, head to our shop to check out the new swag and show some support!

{% cta https://shop.forem.com/ %} View Our Merch Shop {% endcta %}

---

### Share Your Story, Save 20%
**PLUS**: We have a coupon code for **20% off all items in our shop** available to you if you write your very own we_coded post before the month is over!

{% embed https://dev.to/devteam/wecoded-2024-empowering-change-for-gender-equity-in-tech-30nj %}

### Here's how it works:
Whether it's a personal story, a piece of advice, or a call to action, we want to hear your words!

- Publish your post by [starting from scratch](https://dev.to/new) or using [this template](https://dev.to/new/wecoded)
- Tag it [#wecoded](https://dev.to/t/wecoded)
- Once our team validates the post, you can **expect an email from us with your coupon code** within a few days 
- Make sure you have your email correct [in your settings on DEV](https://dev.to/settings) in order to obtain your coupon code

_Note: This is a collective action movement to inspire an inclusive, harassment-free environment! All #wecoded posts will be reviewed by someone on our team. If you would like to learn about the community we’re fostering, please visit our [Code of Conduct and Community Guidelines](https://dev.to/code-of-conduct)._

---

Also, make sure to check out our tag page and landing page to learn more about our mission with we_coded:

{% embed https://dev.to/t/wecoded %}

{% cta https://dev.to/wecoded %} View Our Landing Page {% endcta %}

---

We hope to see your work soon!

-**Rachel + The DEV Community Team**
The GitHub Community Roundup: 03-08-24
Tags: github, community, news, developers
Published: 2024-03-08 15:59:56

Hey folks! Welcome to another edition of the GitHub Community Roundup! There's been some amazing content this week that from the community:

- I enjoyed this post by @aksrao1998 where he shows us how to [triggers workflows in two repositories and share data between the two](https://dev.to/aksrao1998/trigger-workflows-of-different-repositories-and-exchange-data-5a1p).

- @shariqahmed525 shared [pros and cons of using GitHub Copilot](https://dev.to/shariqahmed525/what-are-the-pros-and-cons-of-using-github-copilot-5deo) which was quite insightful! 

- Yan Holtz wrote a nice introduction to GitHub! Check it out, especially if you're new to the platform. 
{% embed https://twitter.com/R_Graph_Gallery/status/1766096644880183681 %}

- Shinya's post on CodeQL teaches us why the tool is a [beneficial game changer for code analysis](https://www.linkedin.com/posts/shinyay_100daysoflearning-github-codeql-activity-7171875774633758721-XT3_?utm_source=share&utm_medium=member_desktop).

- Learn about the [GitHub Student Developer pack](https://www.linkedin.com/posts/billups-tillman_github-softwareengineering-csstudents-activity-7170641697784188928-GY3M?utm_source=share&utm_medium=member_desktop)! An amazing programming resource for students filled with tonns of benefits! Thanks for the great write up Billups.

If you’ve written an article about GitHub or find some great content about GitHub or any of its features or products, please share it with the #GitHub hashtag on Dev.to, Twitter or LinkedIn!

## What's new at GitHub this week?

Well, exciting news! **GitHub Copilot Chat** is now GA in JetBrains IDE! 🚀

![GitHub Copilot Chat in JetBrains IDE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57eqvya2b5llxdpel6py.png)

Learn more about how you can get started by [reading our blogpost](https://github.blog/changelog/2024-03-07-github-copilot-chat-general-availability-in-jetbrains-ide/) or watch the youtube video.

{% embed https://www.youtube.com/watch?v=Di-kkTO6b88 %}

- Learn how to create your first terraform module with GitHub by checking out [this video](https://youtu.be/oVZ8c2D0t-s?si=iNwn9A2kDWaMmrsy). 

- Did you know that Autocoder was one of the first attempts at automatic coding? Back in 1950?! Yea, me either! Read more about the [Hard and soft skills for developers coding in the age of AI](https://github.blog/2024-03-07-hard-and-soft-skills-for-developers-coding-in-the-age-of-ai/) where we touch on the brief history of Ai-powered tools. 

- Learn [How GitHub uses merge queue to ship hundreds of changes every day](https://github.blog/2024-03-06-how-github-uses-merge-queue-to-ship-hundreds-of-changes-every-day/) in this blog post

- Discover how to keep repository maintainer information accurate through CODEOWNERS file in [this blog post](https://github.blog/2024-03-04-keeping-repository-maintainer-information-accurate/). 

A huge thanks goes out to all the contributors to the technical community this week!

Happy Friday and we'll see you all next time for the latest GitHub community updates. ✨
Best Online Course Recommendations for IT Professionals and Students
Tags: learning, cloud, devops, career
Published: 2024-03-08 15:58:46

Hey everyone, this series has been a dream of mine for a long time.

In the IT industry and for students in college, there has always been a big question of how to upskill myself and where to find quality content at an affordable price.

Here I am going to provide my honest opinion on best instructors, best platforms, and best courses to learn ensuing you would learn from the best, become great in your career, and ultimately be able to take care of your family better by landing a great job.

I will provide the following list of technologies for which I will provide the best recommendations:

## Technologies

1. **Cloud** - Amazon Web Services, Microsoft Azure, Google Cloud Platform
2. **Programming Language** - Python, Java, Go
3 **Full Stack Development** - HTML5, CSS3, JavaScript, Angular, React, VueJS, Node, Express
4. **Databases** - MySQL, MongoDB, PostgreSQL
5. **Backend** - Java, Spring, SpringBoot, Hibernate.
6. **Infrastructure as Code** - Terraform, Pulumi, AWS CloudFormation, Azure Arm Templates
7. **Mobile App Development** - Flutter, ReactNative
8. **Configuration Management** - Chef, Puppet, Ansible
9. **Containers and Orchestration** - Docker, Kubernetes, Helm
10. **CI/CD** - GitLab CI, GitHub Actions, Azure DevOps, Jenkins
11. **GitOps** - ArgoCD, FluxCD

These technologies are some that I have highlighted. There are plenty more that I'll cover in the future.

I am happy to discuss any topic you would like. 

> Please leave your comments below.
Polaris: a workflow orchestrator in Go
Tags: go, webdev, programming, opensource
Published: 2024-03-08 15:54:54

Convert messy and lengthy business logic into neat little chunks of code with Polaris. Low integration efforts, big benefits.

If your backend is powered by Go, take a [look](https://harshadmanglani.github.io/polaris)!

[Repo](https://github.com/harshadmanglani)