teleren/devto huggingface dataset:
Do you need global state?
Tags: react, javascript
Published: 2022-09-08 14:15:11

It's no secret that global state is an absolute nightmare - and not just in React. In this post I'm going to show you how to use the Context API and possibly save you the headache of setting up Redux.

## The Context API

React's Context API is often overlooked by newer developers because it's not talked about as it probably should be. In short, it provides utilities for nested access to a value.

Have you ever had some state and passed it down through several layers of components? This is called **Prop Drilling** and it feels awkward for good reason - it's inefficient and really difficult to refactor! Context solves this problem.

### Setting up Context

Imagine you're building a dashboard page to display information about a user - you could have several components that all need to consume that data:

Create a file called `UserContext.ts`:

```ts
import { createContext } from 'React'

const UserContext = createContext<User | null>(null)

export default UserContext
```

### Providing Context to a component tree

Use the _Context Provider_ in the top level of the dashboard:

```tsx
import UserContext from './UserContext'

function Dashboard() {
  const user: User = {
    name: "Tom",
    email: "hello@mitchelmore.dev"
  }

  return (
    <UserContext.Provider value={user}>
       ...
    </UserContext.Provider>
  )
}

export default Dashboard
```

### Consuming Context

Accessing our context is as simple as passing it to one of React's built-in hooks:

```tsx
import { useContext } from 'react'
import UserContext from './UserContext'

function DisplayUser() {
  const user = useContext(UserContext)

  if (user === null) throw new Error("...")

  return (<div>{user.name}</div>)
}
```

It really is that simple - and it's something I discovered far too late into my journey with React.

## When not to use Context

While Context is great for eliminating prop drilling - there are definitely scenarios where I'd be reaching for Redux:

### Complex data

If your data is a giant nested object, then a global state library is something I'd definitely recommend. Redux, for example, will help you split it into manageable "slices" and also let you define actions to get and mutate data at your will.

### Server-synchronised data

A much more sustainable approach to web app development is storing all data server-side and having the frontend reflect it. This completely eliminates global state on the frontend, and prevents issues with saving data as the backend is the single source of truth. [Tanstack Query](https://tanstack.com/query/) (formerly React Query) is by far the best and most popular solution - I'd highly recommend it!

## Conclusion

To conclude, the purpose of this article is to help you understand how understanding React and its ecosystem can help you make architectural decisions. Far too often people spend hours setting up a library like Redux (increasing their bundle size!) just for functionality that could've been perfectly achieved with context.
Usefull Tech Stack - App, Frontend, Backend, Server
Tags: techstack, webdev, programming, beginners
Published: 2022-09-09 22:54:08

This is my "complex" techstack and now in production.

Principles of clean code, use of the best thing in one area and a clear separation of frontend and backend is important to me.



Server (Backend)
- Apache2
- PHP
- Mysql
- Symfony Framework (Api)

Frontend (Web)
- Twig
- HTML, SCSS, JS
- Used API
- Standalone

Frontend (App)
- Android (Native): Java -> WebView
- iOS (Native): SwiftUI 

Now the ask: Why so complicated?
Answer: I think it makes sense to choose the best tool for each task. 

Client and Server is in a perfect workflow.
從 3 - 5 談 C 語言無號整數的運算
Tags: c, cpp
Published: 2022-09-10 04:04:28

如果說 `3 - 5` 有可能是正數, 你信嗎？在 C 語言裡, 如果是無號 (unsigned) 整數, 那 `3 - 5` 就會是正數, 這是因為無號整數會[遵循除以 $2^n$ 取餘數](https://en.cppreference.com/w/c/language/operator_arithmetic#Overflows)的規則, 因此 `3 - 5` 實際運算結果雖然是 -2, 但若是無號整數, 因為不會有負數, 會依循上述規則取結果, 以下是[簡單的範例](https://www.online-ide.com/PsifvoE2hx)：

```c
#include<stdio.h>

unsigned char a = 5, b = 3, c;

int main()
{
    c = b - a;
    printf("%d\n", c);
    return 0;
}
```

執行結果如下：

```
254


** Process exited - Return Code: 0 **
```

這是因為 `unsigned char` 是 8 位元, 因此依照規則就會是 `-2 % 256` 得到 254。

相同的道理, 如果無號整數溢位 (overflow) 了, 也是一樣, 例如[以下的範例](https://www.online-ide.com/JSfQlguMp0)：

```clike!
#include<stdio.h>

unsigned char a = 5;

int main()
{
    a += 256;
    printf("%d\n", a);
    return 0;
}

```

執行結果如下：

```
5


** Process exited - Return Code: 0 **
```

因為 `(5 + 256) % 256` 仍然是 5 的關係。
Welcome to my creative space ! A space for nothing but fun programming projects.
Published: 2022-09-10 11:40:13

This space is to document my voyage back into tech, and some more...

Previously I worked in the tech sector with past employment spent working at '[hosteurope](www.hosteurope.com)', '[ionos](www.ionos.de)' and '[iomart](www.iomart.com)'. These past employment were as a Network Engineer and System Administrator, maintaining Linux & Unix servers. Some of the other tasks included organizing, installing and supporting organizations' computer systems. The LAN, WAN and other data communication systems (firewalls, routers, etc.,).

Then about 2 years ago I decided to take a break from daily grind and spend time travelling the world. I visited Tanzania, Ethiopia, UAE, Egypt and China.

This blog is a space and somewhere to have fun, to explore intellectual curiosities, and, to try experience that creative exhilaration that we can feel when building something from scratch, see it develop from a simple idea, and into a something (hopefully!) useful.

I understand software development is a vast field and one that is creative, demanding and extremely rewarding. It is something I am interested in and I like the field's cerebral nature. Mastering Full-stack Web development (I notice the sector has changed enormously) and will continue continue into software engineering.

Learning and growing technically is humbling and something to look forward to. I also intend to assist others, it is by teaching others that we can effectively learn more.


COPY

COPY
    *It is by teaching that we teach ourselves - Henri Frederic Amiel*

That's all for today !
N-Queen Visualization made with React as a tribute to Queen Elizabeth
Tags: react, algorithms, vite
Published: 2022-09-10 12:03:40

I've a knack of making visualizations for data structures and algorithms to understand them correctly. Recently working on a visualization of N-Queen problem. I happened to complete the project on the same day when Queen Elizabeth passed away. So I dedicated the application to her name. Check the links out if interested. 

- [GitHub](https://github.com/RitamChakraborty/n_queen_visualization)
- [Application](https://ritamchakraborty.github.io/n_queen_visualization)
25 Customer Feedback Tools All Developers Need
Tags: productivity, showdev, news, webdev
Published: 2022-09-11 13:29:40

As a indie maker, you know that your product is only as good as the feedback you get from your customers. 

The more you know about how your customers use your product and why they use it, the better equipped you are to develop a product that will meet their needs.

There are many different types of feedback tools and [product strategies](https://supahub.com/blog/product-strategy-framework) that can help you gather information about what your customers need and want. 

The problem is that many customer feedback tools are expensive, difficult to use and poorly designed.

This can make it hard for small businesses with limited resources to get started with customer feedback tools.

Here are list of 25 customer feedback tools that will help you with your SaaS product:

## 1. Supahub

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

With the Supahub feedback tool, you can easily collect, manage and prioritize your customer's feedback from different platforms in one place. 

It allows you to get real input from your users to stop you from assuming their needs. Instead, let your users share their needs in their own voices.

**Read the list of all 25 feedback collection tools here: [25 exclusive customer feedback tools](https://supahub.com/blog/customer-feedback-tools)**

---

## Thanks for reading 🙏
I'm Ayush, co-founder of [Supahub](https://supahub.com). For more actionable tips and articles that will help you grow, follow me on [LinkedIn](https://www.linkedin.com/in/ayushjangra/) and [Twitter](https://twitter.com/_ayushjangra_)
The simplest way to differentiate between the data engineers, data scientists and the data analyst.
Tags: datascience
Published: 2022-09-12 14:10:07

Taking the three roles as a complete architectural model, we have architecture engineers designing and building the house, lorries and trucks, bringing the building materials and drivers to the construction site
##Data engineers
Data engineers, in this case, are like architectural engineers. just like the architectural engineers,They will design and build the pipelines to ingest data. They are also responsible for maintaining these pipelines. They are the brains behind how the data will flow from data lakes or data warehouses to the data pipelines.
##Data scientists 
Data scientists are like trucks and lorries bringing construction materials to the construction site. Just like the trucks carries the material, data scientists will carry the preprocessed data to the consumer. They will use technologies such as machine learning to make future prediction. They will exploit the data from data pipelines and draw complex insights from such data. 
##Data analysts. 
Data analysts. Like the driver ,takes the building materials to the site, data analysts use their skills to drive the data to the consumer. Data analysts examine and combine several datasets to help the business understand the trend in the business. Data analysts are the brains behind making an informed business decisions in an organization. They work with the current data to understand the current business situation of an organization
Let's Get Cyber-Physical: The Expanding Role of CPS
Tags: opensource, microservices, systems, luos
Published: 2022-09-13 16:01:54

Cyber-physical systems are closely tied to the IoT and will increasingly use AI in every imaginable use case to operate more autonomously.

⏩ https://www.electronicdesign.com/technologies/embedded-revolution/article/21250006/luos-lets-get-cyberphysical-the-expanding-role-of-cps

Nicolas Rabault wrote a new article on Electronic Design to define CPS and their applications in many fields.
SOLID : Dependency Inversion
Tags: typescript, architecture, programming
Published: 2022-09-16 14:28:13

When I searched about it, it turned out **Dependency Inversion** is accomplished by using **Dependency Injection**

So I'm gonna use my own code about **Dependency Injection**. Please take a look at first this article, if you haven't read it yet
{% link https://dev.to/kaziusan/-escape-from-crazy-boy-friend-explain-dependency-injection-so-easily-32fe %} 

▼ Bad code in this article of **Dependency Injection**
```typescript
class Woman {
  makeLover(){
    const bf = new CrazyMan()
    bf.stayWith()
  }
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

const woman = new Woman()
woman.makeLover()
```
image is like this. Woman depends on Crazy man

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

We need to **invert** this direction, but how? 
It resolves by using interface, this is **Dependency Inversion**

```typescript
class Woman {
  constructor(man: IMan) {
    this.man = man
  }
  makeLover(){
    this.man.stayWith()
  }
}

// ⭐⭐ this interface is key !!!!!!!
interface IMan {
  stayWith: () => void
}

class CrazyMan {
  stayWith() {
    console.log('I am dangerous man, stay with me')
  }
}

class GoodMan {
  stayWith() {
    console.log('I am good man, stay with me')
  }
}

const man = new GoodMan()
const woman = new Woman(man)
woman.makeLover()

// I am good man, stay with me
```

▼ Now Crazy man, Good man depend on **Man Interface**, as you can see direction inverts now


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

---

ref
https://khalilstemmler.com/articles/tutorials/dependency-injection-inversion-explained/
[This is good sample of Typescript, it's in japanese though](https://www.membersedge.co.jp/blog/typescript-solid-dependency-inversion-principle/)
Top 40 GIT interview questions and answers for SDET - Automation QA - DevOps - SDE - QAE?
Published: 2022-09-14 13:26:48


Refer below link for frequently used GIT commands and git conflicts
**************************
https://lnkd.in/eWzB45W2
**************************
Want to learn more about GIT and go through all posts related to GIT for SDET then do check out [HERE](https://automationreinvented.blogspot.com/search/label/GIT)

**Git merge conflicts**

Version control systems are all about managing contributions between multiple distributed authors ( usually developers ). Sometimes multiple developers may try to edit the same content. If Developer A tries to edit the code that Developer B is editing, a conflict may occur. To alleviate the occurrence of conflicts, developers will work in separate isolated branches. The git merge command's primary responsibility is to combine separate branches and resolve any conflicting edits.

Git merge Conflicts generally arise when two people have changed the same lines in a file, or if one developer deleted a file while another developer was modifying it. In these cases, Git cannot automatically determine what is correct. Conflicts only affect the developer conducting the merge, the rest of the team is unaware of the conflict. Git will mark the file as being conflicted and halt the merging process. It is then the developers' responsibility to resolve the conflict.
"Remember that if you are planning to move to SDET role, then expertise in GIT is non negotiable."

#qa #automation #devops #interview #testautomation #softwaretesting #github #gitcommands #testing #testers #sdet #gitops #sourcecode #learningtech #learning #team #developer #people

Follow @sidharth88 for more posts
How to merge two arrays?
Tags: javascript, webdev, 100daysofcode, beginners
Published: 2022-09-15 10:16:48

Let’s say you have two arrays and want to merge them:

```javascript
const firstTeam = ['Olivia', 'Emma', 'Mia']
const secondTeam = ['Oliver', 'Liam', 'Noah']
```
One way to merge two arrays is to use concat() to concatenate the two arrays:

```javascript
const total = firstTeam.concat(secondTeam)
```
But since the 2015 Edition of the ECMAScript now you can also use spread to unpack the arrays into a new array:

```javascript
const total = [...firstTeam, ...secondTeam]
console.log(total)
```
The result would be:

```javascript
// ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
```

There is also another way, in case you don't want to create a new array but modify one of the existing arrays:

```javascript
firstTeam.push(...secondTeam);
firstTeam; // ['Olivia', 'Emma', 'Mia', 'Oliver', 'Liam', 'Noah']
```
Open Edge Developer Tools automatically by launching debug with Visual Studio 2022
Tags: programming, dotnet, blazor, productivity
Published: 2022-09-15 11:04:08

During my daily activities, I use Visual Studio constantly to work with Blazor projects.
Since Blazor is a frontend technology that exchanges data with APIs, the developer toolbar of the browser is a very important tool.
My flow to debug an application is: press F5, wait until the browser is loaded, press F12, open the dev tools (and sometimes move the developer toolbar in the right position).
It may seem like a quick activity but repeating this activity many times during the working hours, takes a lot of time and it's annoying.
I found a trick to reduce this manual activity.

From the Visual Studio toolbar on the top, click on the debug menu, on the arrow close to the name of the project.

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

Click on "**Browse with**", in the new window, click on "**Add...**" and insert the following values:


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

For debugging purposes, I use the Edge Developer, but this trick works with the other versions as well.
The path of my dev instance is: "**C:\Program Files (x86)\Microsoft\Edge Dev\Application\msedge.exe**"
As arguments, you can set: "**--auto-open-devtools-for-tabs**".
The friendly name is up to you, for instance, I use the name "**Edge Dev with Tools**"
Click Ok and save.
I set as Default this new browser definition.

Now you can launch your debugging session as always and the developer tools will open automatically at startup.
With my screen I use the developer tools in a separate window, as you can see in the screenshot below.

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

Happy debugging!
Add all the first elements and second elements to new list from a list of list using `list comprehension`
Tags: python, interview, career
Published: 2022-09-15 11:32:23

Question:
Add all the first elements and second elements to new list from a list of list using `list comprehension`

Ex:
Given: [ [1,2], [3,4], [5,6] ]
Expected: [[1, 3, 5], [2, 4, 6]]

Solution:

```python
a = [ [1,2], [3,4], [5,6] ]
final_list = [[x[0] for x in a], [x[1] for x in a]]
print(final_list)
```
Test your PHP
Tags: php, phpskills, phptest
Published: 2022-09-26 04:29:06

Got these tests from recent interviews and thought it to share with everyone to once in a while measure your PHP skill level.

#1. Check if Parentheses, Brackets and Braces Are Balanced. It's better to use Stacks method but use your own if you must.
`'{{}}' = Pass
'[]}{{}}' = Fail
'[[{]{{}}' = Fail
'[]()(' = 1x open parenthesis/bracket/curly brace
'[]({{{{{{{{{{{{{{{{{}}}}}}}}}})' = Too many open `

#2. Unique names

`$names = unique_names(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma']);`

`// should print Emma, Olivia, Ava, Sophia
function unique_names(array $array1, array $array2) : array
{
   //todo: your code here
}`



#3. Find the roots in any order

For example: findRoots(4, 12, 8); //[-1,-2] or [-2,-1]

root formula

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


`@return array An array of two elements containing roots in any order`

`function findRoots($a, $b, $c)
{
    //todo: your code here
}`

#4. Fibonacci Sequence

Write a code that will get the Fibonacci sequence number starting from #1 up to n numbers.

`should print:
1 1 2 3 5 8 13....n`

Post your code in the comments.
It's Hacktoberfest!
Tags: database, hacktoberfest, opensource, github
Published: 2022-10-03 21:24:21

Get a chance to win $30k worth of cash prizes, a team meeting with the CTO, and exclusive swag by building your application idea with SingleStore through Nov. 7th.
 
Sounds appealing, right? 

Here's what you need to know: [https://singlestore.devpost.com/]
Strong Parameters in Rails?
Tags: webdev, ruby, beginners, rails
Published: 2022-12-16 19:29:56

Ah, strong parameters in Rails

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

The magic charm that allows developers write spell-bound code. Just kidding, they're actually a pretty useful tool for protecting your application from malicious user input. But let's be real, they can still be a pain to deal with at times.

So, what are strong parameters exactly? Essentially, they're a way to specify which parameters are allowed to be passed through to your controller actions. This helps prevent attackers from injecting harmful data into your application.

Let's say we have a form that allows users to create a new post. We want to allow them to specify the title and body of the post, but we don't want them to be able to set the published attribute. Without strong parameters, anyone could just send a POST request with a published parameter set to true and voila, they've published a post without your permission.

Here's an example of how we can use strong parameters to only allow the title and body attributes to be passed through:

```ruby
def create
  params.require(:post).permit(:title, :body)
end
```

This will ensure that only the title and body attributes are allowed to be passed through to the create action. Any other attributes will be filtered out.

But wait, there's more! You can also specify which attributes are required by using the require method. For example:

```ruby
def create
  params.require(:post).permit(:title, :body).require(:title)
end
```
This will ensure that the title attribute is not only permitted, but also required. If the title attribute is not present, the controller action will raise a ActionController::ParameterMissing error.

Now, I know what you're thinking. "This is all well and good, but what if I have a bunch of nested attributes that I want to permit? Do I have to write out every single attribute individually?"

Fear not, my fellow developer friend! Rails has introduced the permit! method, which allows you to permit all attributes and nested attributes. Just be careful with this one, as it can potentially open up your application to malicious input if used improperly.

```ruby
def create
  params.require(:post).permit!
end
```

There you have it, a quick overview of strong parameters in Rails.They may seem like a nuisance at times, but trust me, they're worth the effort in the long run to keep your application secure. Happy coding!
Turnstile , alternative to CAPTCHA from cloudflare
Tags: captcha, javascript, cloudflare, privacy
Published: 2022-10-04 03:44:16

Demo: https://demo.turnstile.workers.dev/

Turnstile is our smart CAPTCHA alternative. It automatically chooses from a rotating suite of non-intrusive browser challenges based on telemetry and client behavior exhibited during a session.

> Less data collection, more privacy, same security

## Swap out your existing CAPTCHA in a few minutes

You can take advantage of Turnstile and stop bothering your visitors with a CAPTCHA even without being on the Cloudflare network. While we make it as easy as possible to use our network, we don't want this to be a barrier to improving privacy and user experience.

To switch from a CAPTCHA service, all you need to do is:

1. Create a Cloudflare account, navigate to the `Turnstile` tab on the navigation bar, and get a sitekey and secret key.
2. Copy our JavaScript from the dashboard and paste over your old CAPTCHA JavaScript.
3. Update the server-side integration by replacing the old siteverify URL with ours.

source code for demo example: https://github.com/cloudflare/turnstile-demo-workers

reference: https://blog.cloudflare.com/turnstile-private-captcha-alternative/?ck_subscriber_id=904285867
New Usefull JavaScript Tips For Everyone
Tags: javascript, webdev, beginners, programming
Published: 2022-10-04 04:52:35

## **Old Ways **

```
 const getPrice = (item) => {
  if(item==200){return 200} 
   else if (item==500){return 500}
   else if (item===400) {return 400}
   else {return 100}
}

console.log(getPrice(foodName));

```

## **New Ways**

```
const prices = {
 food1 : 100,
 food2 : 200,
 food3 : 400,
 food4 : 500
}

const getPrice = (item) => {
 return prices[item]
}

console.log(getPrice(foodName))
```

Hope you like my new tricks :D

[](https://github.com/shaon07) follow my github account