teleren/devto huggingface dataset:
Sinatra CRUD-MVC Project 2.0: What I Did This Time Around
Tags: sinatra, html, crud, flatiron
Published: 2021-02-25 01:48:43

Well, I found myself in the same spot only four months forward in time. I did not pass my Sinatra project the first time, nor the second. So, I was gratefully granted a second chance (or third chance) to prove myself. I switched into a different cohort to redo Sinatra and also I switched from full-time to part-time. It was, and still is, frustrating. It was, and still is, daunting.

These two major changes scared me. I was nervous to make the same mistakes. I was doubtful of myself and my abilities, to be blunt. So, I knew I had to look back and reconsider everything. 

During my first attempt at the Sinatra CRUD-MVC project, I was totally fixated on the notion that I had to ~appear~ to know everything. I was convinced that everything had to be perfect, and nothing less would be tolerated. As we know, and I now know, these are not feasible standards for any sort of endeavor. 

Realistically, I did not know everything and nothing was perfect. I was not comfortable with the curriculum back in October (I now know). I seemed to skate through the motions of a working Sinatra project. I relied on a lot of guesswork and quick answers. It is hard to admit when you need help or that you need more time to learn what others can learn in a month. Learning for me takes time. I became aware this time around that I learn most effectively at a slower pace and with the reiteration of the good ol' basics. 

So, I started at the beginning. What can I relearn? EVERYTHING. I combed through SQL: what is a table? what is a row? how do these things reflect in an application? I asked myself what is the functionality of ActiveRecord: wait, what even is ActiveRecord? If I had to describe a 'route' to a younger version of myself, what would I say and how would I say it? I pored over key Sinatra concepts and asked where do I personally see this in the real world? Consistently and redundantly, I tried to relearn all of Phase 2. It was difficult, but definitely worth it. 

I realize now what confidence I had the first time around is nothing in comparison to how I currently feel. I may look back in another four months and experience a whole different set of feelings. I may not. However, I do know that the "failure" of Sinatra the first time was very scary but now, I think of my second chance as both a comfort and a redemption in adjacence to the fear.
How to handle Next.js Api routes more type safely
Tags: nextjs, typescript, react, javascript
Published: 2021-02-25 01:48:29

---
title: How to handle Next.js Api routes more type safely
published: true
description: 
tags: nextjs,typescript,react, javascript
//cover_image: https://direct_url_to_image.jpg
---

# Create a utility method.

```typescript
// handleMethods.ts
type ApiResponse<Data = {}, Error = { message: string }> =
  | { result: true; data: Data }
  | { result: false; data: Error }

export const handleMethods = <Q extends Record<string, string> = {}>() => {
  const handlers: { [key: string]: NextApiHandler | undefined } = {}
  const methodHandler = {
    get: <T, E = string>(
      handler: (
        req: NextApiRequest & { query: Q },
        res: NextApiResponse<ApiResponse<T, E>>,
      ) => void | Promise<void>,
    ) => {
      handlers['GET'] = handler
      return methodHandler
    },
    post: <T, E = string>(
      handler: (
        req: NextApiRequest & { query: Q },
        res: NextApiResponse<ApiResponse<T, E>>,
      ) => void | Promise<void>,
    ) => {
      handlers['POST'] = handler
      return methodHandler
    },
    put: <T, E = string>(
      handler: (
        req: NextApiRequest & { query: Q },
        res: NextApiResponse<ApiResponse<T, E>>,
      ) => void | Promise<void>,
    ) => {
      handlers['PUT'] = handler
      return methodHandler
    },
    delete: <T, E = string>(
      handler: (
        req: NextApiRequest & { query: Q },
        res: NextApiResponse<ApiResponse<T, E>>,
      ) => void | Promise<void>,
    ) => {
      handlers['DELETE'] = handler
      return methodHandler
    },
    prepare: (): NextApiHandler<ApiResponse> => (req, res) => {
      if (handlers[req.method]) {
        return handlers[req.method](req, res)
      } else {
        return res.status(404).json({ result: false, data: { message: 'not found' } })
      }
    },
  }
  return methodHandler
}
```

# Usage

```typescript
// pages/api/users/index.ts

type User = {...}

export default handleMethods()
  .get<Array<User>>(async (req, res) => {
      try {
         const result = await findUsers()
         return res.json({ result: true, data: result })
      } catch(e) {
         return res.status(400).json({ result: false, data: e })
      }
  })
  .post<User>(async (req, res) => {
      try {
         const result = await createUser()
         return res.json({ result: true, data: result })
      } catch(e) {
         return res.status(400).json({ result: false, data: e })
      }
  })
  .prepare()

```
```typescript
// pages/api/users/[id].ts
export default handleMethods({ id: string })
  .get<Array<User>>(async (req, res) => {
      try {
         // you can access query.id type safely.
         const result = await findUsers({ id: req.query.id })
         return res.json({ result: true, data: result })
      } catch(e) {
         return res.status(400).json({ result: false, data: e })
      }
  })
  .prepare()
```
[BLOG] 7 dicas para dominar o PHP
Tags: php, solid
Published: 2021-02-25 01:40:22

Neste artigo eu vou fazer um compilado de regras que irão ajudar você a ser um dev PHP melhor, eu gostaria de deixar claro que em alguns pontos eu vou deixar alguns “ganchos” para você pesquisar sobre os assuntos, já que descrever TUDO vai ficar bem inviável em um único artigo (ou livro).

[Continua...](https://blog.erikfigueiredo.com.br/7-dicas-para-dominar-o-php/)
Exporting from Template 
Tags: template, java, python
Published: 2021-02-25 01:30:02

Ok, I have to export and keep track of some information in a .tpl file and produce a script. I have no clue how to do so primarily because I don’t know how to extract that information from the 2nd line of the tpl. Any help would be appreciated 

Ps. 
The first two lines by the way are purely just meta data line three holds the opening tag for the document
Caching dependencies to speed up workflows in GitHub Actions
Tags: github, devops, node
Published: 2021-02-25 01:29:43

To make your workflows faster and more efficient, you can create and use caches for dependencies and other commonly reused files.

## About caching workflow dependencies
GitHub Workflow runs often reuse the same downloaded dependencies from one run to another. For example, package and dependency management tools such as npm and Yarn keep a local cache of downloaded dependencies.

Jobs on GitHub-hosted runners start in a clean virtual environment and must download dependencies each time, causing increased network utilization, longer runtime, and increased cost. GitHub can cache dependencies you frequently use in workflows to help speed up the time it takes to recreate these files.

To cache dependencies for a job, you'll need to use GitHub's cache action. The action retrieves a cache identified by a unique key. For more information, see actions/cache.

{% github https://github.com/actions/cache no-readme %}

## Example using the cache action
This example creates a new cache when the packages in the package-lock.json file change or when the runner's operating system changes. The cache key uses contexts and expressions to generate a key that includes the runner's operating system and a SHA-256 hash of the package-lock.json file.

```yml
name: Caching with npm

on: push

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Cache node modules
      uses: actions/cache@v2
      env:
        cache-name: cache-node-modules
      with:
        # npm cache files are stored in `~/.npm` on Linux/macOS
        path: ~/.npm
        key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
        restore-keys: |
          ${{ runner.os }}-build-${{ env.cache-name }}-
          ${{ runner.os }}-build-
          ${{ runner.os }}-

    - name: Install Dependencies
      run: npm install

    - name: Build
      run: npm build

    - name: Test
      run: npm test
```

To learn more about cache hits and the cache eviction policy, check out the GitHub Documentation.

_This is part of my 28 days of Actions series. To get notified of more GitHub Action tips, follow the GitHub organization right here on Dev. Learn how to build action with Node.js_

{% link https://dev.to/github/environment-scoped-secrets-for-github-action-workflows-337a %}
Tentang Toko di Internet
Published: 2021-02-25 00:45:22

Dengan masuknya teknologi modern ke dalam kehidupan kita, lebih banyak layanan menjadi lebih mudah. Gadget, perkakas, dan moda transportasi baru membuat fungsi penting manusia seperti komunikasi dan transportasi menjadi mudah.

Dari perkembangan ini, tidak ada yang memberi dampak sebesar Internet. Komunikasi, akses ke layanan pemerintah, dan bahkan transaksi bisnis dimungkinkan melalui penggunaannya. Dan dengan munculnya pedagang internet dan pemroses pembayaran online, fungsi paling dasar dari etos konsumeris (alias belanja) hanya dengan mengklik.

Apa pedagang internet dan pemroses pembayaran online? Pedagang internet hanyalah pebisnis yang menjual produk atau jasanya melalui internet. Situs pedagang internet berfungsi sebagai toko virtual di mana pembeli online dapat menelusuri halaman produk atau katalog. Situs-situs ini biasanya menampilkan harga setiap layanan atau produk, promo penjualan, keranjang belanja virtual, dan yang terpenting, beberapa skema pembayaran.

Skema pembayaran ini adalah mode pemroses pembayaran online. Pemroses pembayaran online adalah institusi yang menawarkan perusahaan atau bisnis sistem untuk menerima dan memproses kartu debit dan kredit tanpa kerumitan berurusan dengan bank atau penerbit yang berbeda secara langsung. Mereka pada dasarnya bekerja sebagai perantara antara pemegang kartu dan Pedagang. 

Pedagang meneruskan detail kartu kredit ke situs web pemrosesan, atau laman pedagang dapat langsung membuka situs pemroses. Prosesor kemudian memvalidasi detail kartu dan akun. Setelah validasi, detail kartu dikirim kembali melalui halaman `Pedagang bersih 'untuk konfirmasi atau penolakan. Jika sudah dikonfirmasi maka pembelian sudah selesai dan pembelanja tinggal menunggu pengirimannya. https://www.itsp.my.id/
Migrating from eslint-loader to eslint-webpack-plugin
Tags: javascript, webpack, eslint, productivity
Published: 2021-02-25 00:26:34

---
title: Migrating from eslint-loader to eslint-webpack-plugin
published: true
description: A brief migration guide.
tags: javascript, webpack, eslint, productivity
canonical_url: https://laurieontech.com/posts/eslint-webpack-plugin/
---

[`eslint-loader`](https://github.com/webpack-contrib/eslint-loader) is deprecated. The replacement, is [`eslint-webpack-plugin`](https://github.com/webpack-contrib/eslint-webpack-plugin).

The README gives helpful information, but in looking for a full post on migration I came up empty. So this is that post for anyone else!

## Existing Example
The README example is great for switching from rule to plugin syntax. So this,

```js
const config = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        options: {
          // eslint options (if necessary)
        },
      },
    ],
  },
}
```

Becomes this.

```js
import ESLintPlugin from 'eslint-webpack-plugin')

const config = {
  plugins: [new ESLintPlugin(options)],
}
```

But what happens with all those additional key-value pairs included in the original ruleset? They can't just be dropped, it changes the functionality.

## Plugin Options
Depending on what configuration you were passing, you may have to make some slight tweaks. For example, I had the following.

```js
const config = {
  module: {
    rules: [
      {
      enforce: `pre`,
      test: /\.jsx?$/,
      exclude: (modulePath: string): boolean =>
        modulePath.includes(VIRTUAL_MODULES_BASE_PATH) ||
        vendorRegex.test(modulePath),
      loader: 'eslint-loader',
      },
    ],
  },
}
```

`test` takes a glob for files to run the loader against. There are a few options in `eslint-webpack-plugin` that provide the same functionality, I opted for `extensions`.

`exclude` still works but because plugins run against the entire chunk, whereas loaders run against single files, it's a bit different. Mainly, it takes an array of strings rather than a function. Note that it also defaults to `/node_modules/`.

Finally, there is `enforce`. I didn't find an options level equivalent for this. As it turns out, I was able to drop it in my implementation. However, I believe you can use a hook to execute the plugin at a specific point in the build process.

So my migrated config became this.

```js
const options = {
    extensions: [`js`, `jsx`],
    exclude: [
      `/node_modules/`,
      `/bower_components/`,
       VIRTUAL_MODULES_BASE_PATH,
    ],
    ...eslintOptions, // these are the options we'd previously passed in
}

const config = {
   return new ESLintPlugin(options)
}
```

## And that should be it
I had to do a bit more to complete the migration in the existing codebase. If you'd like to see the code in the wild you can check out [the PR](https://github.com/gatsbyjs/gatsby/pull/29736). But hopefully, this helps someone else!
Understanding Time Series and ARIMA
Tags: datascience, machinelearning, timeseries
Published: 2021-02-25 00:00:54

I wrote a long and in-depth blog post explaining time series basics and good old classic ARIMA model! 

Enjoy and have a great day ;)


### [Understanding Time Series and ARIMA](https://jithendrabsy.hashnode.dev/understanding-time-series-and-arima)
Day 25: Calculator
Tags: 100daysofcode, python
Published: 2021-02-25 00:00:24

A simple calculator that runs in terminal which can add, subtract, multiply and divide using functions

```python
# This function adds two numbers 
def add(x, y):
   return x + y

# This function subtracts two numbers 
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user 
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")
```
How to create environment variables only to be used in the development version of Nextjs?
Tags: nextjs
Published: 2021-02-25 00:00:00

---
  title: How to create environment variables only to be used in the development version of Nextjs?
  published: true
  tags: Nextjs
  date: Thu Feb 25 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/create-environment-variables-only-for-development-nextjs
  cover_image: https://melvingeorge.me/_next/static/images/main-09fe52b0608810fae6006ab02f4d9326.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/create-environment-variables-only-for-development-nextjs)
  
To create environment variables that should be used only in the development version of your Nextjs project, you can make a file called `.env.development` at the root of the Nextjs project folder.

This file will be used (along with the `.env` if you have it defined) to take environment variables in the development version or when using the `next dev` command in the terminal.

For example, let's say you have an environment variable called `SERVER_ID=12345` which you need to use only in the development version of your Next.js project, so we can define this environment variable in the `.env.development` file like this,

**.env.development file**

```js
SERVER_ID = 12345;
```

- Useful in decoupling information from `production` and `development` versions
- Check out [How to create and use environment variables in Nextjs?
  ](https://melvingeorge.me/blog/create-and-use-environment-variables-in-nextjs) to get a detailed explanation on creating and using environment variables in general in Nextjs.

### Feel free to share if you found this useful 😃.

---
Run Multiple Make Targets Concurrently
Tags: make, linux, unix
Published: 2021-05-08 15:40:33

---
title: Run Multiple Make Targets Concurrently
published: true
date: 2021-02-25 00:00:00 UTC
tags: make, linux, unix
canonical_url: https://tech.serhatteker.com/post/2021-02/run-multiple-make-targets-concurrently/
---

[make] is a widely used and powerful tool for running common tasks in a project.

I often look at the `Makefile` of a project in order to see how a project perform regular tasks such as running tests, compiling and starting db, etc.


## Use Case 1

I want to run 2 local servers at the same time. I can run them on separate terminal windows but I don't want to do that. I'm a lazy developer and want to use *one line* solution.

For instance I want to run a `python` backend server and `javascript` front end server for `live reload` — if there is any change in static assets like `js`, `css`, `scss` etc..


```make
# Makefile

django-server: ## Run the Django server
  python manage.py runserver 8000

npm-server: ## Run npm server to live reload
	npm run dev
```

You can run them concurrently like below:

```bash
$ make -j 2 npm-server django-server
```

Or you can use a `target` for it as well:

```make
# Makefile

servers:
	make -j 2 npm-server django-server

django-server: ## Run the Django server
  python manage.py runserver 8000

npm-server: ## Run npm server to live reload
	npm run dev
```

Then run `make servers`.

## Use Case 2

I want to run a local server and open a browser related to it. I don't want to manually click my browser and type `localhost:$PORT`.

Solution:

```make
# Makefile

local-dev: django-server browser

django-server: ## Run the Django server
  python manage.py runserver 8000

browser:
    google-chrome --new-window http://localhost:8000
    # or if you use firefox
    # firefox --new-window localhost:8000
```

Then type `make local-dev`.


All done.




[make]: https://www.gnu.org/software/make/manual/html_node/index.html#Top
Properties of good unit tests
Tags: testing
Published: 2021-02-27 11:15:23

---
title: Properties of good unit tests
published: true
date: 2021-02-25 00:00:00 UTC
tags: testing
canonical_url: https://jhall.io/archive/2021/02/25/properties-of-good-unit-tests/
---

I’ve said calculating code coverage is overrated. But I’m also a strong believer in good testing. So what makes for _good_ tests?

This is a nonexhaustive list of some charactaristics I look for when writing tests, or reviewing tests others have written. What would you add?

1. **Independent.** A test should work by itself, or when executed with others. Tests that depend on state configured by previous tests are broken.
2. **Deterministic.** Obviously a test that has a non-deterministic result is not a good test.
3. **Reliable.** A test that randomly fails is potentially worse than no test at all.
4. **Easy to read.** I place a high value on readable code. Tests are code, and thus should also be readable.
5. **Isolated.** In a perfect world, each regression will cause one, and only one test to fail. This isn’t always practical, but it’s a good goal to aim for.
6. **Meaningful.** This one is a bit subjective, but as an example: Testing a simple getter or setter may not be meaningful. Testing the standard library probably isn’t meaningful.
A Cross-platform Azure Service Bus explorer
Tags: azure, devops, microservices, tools
Published: 2021-02-24 22:48:35

If you have worked with Azure Service Bus, you know that having an explorer is essential for developers. An explorer is a tool that helps you to view messages in queues and manage them so that you can develop and test distributed systems.

[PurpleExplorer](https://github.com/telstrapurple/PurpleExplorer) is a new open-source tool that runs on any platform (Windows, macOS, Linux) and helps developers to:
* Connect to Azure Service Bus
* View topics and subscriptions
* View queues
* View active and dead-letter messages
* View message body and its details
* Send a new message
* Save messages to send them quickly
* Delete a message
* Purge active or dead-letter messages
* Re-submit a message from dead-letter
* Dead-letter a message

It also saves the messages so that engineers and testers can send different messages multiple times easily. It is open-source (MIT license) available at:

https://github.com/telstrapurple/PurpleExplorer

Note that it is in Beta version now.
Hope it is helpful to you all :)
Day 316 : Real Ones
Tags: hiphop, code, coding, lifelongdev
Published: 2021-02-24 22:35:57

_liner notes_:
- Professional : Pretty good day. Finished up a demo application. Talk to speak with a coworker. They live in Texas so I got to hear how the whole disaster during the snowstorm played out. Spent the rest of the day doing some research and working on a Web Component. Speaking of Web Components, my video from being on the Auth0's Avocado Labs show is up on YouTube. Thanks to them for having me.

{% youtube LwInC3gM8z8 %}

- Personal : Last night, I went through a bunch of tracks for the radio show this week. Did some planning and coding on my side project. I was working out what sites would cover what functionalities. I'm thinking I'm going to split up the project into smaller more focused sections so if I ever need to work on one part, the others won't be disturbed. We'll see how this goes. This is the largest project I've done. Also watched an episode of "Attack on Titan". So good!

![Mid sections of trees, some looking purple, in Redwood State Park, CA, USA, with one that has a branch with pink flowers and green leaves](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxewkzagq5a8sj959oi2.jpg)

Going to basically see if I can replicate last night. Worked out that I may need another mini-site to handle something specific. May start working on that since it will rely on the admin section I've been working. May be good to have both so I can test things out. I've only been really using fake data so it will be good to use some real ones. We'll see.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube BQYEbdlb9kg %}