teleren/devto huggingface dataset:
How to migrate Rails UJS to Hotwire (Turbo)
Tags: rails, hotwire, tailwindcss, tutorial
Published: 2021-12-11 09:10:53


See [Hotwire handbook](https://turbo.hotwired.dev/handbook/drive#performing-visits-with-a-different-method)

1. [Update hotwired/turbo-rails](#1-update-hotwiredturborails)
2. [Remove rails/ujs](#2-remove-railsujs)
3. [Replace link_to delete](#3-replace-linkto-delete)
4. [Replace link_to data confirm](#4-replace-linkto-data-confirm)
5. [Replace button data disable with](#5-replace-button-data-disable-with)
6. [Set status response in controller](#6-set-status-response-in-controller)

---

## 1. Update hotwired/turbo-rails

In __package.json__, update `@hotwired/turbo-rails` package to 7.1.0 (or greater)
```
 "@hotwired/turbo-rails": "^7.1.0"
```

---

## 2. Remove rails/ujs 

- From the package.json file
```bash
yarn remove @rails/ujs
```

- From the application.js entry point
```js
require("@rails/ujs").start() // remove this line
```

---

## 3. Replace link_to delete
`method: :delete`
becomes
`data: {turbo_method: :delete}`

```erb
<%# Old %>
<% link_to "Destroy", task_path(@task), method: :delete %>

<%# New %>
<% link_to "Destroy", task_path(@task), data: {turbo_method: :delete} %>
```

---

## 4. Replace link_to data confirm

`data: {confirm: 'Are you sure?'}`
becomes
`data: {turbo_confirm: 'Are you sure?'}`

```erb
<%# Old %>
<% link_to "Destroy", task_path(@task), method: :delete, data: {confirm: 'Are you sure?'} %>

<%# New %>
<% link_to "Destroy", task_path(@task), data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
```

---

## 5. Replace button data disable with

In Rails UJS, a form's submit button can be disabled and its text replaced by adding the data disable_with attribute.

```erb
<%= f.button "Search", data: { disable_with: "Searching..."} %>
```

With Turbo, you can set the text content based on the parent's button disabled status. [Source](https://github.com/hotwired/turbo/pull/386)

```css
button             .show-when-disabled { display: none; }
button[disabled]   .show-when-disabled { display: initial; }

button             .show-when-enabled { display: initial; }
button[disabled    .show-when-enabled { display: none; }
```

```html
<button>
  <span class="show-when-enabled">Submit</span>
  <span class="show-when-disabled">Submitting...</span>
</button>
```

Or if you use Tailwind, you can leverage Tailwind's [group](https://tailwindcss.com/docs/hover-focus-and-other-states#styling-based-on-parent-state) and [disabled](https://tailwindcss.com/docs/hover-focus-and-other-states#disabled) status to create a similar effect.

```erb
<%= f.button class: "group" do %>
   <span class="group-disabled:hidden">Search</span>
   <span class="hidden group-disabled:block group-disabled:cursor-wait">Searching...</span>
<% end %>
```


---

## 6. Set status response in controller

Respond with a [303 status code](http://www.railsstatuscodes.com/see_other.html)

```rb
class TasksController
 ...

  def destroy
    @task = Task.find(params[:id])
    @task.destroy
    redirect_to tasks_path, info: "Task deleted", status: :see_other
  end 
end
```
The journey from Platform Nine and Three-Quarters
Tags: codepen, html, webdev, design
Published: 2021-12-11 09:03:38


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

For the 20 years of harry potter i decided to create a pen which represent the Platform Nine and Three-Quarters. 

What do you think about my work full html and css ?

[](https://codepen.io/nicolas-jeanne/pen/KKXgrad)
Measuring Employee Value The Wrong Way
Tags: webdev, performance, management
Published: 2021-12-11 07:53:34

How should the value of an employee be measured? That's honestly a really tough question. I do know of some ways that do not work. I am a software engineer team lead and here are some managing styles that don't work.

## Butt In Seat
Not that long ago an employees value was measured by seeing them in person at their desk working away. Back when we all worked in the office I had a Sr. manager (two above me) who would walk around the office and pop his head into your room to have "small talk" about nothing important. If he did not see you in your room you would get a message from your manager to talk about your productivity. This kills trust.

When work went 100% remote the same thing happened with Slack. When your activity dot went from green to gray you could bet that you would get a message from this same manger about something random. If you didn't respond in 5 minutes you could expect a message from your direct manager about productivity.

## First Responders
When an issue arises, being able to respond quickly is a good thing but as soon as its a measurement of ones value is when it becomes dangerous. Many times when an issue comes up people will respond blindly to it firing from the hip. This can cause damage and lead people down wrong paths. Taking a moment to think through the issue and do research before throwing out answers is much more beneficial. But guess what, you are late to the party and the "First Responder" credit has already been claimed. GG.

## Number of Tasks Completed
In software development we track our work with tickets. We take a ticket that has acceptance criteria, work on it and then deliver it. Measuring the number of tickets an employee completes is good way of seeing their value but it does not paint the full story.

I had a co worker who was a high ticket completer. He would crunch out close to 25% more tickets than the next highest contributor. Management loved this employee. I mean why shouldn't they? He is getting shiz done! Well, taking a closer work at what was actually happening painted things very differently. Over half of the tickets he was completing was fixing bugs from previous work he had completed. Most of the production outages were due to a change he had made. What's interesting is that he was also the first one to respond to these issue making him look like a hero. Want to know how to be the best fire fighter? Be the first to the scene by creating the fire yourself.

## Talk The Most In Meetings
I had a Coworker who quickly moved up in the ranks because he had a loud voice in a meeting. He would talk over anyone and interrupt who ever was talking if he had something on his mind. Unfortunately management saw this as a sign of strength and good leadership. What it did is caused others to not speak their mind. Who likes getting trampled? Especially in front of their peers!

Having a strong opinion can be a good thing but it needs to be shared with respect for others. 

Thanks for taking the time to read this article. I hope to do a follow up article on things that I have seen that do work.
Using a Kubernetes Service Mesh Worth It?
Published: 2021-12-11 08:37:25

"A service mesh is a dedicated infrastructure layer that decouples some of the critical operational tasks of a distributed application from its business logic. Large-scale, Kubernetes-hosted microservice applications are natural candidates for service meshes due to their complex requirements of inter-services communication (e.g., retries, timeouts, traffic splitting), observability (e.g., metrics, [logs](https://www.containiq.com/post/kubernetes-logging), traces), and [security features](https://www.containiq.com/post/kubernetes-security-best-practices) (e.g., authentication, authorization, encryption). Service meshes can offload many operational concerns of the [Kubernetes cluster](https://www.containiq.com/post/kubernetes-cluster), leaving the developers to focus on business logic."

Is using a service mesh in Kubernetes really worth the trouble? Not sure? Then check [this](https://www.containiq.com/post/kubernetes-service-mesh) out.
Web Developer, why become one?
Tags: webdev, beginners, career, motivation
Published: 2021-12-11 08:19:34

Web development, you must have heard of this word before and specially if you're from some technical background.
But what does this mean?
The websites you see are made by Web-developers of course you must have seen, everyone knows about them, they are like pages that show some information and more.
Well in 2021 almost everyone is familiar with programming and many are even learning some languages, but no matter how good programmer you are, you can't ignore web. Now by this I don't mean that web-developers are not programmers but there is a thin grey line between both in my opinion. What people know about both of them is that they earn a considerable amount which satisfactory to hear but the efforts behind that comfort is HUGE!
Web-developers are in every company you see today even in startups because everyone needs that page for themselves. So now you might think how can one call himself a web-developer is there some sort of degree that one needs to do?
Well no, there are many tutorials and guides out there on the internet and many communities that beginner friendly that love to help beginners and guide them through their journey, please note that I'm not referring to some paid courses or any sort of promotion, it's just for guidance.
Hope this was inspiring.
Routing in React | React Router V6
Tags: react, javascript, routing, programming
Published: 2021-12-11 07:44:55

In this video, I have explained how to implement <b>Routing in React Application</b>, how to pass <b>params</b> through routing, how to redirect from one page to another page and more with step by step explanation.

<b>Routing</b> is the process using which user can navigate from one page to another page with in an application.

Timeline :
00:20 Install react-router-dom 
00:55 Implement Routing
03:08 Define Routes for each Page
06:15 Create Navigation Bar
08:28 Redirect from one page another on Button Click
10:47 Pass Params through Routing


{%youtube PwE5renh7wo%}
Freaky Like Me | Sparklingman digital poster 020
Tags: codepen, sparklingman, poster
Published: 2021-12-11 07:02:56

---
title: Freaky Like Me | Sparklingman digital poster 020
published: true
tags: codepen, sparklingman, poster
---



{% codepen https://codepen.io/sparklingman/pen/XWerVGy %}
Advent of code Day 11
Tags: adventofcode, adventofcode2021, programming, 42
Published: 2021-12-11 07:02:26

This was a nice puzzle, I appreciate the short input, so that I can simply cut-pasting into a multiline string.
Thanks to this experience I'm getting more and more feedback on what I should add to AdamsTowel. See after the code for details:
```
reuse [L42.is/AdamsTowel]
Split={class method S.List (S that)=\()(
  for c in that.replace(S"" with=S",").split(S",")\add(c)
  )}
Matrix=Collection.matrix(I.List,row=10I,col=10I)
Coords = Collection.list(Matrix.Coord)
Near={class method Coords (Matrix.Coord that) = Coords()(
  for r in Range(I"-1" to=2I)
    for c in Range(I"-1" to=2I)
      if r!=0I || c!=0I (
        new = that.with(row=\row+r).with(col=\col+c)
        catch error Any _ void
        \add(new)
        )
  )}
Step={
  class method I (mut Matrix that)=(
    for var v in that ( v+=1I )
    \flashes(m=that)
    )
  class method I flashes(mut Matrix m) = {
    flashes=Match.Count()(
      for c in m.coords() var v in m if v>9I (
        \add(\.true())
        v:=0I
        for n in Near(c) (
          vi = m.val(n) 
          if vi!=0I m.set(n val=vi+1I)
          )
        ))
    if flashes==0I return 0I
    return flashes+\flashes(m=m)
    }
  }
Main11=(
  input=S"""
    |3113284886
    |2851876144
    |2774664484
    |6715112578
    |7146272153
    |6256656367
    |3148666245
    |3857446528
    |7322422833
    |8152175168
  """
  m1=Matrix(\()(for l in input.split(S.nl())
    for s in Split(l) \add(I(string=s))))
  var tot = 0I
  for i in Range(100I) ( tot+=Step(m1) )
  Debug(tot)//1705  
  m2=Matrix(\()(for l in input.split(S.nl())
    for s in Split(l) \add(I(string=s))))
  for i in Range.unbounded() if Step(m2)==100I (
    Debug(i+1I)//of course the puzzle wants it
    Break()//starting from one, so 265 not 264 :-/
    )
  )
```

* Splitting on all characters seams to be very common, so I should add it to my spliterators.
for example we could have
```
m1=Matrix(\()(for l in input.split(S.nl())
    for s in l.split() \add(I(string=s))))
```
* Near elements of matrixes are quite a common feature too,
ideally I would like to allow either:
```
for (coord,val) in myCoord.near8(map) ( .. ) //or near4()
```
or 
```
for coord in myCoord.near8() val in map.near8(myCoord) ( .. )
```
What would be better? the first one requires boxing objects, the second requires two iterations and thus double checks for what coordinates actually are in the range.
  
* Should I change Match.Count to offer \addOne,\addIf(Bool that) \add(I that) and may be other operations like \times and \divide ? 
If so, that would remove the need to make an Accumulator for I... but what about Num and Math.Long? or even Math.Double??
That is, do we want to write
```
res=Double.Count()( for v in list (\add(v) \times(2\) )
```
or 
```
res=Match.CountDouble()( for v in list (\add(v) \times(2\) )
```
Planning for last release
Published: 2021-12-11 06:05:08

#overview
In this release I will choose to add a new feature to a current project. The first thing came up in my mind was finding an issue that would require me to create a new component or a page. I went to Github and spent nearly 1 hour to find one. At the moment, I have chose 2 issues to work on. They they were both interesting

#Telescope
[Issue-2550](https://github.com/Seneca-CDOT/telescope/issues/2550)
The prop named <code>justify</code> was deprecated, so I what I would do was replacing all of them with <code>justifyContent</code> instead.
I already created a pull request to Telescope so I had everything set up for the project. This will not really complicated for me, but who knows what is going to happen because there might be bugs or at the time I am dealing with the issue, there may be someone's PR gets merged and there will be conflict.

#Code Peak
[Issue-13](https://github.com/VishalIITP/CodepeakSuperDuper/issues/13)
This one was more interesting since I would be adding a new design for the website, the leaderboard. Because the website had a lot of pages that were already designed, finding and making a new appearance for the leaderboard page will be challenging. Everything needs to match together. What I would do is going to the internet to find some template to get inspired. And also this is the first time I have seen this project so it might take me sometimes to get used to the code and have everything set up.

# Last thought
I am ready for the challenge. It seems challenging and will take time but I am excited to get into work.
Getting Started with TypeScript<T> in React

Published: 2021-12-11 06:02:35


**First :** Open the terminal and run this command

```yaml
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript

```

##### You will be get a up and running react app with typescript configurations with this template.

Now you can make changes to your App.tsx file.

> Note : in your tsconfig.json file strict mode is set true, while it is a good practice to have it true you might get a lot errors and feel more restrict if not used proper ways around typescripting your app.

```tsx
const App: React.FC = () => {
  // App body
};
```

Note : You must have installed a dependancy @types/node & @types/react. Check your package.json file

#### Defining a state with type

```js
const [task, setTask] = useState < string > '';
// <string | null> throws error that value cannot be null;
const [todoList, setTodoList] = useState < Array < string >> [];
// null does not work Array<string |null> it shows error that string[] cannot be null
```

Input and onchange handler

```js
<input type="text" value={task} onChange={handleChange} />
```

```tsx
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  // you have to specify what event type
  setTask(event.target.value);
};
```

So apparently typescript needs the event type also which is provided by our browser (Js) events and React extends those events & puts them in the `React.syntheticEvent` variable. Typescript wants the event provided by React.

Lets create a useReducer component with typescript and react.
1.Defining our action types & initial state

```tsx
import { useReducer } from 'react';

const initialState = {
  counter: 100,
};

type ACTIONTYPES =
  | { type: 'increment'; payload: number }
  | { type: 'decrement'; payload: number };
```

2.Count reducer

```tsx
function counterReducer(state: typeof initialState, action: ACTIONTYPES) {
  switch (action.type) {
    case 'increment':
      return {
        ...state,
        counter: state.counter + action.payload,
      };
    case 'decrement':
      return {
        ...state,
        counter: state.counter - action.payload,
      };
    default:
      throw new Error('Bad action');
  }
}
```

3. UseReducer component

```tsx
export default function UseReducerComponent() {
  const [state, dispatch] = useReducer(counterReducer, initialState);
  return (
    <div>
      <div>{state.counter}</div>
      <div>
        <button onClick={() => dispatch({ type: 'increment', payload: 56 })}>
          Increment
        </button>
        <button onClick={() => dispatch({ type: 'decrement', payload: 26 })}>
          decrement
        </button>
      </div>
    </div>
  );
}
```

And that is how you create a simple reusable type based component in react.
`<> By Satish Rajnale </>`
Mis Primeras Paginas Web
Tags: html, css
Published: 2021-12-11 05:56:24

Termine esta pagina web en 3 dias no le dedicaba mucho tiempo
Pero me gusto como quedo!

Seguire haciendole unas modificaciones en un futuro...

Mi primo me presto una cuenta en la cual estoy aprendiendo 
De un curso de "desarrollo web"
https://twitter.com/codigoconjuan  Me gusto bastante el contenido!

Pueden ver como quedo mi pagina aqui: https://mylittleviruz.netlify.app/


Seguire subiendo aqui mas paginas ultima modificacion
10/12/2021   Hora 11:57 deberia estar durmiendo xD

12/12/2021 Acabo de terminar otra pagina 
La agregara a la lista
https://frontendstoremylittleviruz.netlify.app/

Bueno aprendi de grid esta chilero :)
Build the deployment system around GitHub deployment API
Tags: github, devops, deployment, opensource
Published: 2021-12-11 05:55:55

 I've been working as a DevOps engineer for the last three years and built the deployment system around GitHub deployment API. In this article, I'll explain the deployment API for those of you who want to build the deployment system.

## GitHub Deployment API

GitHub provides the [deployment API](https://docs.github.com/en/rest/reference/repos#deployments) **to trigger deploying a specific ref (branch, SHA, tag) and dispatches the deployment event**. The workflow seems relatively straightforward:

* Request to deploy a specific ref with a payload, and GitHub dispatches the deployment event.
* A system such as GitHub Action or Jenkins listens for the event and runs the actual deployment.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tcpxw5p5cp5vjdtaru6.png)

If you want to deploy the specific branch to the `dev` environment, you can do it by the API call below. Then GitHub dispatches the deployment event to your tools. The [deployment event](https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#deployment) has information that your tools can deploy, such as the commit SHA, environment, and payload. 

```shell
curl --location \
--request POST 'https://api.github.com/repos/{OWNER}/{REPO}/deployments' \
--header 'Authorization: Bearer {TOKEN}' \
--header 'Content-Type: application/json' \
--data-raw '{
    "ref": "{BRANCH}",
    "environment": "dev"
}'
```

 For details, the deployment API provides various parameters to verify a deployment.

* `ref` parameter specifies branch, tag, or SHA. Many teams often deploy branches and verify them before merging a pull request.
* `environment` parameter allows specifying a runtime environment. Teams often have multiple environments for verifying, such as `production` or `qa`.
* `auto_merge` parameter is used to ensure that the requested ref is not behind the repository's main branch. The default value is `true`.
* `required_contexts` parameter allows you to specify a subset of commit status that must be `success`. By default, every status must be in a `success` state.

## What is Gitploy?

 GitHub provides a beautiful deployment API. But it is not easy to build a new deployment system around the deployment API, especially for a small team (or organization) it doesn't have enough resources to build.  If you find the tooling to fill these gaps, [Gitploy](https://github.com/gitploy-io/gitploy) can be one of the options. Gitploy provides a straightforward UI and great features for deployment such as rollback, review, lock.

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

*Thanks for reading, and leave me comments on what do you think!*
Progress Report 
Tags: javascript, webdev, stream
Published: 2021-12-11 05:52:02


## Progress
Until now, my first [PR](https://github.com/Seneca-CDOT/telescope/pull/2520) for adding route `\feeds\invalid` to Posts service merged, and I also sent another [PR](https://github.com/Seneca-CDOT/telescope/pull/2575) for the issue [#2413](https://github.com/Seneca-CDOT/telescope/issues/2413). So everything is going well, and I have not had any significant challenges working on these issues.

## Finding
The hardest part for implementing the route `\feeds\delayed` to Posts service is testing my code. When microservices finished downloading feeds and processing them, I checked the Redis server to find the delayed one. And I found nothing. After asking a question on Telescope's Slack channel, I got an answer from prof. David that this case is not usual. The reason is a feed is marked delayed only when the processor receives an `HTTP 429` response ("the user has sent too many requests in a given amount of time ("rate limiting")"). This issue made it hard to test my new functions against the real-time database.
The workaround suggested by prof. David is implementing an integration test to create delayed feeds on the fly. Surprisingly, those feeds did not have the time to live when I used `ttl` command. I found that the `setDelayedFeeds()` function did not set the expire time for the key. 
```javascript
// old code
setDelayedFeed: (id, seconds) => redis.set(createDelayedFeedKey(id), seconds, 1),
// new code
setDelayedFeed: (id, seconds) => redis.set(createDelayedFeedKey(id), seconds, 'EX', seconds),
```

## Take-away
The biggest take-away for me this time is learning about Redis commands and [Readable stream](https://nodejs.org/api/stream.html) in NodeJs. 
Streams is one of the core concepts in NodeJs, and it is often used when we need to work with a large amount of data.
When calling the `scanStream()` method on a Redis client, I actually created an object of readable stream.
> Scanstream : Convenient class to convert the process of scaning keys to a readable stream

My code: 
```javascript
const getFeedKeysUsingScanStream = (matchPattern) => {
  const keys = new Set(); 
  const stream = redis.scanStream({
    match: matchPattern,
  }); //create a readable stream object 
  return new Promise((resolve, reject) => {
    stream.on('data', (data = []) => {
      data.forEach((k) => keys.add(k));
    });
    stream.on('error', (err) => {
      logger.error({ err }, 'Error while scanning redis keys');
      reject(new Error('Error while scanning redis keys'));
    });
    stream.on('end', () => {
      resolve([...keys]);
    });
```
A stream object has many events: 'closed', 'data', 'end', 'error', etc. Because the stream processes data piece by piece, we need to wrap it inside a Promise and only *resolve* when there is no more data to consume _ **the end event**.

In the end, I was able to make the route work, and I am happy with the progress.