teleren/devto huggingface dataset:
Code Smell 93 - Send me Anything
Tags: oop, programming, webdev, javascript
Published: 2021-10-13 03:31:27

*Magic functions that can receive a lot of different (and not polymorphic arguments)*

> TL;DR: Create a clear contract. Expect just one protocol.

# Problems

- Fail Fast principle violation

- Error prune

- Readability

- [If polluting](https://dev.to/mcsee/how-to-get-rid-of-annoying-ifs-forever-1jfg)

- [Nulls](https://dev.to/mcsee/null-the-billion-dollar-mistake-1h1c)

- Bad Cohesion

# Solutions

1. Take just one "kind" of input

2. Arguments should adhere to a single protocol.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/d6efbffa513dae1c59059439c64eea1b)
```php
<?

function parseArguments($arguments) {
    $arguments = $arguments ?: null;
    //Always the billion-dollar mistake
    if (is_empty($arguments)) {
        $this->arguments = http_build_query($_REQUEST);
        //Global coupling and side effects
    } elseif (is_array($arguments)) {
        $this->arguments = http_build_query($arguments);
    } elseif (!$arguments) { //null unmasked
        $this->arguments = null;
    } else {
        $this->arguments = (string)$arguments;
    }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/7876a9b6bacf55a72abcaf5e2ca2e008)
```php
<?

function parseArguments(array $arguments) {
    $this->arguments = $arguments;
    //much cleaner, isn't it ?
}
```

# Detection

We can detect this kind of methods when they do different things, asking for the argument *kind*

# Tags

- If Polluter

# Conclusion

Magic castings and flexibility have a price. They put the rubbish under the rug and violate fail fast principle.

# Relations

{% post https://dev.to/mcsee/code-smell-69-big-bang-javascript-ridiculous-castings-49ij %}

{% post https://dev.to/mcsee/code-smell-06-too-clever-programmer-37lb %}

{% post https://dev.to/mcsee/code-smell-12-null-la4 %}

# Credits

Photo by <a href="https://unsplash.com/@henniestander">Hennie Stander</a> on <a href="https://unsplash.com/s/photos/juggler">Unsplash</a>
  

* * *

> Referential transparency is a very desirable property: it implies that functions consistently yield the same results given the same input, irrespective of where and when they are invoked.

_Edward Garson_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Creating a CI/CD pipeline!
Tags: cloud, cloudresumechallenge
Published: 2021-10-13 03:23:33

Fairly quick post today.

I was going to work on the next step of the webpage by adding a counter in React, but the whole not-having-version-control-set-up was starting to bother me. All my projects at work use Git, so why shouldn't I be able to use it here?

I also ran into a bit of a snag, I was cleaning up some of the template features that I didn't really need, and OOPS I deleted some bootstrap code that handled the page formatting. Bad news: I deleted it. Good news: I still had the template saved. So all I had to do was just copy the files I had removed. Another reason I need to get Git set up ASAP!

So I went to my GitHub page ([shameless plug](https://github.com/danipo), though not impressive in the least) and created a new repo. 

New lesson! If you're using VSCode, you don't need to create the repo. You can push the working directory into a new GitHub repo using their built-in source control handler. I deleted the one I had made on the site, and pushed the local folder to a new repo.

That was the easy part. Next, that repo has to communicate with S3. This is where Github Actions come in. I was already familiar with pipelining previously as my work uses Gitlab and their similar CI/CD tools, so the YAML structure was very easy to set up and understand. I just needed to figure out how to talk to S3.

Luckily that was also pretty easy with a few searches. I landed on [this blog] (https://blog.iamvarshith.dev/how-to-deploy-the-static-website-to-s3-using-github-actions) which went step by step detailing adding the AWS Access Keys to my Secrets and what to add to the YAML. 

From there I ran a few tests, checking in a few small changes to see if they showed up in GitHub, succeeded the pipeline, and showed up in my Bucket. Then opened up my website in my mobile browser to verify. And it was all done!

Finally some version control, peace of mind, and some sleep!

Until next time!
Why do I even need favicon to prevent server errors? And, why the default is .ico?
Tags: favicon, webdev, discuss, electron
Published: 2021-10-13 02:02:58

Do I even need `/favicon.ico` for `http://localhost` or Electron?

Right now? I use 1px PNG (not ICO) at `/f/favicon.png` (not at `/`, but at `/f/`). I think it is at least better than using a a short string of data URI (where Fastify Helmet or Express Helmet won't allow).

```sh
pip install pillow
python -c 'from PIL import Image;Image.new("RGBA", (1,1), color=(0,0,0,0)).save("favicon.ico", sizes=[(1,1)])'
```
Working with Git Remotes
Tags: github, git, javascript, opensource
Published: 2021-10-13 01:44:19

## Adding new feature to other project

I chose one of the javascript project to work on, and I was having little to no knowledge on javascript, which made the lab extremely tough for me - but I think this is the sake of working with other projects in other language, which I can learn. I added configuration feature to pass a config file in json format.
I added a feature to update the language, input, output, and stylesheet configuration as the user's custom configuration. 
T

By using 
```
-c( or --config) *filename* 
```
it would update the configuration.

Here is the changes that I made. https://github.com/Kevan-Y/text-ssg/pull/23/files
Also in the PR, there were back and forth communication with Kevan, he gave me feedbacks and I updated. 
https://github.com/Kevan-Y/text-ssg/pull/23
Learning new language and frameworks are always exciting. 



## Merging other's repo with command line

I had some issue with the process of merging the pull request.
At first, I forgot that I had to use commands, and merged the project manually in github as usual. I realized I manually merged it, and had to revert the commit. I added Leyang's remote repo in my local repo using git bash. However I was not able to merge Leyang's repo without a pull request opened. 
Since I am not authorized to create PR from Leyang's repo, I had to revert the reverted PR. I was able to finally work with the git command to merge the PR, but since the branch was created within my repo (because of the revert), I was only able to experience part of the learning through this lab. 
Original PR created by Leyang is https://github.com/irenejoeunpark/ssgApplication/pull/19
You are welcomed to look at our collaboration works.
🚪 Really exit!
Tags: javascript, node
Published: 2021-10-13 01:29:43

Here's a funny (and really unimportant) thing I discovered about Node.js today.

First, for anyone who may not know, if you ever want to see the source code of a JavaScript function, you can just call `.toString()` on the function. (*if* it's a JavaScript function, and not one that's implemented in native code inside of the JS engine itself)

Let's try it on `process.exit`:

```js
console.log(process.exit.toString());
```

Here's what we get as output:

```js
function exit(code) {
  if (code || code === 0)
    process.exitCode = code;

  if (!process._exiting) {
    process._exiting = true;
    process.emit('exit', process.exitCode || 0);
  }
  // FIXME(joyeecheung): This is an undocumented API that gets monkey-patched
  // in the user land. Either document it, or deprecate it in favor of a
  // better public alternative.
  process.reallyExit(process.exitCode || 0);
}
```

It turns out that `process.exit()` is just a thin wrapper around another function, `process.reallyExit()`! `process.reallyExit()` is a native function, so we can't inspect its code in this manner (but you can [find it in Node's source code on GitHub if you're interested](https://github.com/nodejs/node/blob/f1658bdc8f84950b4fab9e8a4e1561fd05a043df/src/node_process_methods.cc#L442)).

This tickled me. It's a good reminder that there are always some funny, hacky things in the technologies we know and love.
The Odin Project: Landing page: walk-through
Tags: webdev, tutorial, beginners, css
Published: 2021-10-13 01:17:32

## There is a never-ending supply of “free” educational materials. 

But how do you know if they are “_good_” - if you don't know that much about the subject yet?

Well, one way - is to see the final product.

Today, I'd like to talk about TOP's landing page project from their fundamentals course.

### Here are some of the outcomes:

![Figure of many broken website layouts](https://community.codenewbie.org/remoteimages/uploads/articles/yhnl2vsdhoie93xtpwfb.jpeg)

_To be fair_, They say:

> “Do not worry about making your project look nice on a mobile device. We’ll learn that later.”

But in a world where 80% of traffic is on a small screen, we feel like this is starting newcomers off on the wrong foot. HTML and CSS are better than ever and learning from a small-screen-first approach has _massive_ benefits beyond just the responsive layout bits. (Did I just turn English for a minute?)

It's much more difficult to undo mental models later - than to just get them right in the first place.

You can check out the whole lesson/[project outline](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/landing-page).

(it has the mockup etc.)

If you want a challenge, give it a shot! 

and when you're done, you can see my take on it:

{% vimeo 622166595 %}

If you have any thoughts about this, we'd love to hear them. Have you gone through the TOP foundation course? Did we miss anything? We can splice in any of your suggestions. : )

I hope you find it helpful.



---

Hey - and - if you feel like doing some flexbox challenges: we have some "_free_" (haha) ones right here: [https://perpetual.education/exercises/flexbox-part-1](https://perpetual.education/exercises/flexbox-part-1/)
Java Switch Statements
Tags: java, programming, opensource, dsa
Published: 2021-10-12 20:02:45

###What are java statements?
Use the switch statement to select one of many code blocks to be executed.

###Syntax:
```
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
```

###How does it work?

* The switch expression is evaluated once.
* The value of the expression is compared with the values of each case.
* If there is a match, the associated block of code is executed.
* The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

####Example:
```
int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)
```

###The break Keyword
When Java reaches a *break* keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

###The default Keyword
The default keyword specifies some code to run if there is no case match:

####Example:
```
int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
```
* Note that if the default statement is used as the last statement in a switch block, it does not need a break.

For a more detailed introduction to java programming, I would surely encourage you to check out this wonderful toturial
[Switch Statements + Nested Case in Java](https://www.youtube.com/watch?v=mA23x39DjbI&list=PL9gnSGHSqcnr_DxHsP7AW9ftq0AtAyYqJ&index=6&t=569s) by *Kunal Kushwaha*

Feel free to connect with me on [github](https://github.com/rukundob451) and [Linkedin](https://www.linkedin.com/in/benjamin-rukundo-539ab01a6/), thank you.
Top 10 websites to learn python for free
Tags: python, tutorial, programming, beginners
Published: 2021-10-13 00:55:14

This website from Dr. Chuck Severance
1- [py4e] (https://2u.pw/OmN30) 

2- [w3schools] (https://2u.pw/0PtmJ)

3- [guru99] (https://2u.pw/OL8nP)

4- [tutorialspoin] (https://2u.pw/WHgnK)

5- [geeksforgeeks] (https://2u.pw/1EDdv) 

6- [freecodecamp] (https://2u.pw/YEX4J)

7- [realpython] (https://2u.pw/rZmwZ)

8- [techbeamers] (https://2u.pw/45IO0)

9- [developers.google] (https://2u.pw/37U2G)

10- [docs.microsoft] (https://2u.pw/nYrXS)
Intro To MongoDB Realm with VueJS Ionic Framework And ViteJS, Refactoring Application State with Composition API
Tags: mongodb, realm, ionic, vue
Published: 2021-10-13 00:36:29



The [MongoDB Realm Web SDK](https://docs.mongodb.com/realm/web/#std-label-web-intro) enables browser-based applications to access data stored in MongoDB Atlas and interact with MongoDB Realm services like Functions and authentication. The Web SDK supports both JavaScript and TypeScript applications.

{% youtube Uq8DUd6jF2w %}

In this short video we are refactoring application state related to Realm and Mongodb into a separate composition function instead of using something like vuex for state manager. We start with the code from the [previous video](https://www.youtube.com/watch?v=HIIqSWB_4G8)

Currently, there is no solution for writing to the local database as a replacement for sqlite in an Ionic Application. It looks like some people have started to build a plugin, but didn't get too far.

We are building the application using [Vuejs](https://v3.vuejs.org/), it is being packaged and developed using [ViteJS](https://vitejs.dev/) and the UI Components are from [Ionic Framework](https://ionicframework.com/vue)

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/W7W31U7HM)

```react
// realm-state.ts
import * as Realm from "realm-web";
import { computed, ref } from "vue";

const user = ref<any>(null);

// get app instance
const app = Realm.getApp("application-vue-1-afmqh");
user.value = app?.currentUser;

export const useAppState = () => {
  const isLoggedIn = computed(() => user.value !== null);

  /**
   *
   */
  const login = async (email: string, password: string) => {
    const credentials = Realm.Credentials.emailPassword(email, password);
    await app.logIn(credentials);

    // Refresh a user's custom data to make sure we have the
    // latest version
    await app?.currentUser?.refreshCustomData();

    //assign logged in user
    user.value = app?.currentUser;

    return true;
  };

  /**
   *
   * @returns
   */
  const logout = async () => {
    await app.currentUser?.logOut();
    //assign logged in user
    user.value = null;
    return true;
  };

  const createAccount = async ({
    email,
    password,
    first,
    last,
  }: {
    email: string;
    password: string;
    first: string;
    last: string;
  }) => {
    // Create user
    await app.emailPasswordAuth.registerUser(email, password);

    // Authenticate the user
    await app.logIn(Realm.Credentials.emailPassword(email, password));

    // save profile information
    const mongodb = app?.currentUser?.mongoClient("mongodb-atlas");
    const collection = mongodb?.db("vue-db1").collection("profile");

    const resp = await collection?.insertOne({
      userID: app?.currentUser?.id,
      first,
      last,
    });

    // Refresh a user's custom data to make sure we have the latest version
    await app?.currentUser?.refreshCustomData();

    //assign logged in user
    user.value = app?.currentUser;

    return app.currentUser;
  };

  return {
    isLoggedIn,
    user,
    // functions
    login,
    logout,
    createAccount,
  };
};
```
How to integrate storybook with npm workspace, react, and webpack
Tags: storybook, webpack, react, monorepo
Published: 2021-10-13 00:21:12

[Storybook](https://storybook.js.org) is the most popular UI component development tool for React. It helps you develop and design UI components outside your app in an isolated environment. 

This is the very basic setup to integrate our [previous react monorepo](https://dev.to/ynwd/how-to-create-react-monorepo-with-npm-workspace-webpack-and-create-react-app-2dhn) with storybook. You can find the source code of this tutorial on [monorepo-storybook-branch](https://github.com/ynwd/monorepo/tree/storybook).

## Setup Storybook
You can use [this repo](https://github.com/ynwd/monorepo) to start.
```
cd web/components/
```

Install storybook
```
npx sb init --builder webpack5 -f
```
> *You can find detail overview of storybook and webpack 5 on this page: [Storybook for Webpack 5](https://storybook.js.org/blog/storybook-for-webpack-5/)*

Run storybook
```
npm run storybook
```

You can also run storybook from the app root folder
```
npm run storybook -w @fstr/components
```

## Update webpack config
This update is used to handle css files of storybooks.
```js
const path = require("path")

module.exports = {
    mode: "production",
    entry: {
        index: { import: "./src/index.js" }
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: "babel-loader",
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
    output: {
        filename: "components.bundle.min.js",
        library: 'fstrComponents',
        libraryTarget: 'umd',
        clean: true
    },
}
```
> *You can find detail instruction to setup webpack css on [this page](https://webpack.js.org/guides/asset-management/#loading-css)*

## Use storybook component
Update index
```js
// web/components/src/index.js
import React from "react"
import { Button } from "./stories/Button.jsx"

const Header = ({ text = "" }) => {
    return (
        <h1>Shared header library {text}</h1>
    )
}

export {
    Button,
    Header
}
```

Still in `web/components` folder, build the storybook component.
```
npm run build
```

You can also build from root folder.
```
npm run build -w @fstr/components
```

Link the built components to npm workspace.
```
npm install
```

And finally you can import the storybook component from all modules
```js
// web/modules/root/src/App.js
import './App.css'
import { Header, Button } from "@fstr/components"

function App() {
  return (
    <div className="App">
      <Header text="from root" />
      <Button
        label="Button"
        onClick={() => { }}
      />
    </div>
  )
}

export default App
```

Run the root module to see the changes
```
npm start -w @fstr/root
```
Ana apresenta Karenina Arch
Tags: webdev, programming, python, beginners
Published: 2021-10-13 00:19:29

Olá cats, como vão?

Eu sou a Ana Paula, mas gosto e prefiro ser chamada de Karenina Arch, e este é meu primeiro post aqui no DEV Community.

Estou muito feliz em participar da comunidade e espero contribuir muito. Agradeço desde já a todes por compartilharem tanto conhecimento comigo! Muito obrigada!

Bom, meu intuito é fazer reviews de livros técnicos que tenho estudado, em especial, os que abordam tecnologia, computação, design e matemática. Amo essas áreas e tenho me dedicado às leituras das mesmas.

Quero compartilhar minhas impressões a respeito de obras que abordam estes temas para ajudar quem também tem interesse neste tipo de aprendizado por conta própria e também receber indicações de novos livros para que eu possa ir lendo e aprendendo cada vez mais!

Para começar, vou fazer um review do livro "Use a Cabeça! Programação". A série "Use a Cabeça!" tem sido uma das minhas obras preferidas enquanto iniciante por toda sua didática, mas assim como toda e qualquer obra está longe de ser uma unanimidade ou perfeição. Vou compartilhar os pontos que achei bons e outros nem tanto a respeito deste livro, mas claro, desde já recomendo fortemente que você crie suas próprias impressões a partir de sua leitura do livro. Não quero e não acho tão produtivo compartilhar um resumo, mas acho interessante dividir minhas impressões com a comunidade a partir de reviews.

Bom, para um primeiro post, é isso!

Mais uma vez muito obrigada e nos vemos muito e breve! Não deixem de estudar. Eu acredito e torço por você!
npmrc authentication for a private scoped organisation package
Tags: webdev, npm
Published: 2021-10-14 00:29:28

---
title: npmrc authentication for a private scoped organisation package
published: true
date: 13/10/2021
tags: #webdev #npm
canonical_url: https://darraghoriordan.com/2021/10/13/npmrc-scoped-organisation-authentication/
---

If you have to login to npm to multiple organisations it can be easier to use an `.npmrc` file that you move around rather than `npm login` command.

<!-- end excerpt -->
## The npmrc file

The .npmrc file sits in the root of a project and allows to set specific settings for that project. Npm will use the first instance of a setting it finds starting in the local repository and moving to your home folder. This allows you to have specific settings for logging in to special package repositories.

## First - do not commit the file!

Make sure you add .npmrc to your .gitignore file.

Do not check your npmrc with auth token into the source control.

## Scoped authentication using an npmrc file

Different package repositories will have different credential methods but it is usually a token of some kind that is passed through a query string parameter. e.g. for npm it is `authToken`.

Here is an example if you wanted to log in to npm for most packages but you have your `@myPrivateOrg` packages in jfrog.

```
//registry.npmjs.org/:_authToken=YOUR_NPM_TOKEN_HERE

@myPrivateOrg:registry=https://myPrivateOrg.jfrog.io/artifactory/api/npm/node-packages/
//myPrivateOrg.jfrog.io/artifactory/api/npm/node-packages/:_auth=YOUR_JFROG_TOKEN_HERE
//myPrivateOrg.jfrog.io/artifactory/api/npm/node-packages/:always-auth = true
package-lock=true
email = my.email@thisemail.com
```

Note that the tokens are usually base64 encoded. I talk about how to do this on mac here: [https://www.darraghoriordan.com/2021/02/07/set-jira-release-azure-devops-pipeline/](https://www.darraghoriordan.com/2021/02/07/set-jira-release-azure-devops-pipeline/)
Reader response: How does QA fit into DevOps?
Tags: qa, devops, testing
Published: 2021-10-27 10:31:00

---
title: Reader response: How does QA fit into DevOps?
published: true
date: 2021-10-13 00:00:00 UTC
tags: qa,devops,testing
canonical_url: https://jhall.io/archive/2021/10/13/reader-response-how-does-qa-fit-into-devops/
---

Last week [I wrote about](https://jhall.io/archive/2021/10/08/how-does-qa-fit-into-devops/) the idea of QA serving a supporting role to developers, to overcome the common tendency of an adversarial relationship between developers and QA.

Fellow reader Axel Schüssler replied to that post with his own story:

> As an agile tester, I come to DevOps from the other direction. We solve the problem of the “wall of confusion” between dev and QA by enabling dev teams to do most testing on their own. And DevOps gives teams a whole range of new possibilities to address quality risks. Exciting times.

I love this!

One thing I like so much about the agile movement is that regardless of our various starting points, as an industry we tend to converge on many of the same solutions. Axel’s example helps to underscore this!

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._