teleren/devto huggingface dataset:
useNavigate not working in Ternary operator
Published: 2022-11-05 21:50:36

Hi guys, I'm a newbie in ReactJS and I am working on a Banking Application to get better at this library. At the moment I am stuck with a React Router problem while signing-in. To simplify my question, I have removed the JWT implementation. Basically the setAuthentication should set isAutheticated to true and then based on the ternary operator, I should be sent to "/home" and if false then the index page "/". However, every time I click on submit, I am routed to the "/" path. The router has already been set in the App.js file for both the paths mentioned. Also, when I use navigate outside of the ternary operator, it works and I am sent to the "/home" path. What could be the problem?

```
const [email, setEmail] = useState('')
const [password, setPassword] = useState('') 
const dispatch = useDispatch(); 
const { token, isAuthenticated } = useSelector((state) => state.userLogin) 
const navigate = useNavigate();

const handleSubmit = (e) => { e.preventDefault();
 dispatch(setAuthentication())

 isAuthenticated === true ? navigate('/home') : navigate('/');

 setEmail('');
 setPassword('')
}
```
How to use Chakra UI with Next.js 13 (React Server Components)
Tags: nextjs, chakraui, server, components
Published: 2022-11-05 21:48:11

Next.js 13 was released a short time ago, bringing great news, the /app directory, which works with React Server Components.

"Today, many components from npm packages that use client-only features do not yet have the directive" ([Rendering: Server and Client Components | Next.js](https://beta.nextjs.org/docs/rendering/server-and-client-components#third-party-packages))

### How can we use those components while we enjoy the new features available in /app directory?

This is quite easy to answer, here's a shortcut for the code that would work with Chakra UI:
#### **`chakra-client-components.js`**
```typescript
"use client"
export * from "@chakra-ui/react";
```

So instead of importing from "@chakra-ui/react" in your code, you should import from "./chakra-client-components".

That's all folks 👋
React state in 2 min
Tags: webdev, react, state, beginners
Published: 2022-11-05 20:46:25

Dear reader,this is going to be a 4 part series article highlighting the following concepts on state in react.
On a lighter note,did you know you just discovered a gem in the react mines 😁. Here!

## What is State in React?

## How State in React works?

## Types of State in React

## What is Lifting State Up in React?

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


**Okay, lets get started!**
## What is State in React?
- React Provides a dynamic data store for each component
- The internal data represents the state of a react component and can be accessed using the state member variable of that react component.
- Whenever the state of the component changes, the component re-renders along with its new state by calling the render() method.

> ### Summary:
> The state represents the value of dynamic properties of a React component's data at a given instance. 

## How to define State in React?

- They are two ways to define the state in React, using the setState API and useState Hooks API respectively.
- Will focus on the useState hook API for functional components
- React state should not be modified directly through the state member variable and updating the state through the member variable does not re-render the component.
- to define state simply import the  useState hook
   ``` const [myState, setMyState] = useState({name: 'Jon'}) ```

- To access the state simply :
 ``` <p>{myState.name}</p> ```

- To update state simply:
``` 
const handleState =() => {
    setMyState ({name: 'Jane', age: 27})
}

```
> ### Summary
>  We can update any one of the state fields at a time instead of updating the whole object. This feature gives the developer the flexibility to easily handle the state data.

### Conclusion

In react whenever the state is inferred or defined it simply means the status of the application or component at any given instance and that allows it to be aware of its environment to respond to requests and updates accordingly.
Change element scale by scroll on parent (zoom by scroll on parent)
Tags: javascript, css, html
Published: 2022-11-05 20:33:28

I'm trying to add scaling by mouse scroll , but so far not so good, I'm somehow failing to place the scaled element (in this case id: test) correctly

```
const ts = {
        scale: 1,
        rotate: 0,
        translate: {
            x: 0,
            y: 0
        }
    };



  var parent =  document.querySelector('#parent');
  
    parent.addEventListener("wheel", 
     (event) => {
     event.preventDefault();
        let xs = (event.clientX - ts.translate.x) / ts.scale;
        let ys = (event.clientY - ts.translate.y) / ts.scale;


        let delta = (event.wheelDelta ? event.wheelDelta : -event.deltaY);


        ts.scale = (delta > 0) ? (ts.scale * 1.03) : (ts.scale / 1.03);


         ts.translate.x = event.clientX - xs * ts.scale;
         ts.translate.y = event.clientY - ys * ts.scale;
        setTransform();
    }
    ,true);
    function setTransform() {
        const steps = `translate(${ts.translate.x}px,${ts.translate.y}px) scale(${ts.scale})`;
        test.style.transform = steps;
    }
#parent {
height:900px; 
width:100%; 
border:1px solid #000000;
background-color:gray;
overflow: hidden;
} 

#test {
max-width: 100px;
max-height: 100px;
min-height: 100px;
min-width:100px;
background-color:pink;
position:relative;
}
    <div id="parent" >
        <div id="test"></div>
    </div>
```

https://jsfiddle.net/3uhy46dv/

what I'm doing wrong?

this is what it should be like. https://postimg.cc/k28x2DsB
One Minute: Chicken Scheme
Tags: oneminute, chickenscheme, scheme, lisp
Published: 2022-11-05 20:32:28

CHICKEN Scheme is an open-source Scheme implementation.

**Design:** [Cheney on the MTA](https://web.archive.org/web/20060303155622/http://home.pipeline.com/~hbaker1/CheneyMTA.html)
**Modes:** [Interpreter](http://wiki.call-cc.org/man/5/Using%20the%20interpreter), [Compiler](http://wiki.call-cc.org/man/5/Using%20the%20compiler)
**Standards:** [R5RS](https://doi.org/10.1145/290229.290234), [R7RS](https://small.r7rs.org/)
**Platforms:** x86, x86-64, ARM, ARM64, MIPS, SPARC64, PowerPC
**Systems:** Linux, MacOS, BSD, Windows
**License:** [BSD-3-Clause](http://opensource.org/licenses/BSD-3-Clause)
**Written In:** C

**Website:** http://call-cc.org
**Manual:** http://wiki.call-cc.org/manual/index
**Wiki:** http://wiki.call-cc.org/
**Repository:** https://code.call-cc.org/cgi-bin/gitweb.cgi?p=chicken-core.git;a=summary
**Standard Libraries:** http://wiki.call-cc.org/man/5/Included%20modules
**Extension Repository:** http://eggs.call-cc.org/5/

**Wikipedia:** https://en.wikipedia.org/wiki/Chicken_(Scheme_implementation)
**Open Hub:** https://www.openhub.net/p/chicken
Member function & member procedure from the oracle to postgresql
Tags: postgres, ora2pg
Published: 2022-11-05 20:19:13

create or replace TYPE    "TEST_ACC"     AS OBJECT(
create or replace TYPE    "TEST_ACC"     AS OBJECT(
OGID        VARCHAR2(6),
ACCT           VARCHAR2(10),
member procedure TEST_ACC_I (ADT IN VARCHAR2),
member function TEST_ACC_II RETURN VARCHAR2
);



create or replace TYPE BODY               "TEST_ACC" AS
MEMBER PROCEDURE TEST_ACC_I(ADT IN VARCHAR2) IS
BEGIN
OGID        :=RPAD(trim(replace(replace(SUBSTR(ADT, 1,6),CHR(9),''),chr(13),'')), 6, ' ');
ACCT          := RPAD(trim(replace(replace(SUBSTR(ADT,  7,10),CHR(9),''),chr(13),'')), 10, ' ');
END;
MEMBER FUNCTION TEST_ACC_II
RETURN VARCHAR2 IS
BEGIN
RETURN RPAD(trim(replace(replace(OGID, chr(9), ''),chr(13),'')), 6, ' ') ||
       RPAD(trim(replace(replace(ACCT, chr(9), ''),chr(13),'')), 10, ' ') ||
      
END;
END;

ORA CODE: Using the below code from the other procedure.

v_t_acc := TEST_ACC(null, null, null, null);



How to convert this into postgresql


ORA CODE: Using in the other procedure.

v_t_acc := TEST_ACC(null, null, null, null);
Soul, SQLite REST server is realtime now.
Tags: sqlite, realtime, node, api
Published: 2022-11-05 20:15:03

Hi Folks, It's been an amazing journey since I first published Soul on HN and now I added a really major feature that Soul lacked, Realtime changes via Websockets.
For those who are not familiar with Soul, it basically takes a SQLite database file and run a CRUD API on it, so you can have a minimal backend with no code.

Now thanks to this new feature, users can subscribe to changes in a table and whenever a Create, Update or Delete operation happens, Soul will send the realtime data to subscribers.

If you need some examples on how to work with websockets in Soul, you can find a bunch of examples here: https://github.com/thevahidal/soul/blob/main/docs/ws-examples.md

Please let me know what you think of this new feature and also submit any issues you faced so we can fix them as soon as possible.

Also if you have ideas to make Soul a better tool, please send me your ideas, it'll help me a lot.

Here's a small example of how realtime works in Soul:
```bash
 # Install Soul
npm install -g soul-cli 

# Install websocket client to test Soul realtime
npm i -g wscat

 # Download sample sqlite database
wget https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite

# Run Soul
soul -d ./Chinook_Sqlite.sqlite -p 8000

# Subscribe to Employee table realtime changes
wscat -c ws://localhost:8000/ws/tables/Employee
```

Then to test it, in a new terminal, insert a new row in the table Employee:
to test it, in a new terminal, insert a new row in the table `Employee`:

```bash
curl --request POST \
  --url http://localhost:8000/api/tables/Employee/rows \
  --header 'Content-Type: application/json' \
  --data '{
    "fields": {
        "FirstName": "Damien",
        "LastName": "Rice"
    }
}'
```

Checkout `wscat` terminal, it should respond with the following message:

```json
{
  "type": "INSERT",
  "data": {
    "pk": 10,
    "FirstName": "Damien",
    "LastName": "Rice"
  }
}
```

You can test the same thing with Update and Delete operations too.

Once again thanks for the support and I'll see you in the next one!

Repo: https://github.com/thevahidal/soul
HN: https://news.ycombinator.com/item?id=33484693
Laravel update factory after creation
Tags: laravel, factories, callbacks
Published: 2022-11-18 18:58:46

---
title: Laravel update factory after creation
published: true
date: 2022-11-05 20:02:00 UTC
tags: Laravel, Factories, Callbacks
canonical_url: https://dcblog.dev/laravel-update-factory-after-creation
---

Using a Laravel factory to create a user and then update a relationship directly is possible using factory callbacks. Using a configure method you can call **afterCreating** and **afterMaking** closures:

```

<?php

namespace Database\Factories;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name' => $this->faker->name(),
            'slug' => Str::slug($this->faker->name()),
            'email' => $this->faker->email(),
            'password' => Hash::make('password'),
            'is_active' => 1,
            'remember_token' => Str::random(10),
        ];
    }

    public function configure()
    {
        return $this->afterCreating(function (User $user) {
            $user->tenant_id = Tenant::factory()->create([
                'owner_id' => $user->id
            ]);
            $user->save();
        });
    }
}

```

Read more about [Factory Callbacks](https://laravel.com/docs/9.x/eloquent-factories#factory-callbacks)
How to Merge Two Sorted Arrays
Tags: dsa, java, sorting
Published: 2022-11-05 19:56:45

Problem
You are given two sorted arrays A and B of lengths m and n, the task is to merge the two sorted arrays in such a way that the merged array is also sorted.

## Example
**Input**
A[] = {3, 9, 10, 18, 23}
B[] = {5, 12, 15, 20, 21, 25}

**Output**
Merged[] = {3, 5, 9, 10, 12, 15, 18, 20, 21, 23, 25}

**Explanation**
The merged array is of the size of n + m and contains both the elements of array A and array B in sorted order

**Input:**
A[] = { 5, 8, 9}
B[] = {4, 7, 8}

**Output:**
Merged[] = {4, 5, 7, 8, 8, 9}

**Explanation**
The merged array is of the size of n + m and contains both the elements of array A and array B in sorted order

## Index

1. Brute Force Approach
2. Insertion Sort Approach
3. Efficient Approach — Using Merge Sort
 

## Brute Force Approach
The idea is to create a new array C[] of length m+n and put all the elements from A[] and B[] in it and then sort them using Arrays.sort().

![Merged Array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tl5dgsqvur5bxb2io3tq.png)

## Algorithm

1. Create an array C of n+m size to store the merged array
2. Put the values of both A and B arrays using a for loop
3. Sort the C array using Array..sort().

![Simple merging of two sorted arrays](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ur07djopxu4jxzdvduut.png)

## Pseudo Code
```Int[] solve(int[] A, int[] B, int n, int m) {
Create a new array C of n+m size
while(i<n) {
C[k++] = A[i++];
}
while(j<m) {
C[k++] = B[j++];
}
Sort C;
return C
} ```



## Output
Array after merging - 1 2 3 4 5 6 7 8

**Time Complexity** — O((m+n) log(m+n))
We have sorted an array of size m+n using Arrays.sort(), and the time complexity of this operation is O(n log n) which in this case becomes O((m+n )log(m+n))

**Space Complexity** — O(m+n)
We have created a new array C of size n+m which will store the merged sorted array.

[Continue Reading…](https://tekolio.com/how-to-merge-two-sorted-arrays/)
How can you help me at problem solving?
Tags: help, programming
Published: 2022-11-05 19:53:13

I need to master my skills at problem solving as a programmer to be good software engineer as all know , i have programming basics knowledge , oop , data structures and i don't know where i should start or how to start , i tried to solve problems on codeforces and other websites like this but i find it so difficult to solve problems even after see solution i disappointed to not solve it , so if you have any platform or courses to make me master my skills at problem solving please suggest it to me and i will be grateful to you
Make your DOM look like an eye that can focus on anything!
Tags: webdev, javascript, typescript, github
Published: 2022-11-05 19:36:21

![Watching-you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dvnx2ayqfp5rc2cqe9e8.png)

Hello, I'm Ryan.

I would like to show you an animation library I developed😀.

It can make your DOM look like an eye that can focus on anything!

The Repo URL: https://github.com/jj811208/watching-you

## Example

<a href="https://jj811208.github.io/watching-you/#/example/login" target="_blank">Login Form</a>
![login-form-watcher](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkm9s7kqzfzsxu992ldb.gif)

<a href="https://jj811208.github.io/watching-you/#/example/cena" target="_blank">Cena is watching you</a>
![cena-is-watching-you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts2mfnrd7if8f8i0ssz6.gif)

## Features

- Ability to watch mouse or another DOM or even input values, watch anything you want!
- Because it is DOM-based, it is easy to support RWD
- Supports multiple frameworks
  - vanilla.js
  - react
  - vue
- Zero dependency (every framework is!)
- Written in typescript
- The size of the core code is only `3kb` after gzip compression
- If the element is not on the screen, it will automatically stop running

You can see more on the GitHub Repo!!

---

I like this effect myself and have used it in many projects, but this repo is still an very new open source project, so if you find bugs or have any suggestions, feel free to open an issue, I would appreciate it 🙏

Finally, if you like it, I hope you can star this repo 🤩

The Repo URL: https://github.com/jj811208/watching-you
4 Tools you can't live without
Tags: webdev, kanban, vscode, extension
Published: 2022-11-05 19:35:34

In this post I will cover tools I use in my day to day life as a software engineer, let’s get started. It will cover extensions, platforms and a terminal that I can guarantee will speed up your workflow.

---

###1. Linear (Kanban Board)
If you have used Trello before it should be a seamless transition, but with benefits. Linear is the new way to build products, to streamline issues, sprints, and product roadmaps. The major difference where Linear really shines is it’s integrations, it enables github, Figma and Slack to name a few, to easily move issues based on e.g Github pull request with no extra setup. 

And the modern design is a nice change too, really makes you feel that we have moved into the 21st century. 

> It’s worth mentioning, you do need to authorize with the corresponding platform like Github to make it work.       
> https://linear.app/

![Demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20vw1w453ro51eyppkik.png)

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

---

###2. Advanced New File
advanced-new-file is a Vscode extension that allows you to create files anywhere in your workspace from the keyboard, very neat extension if you are like me and hate to move your hands from the keyboard.
![Demo](https://media.giphy.com/media/l3vRfRJO7ZX6WNJQs/source.gif)
[Source From Github Repo](https://github.com/patbenatar/vscode-advanced-new-file)

---

###3. Warp (Terminal)
The terminal for the 21st century, with features like auto completion, something they call Blocks and multiple tabs for all your scripts to run at the same time, and a lot more covered right [here.](https://docs.warp.dev/getting-started/readme) 

The main reason I use Warp is funny enough not warps features but rather the fact that it is an external terminal that keeps running despite my code editor. But it’s worth a try.
> It’s worth mentioning, Warp is for MacOS only for the time being, but will come to Windows at some point.
> https://www.warp.dev/

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

    

---

###4. Html Tag Wrap
htmltagwrap Wraps your selection in HTML tags. It can even wrap selections that span multiple lines. htmltagwrap is the extension I thought I never needed, but turns out I can’t imagine myself without it. And as we established I love the freedom of using the keyboard for every task possible, so this extension is another one for the books.

**How to Use It**
>Select one or more blocks of text or strings of text.
>Press Alt + W or Option + W for Mac.
>Type the tag name you want.
![Demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpgc1dtr1eetfkqx18ar.png)
[Source From Github Repo](https://github.com/bgashler1/vscode-htmltagwrap)

---

So I think this covers it. I hope you could use this and got inspired to try one of the four apps in this post.
C++ 3-Dars cin string int
Tags: beginners, programming, tutorial, cpp
Published: 2022-11-05 18:49:06

# C++ O’zgaruvchilar

 Assalomu alaykum bugun siz bilan **C++** dasturlash tilida o'rgaruvchilar haqida gaplashib olamiz. O'zgaruvchilar ma'lumot qiymatini saqlab turuvchi idish sifatida tushunishimiz mumkin. **C++** dasturlash tilida turli xila o'zgaruvchilar mavjud bo'lib har bir tur xil kalit so'zlari bilan nomlangan.

> O'zgaruvchi - Xotiraning nomlangan qismi bo’lib, o’zida ma’lum bir toifadagi qiymatlarni saqlaydi. O’zgaruvchining nomi va qiymatlari bo’ladi. O’zgaruvchining nomi orqali qiymat saqlanayotgan xotira qismiga murojaat qilinadi. Programma ishlashi jarayonida o’zgaruvchining qiymatini o’zgartirish mumkin. Har qanday o’zgaruvchini ishlatishdan oldin, uni e’lon qilish lozim.


- `int` - 123 yoki -123 kabi butun sonlarni (butun sonlar) saqlaydi.
- `double` - 19.99 yoki -19.99 kabi o'nli raqamlar raqamlarini saqlaydi
- `char`- "a" yoki "B" kabi bitta belgilarni saqlaydi. **Char** qiymatlari bitta tirnoq bilan o'ralgan.
- string- `"Hello World"` kabi matnlarni saqlaydi. Qator qiymatlari ikki tirnoq bilan o'ralgan
- bool - qiymatlarni ikki holat bilan saqlaydi: haqiqiy yoki noto'g'ri, `True` yoki `False` ( **1** yoki **0**)

> O'zgaruvchi qisqa nomga ega bo'lishi mumkin (masalan, x va y) yoki ko'proq tavsiflovchi nom (yosh, cpp, master va h.k). **C++** o'zgaruvchilar uchun qoidalar:

- O'zgaruvchilar nomi raqam bilan boshlanmaydi!
- O'zgaruvchi **[a-Z]** harf bilan boshlanib raqamlar ham aralashtirsa bo'ladi. ( _ali123, son90 va h.k)
- O'zgarvchi nomida katta va kichik harflar ahamiyatga ega bo'lib misol uchun **Aka** va **aka** ikki xil o'zgaruvchi nomi hisoblanadi! (Aka, aka, AkA, aKa)

**1-Masala:** Bizga cpp nomli o'zgaruvchi nomi butun tipga tegishli va qiymati 13 ga teng. ushbu o'zgaruvchini ekranga chiqaring.

```cpp
#include <iostream>
using namespace std;
​
int main() {
 int cpp;
 cpp = 13;
 cout << cpp;
}
```

```cpp
13
```
  Esdan chiqarmang. O'zgaruvchiga yangi qiymat kiritsangiz yoki tayinlasangiz oldingi mavjud o'zgaruvchi qiymati yuqoladi. quyidagi misolda ko'ring.

```cpp
#include <iostream>
using namespace std;
​
int main() {
   int mn = 13;  // mn 13 ga teng edi
   mn = 15;  // endi mn 15 ga teng 
   cout << mn;  // Natija 15 chiqadi
}
```

## O'zgaruvchi boshqa turlari.

```cpp
int myNum = 5;               // Butun qiymatli o'zgaruvchi
double myFloatNum = 5.99;    // o'nli kasrli sonlar uchun
char myLetter = 'D';         // Char tipga tegish yani bitta belgi
string myText = "Hello";     // TEXT saqlaydi
bool myBoolean = true;       // Boolean tipi bunda rost yoki yolg'on (true or false)
```



## Bir nechta o'zgaruvchini e'lon qilish.

   Bir **xil turdagi** bir nechta o'zgaruvchini e'lon qilish uchun vergul bilan ajratilgan ro'yxat shakllantiriladi:

```cpp
#include <iostream>
using namespace std;
​
int main() {
    int x = 13, y = 15, z = 1;
    cout << x + y + z;
}
```

Natija butun qiymatdagi berilgan **x,y,z** lar yig'indisini hisoblaydi.

```cpp
29
```

Hayr hurmatli Bo'lajak dasturchilar Keyingi darslarda ko'rushguncha 🖐️

@dawroun
Hello world!
Published: 2022-11-05 18:40:33

I've made a few significant pivots in my career,  some for  necessity, others for choice. Now I decided to make a more radical career change. I know it will shock a lot of my closest friends: I am starting a Front End Bootcamp at edX. Hopefully, by the final 2023, I will be working as a Front End developer. I would love to hear from you about your Journey and experiences that could help mine!
I am very excited to hear about your history!
Css
Published: 2022-11-05 18:30:01


`:root{
    --header-height: 56px;
    --sum-header:8px;
}


body{
    margin: 0px;
    background-color: rgb(245 245 245);
}
div.liner-header{
    display: flex;
    justify-content: space-evenly;
    background-color: #fff;
    align-items: center;
    
}

img.logo-img{
    height: calc(var(--header-height) - var(--sum-header) * 2);
}
button.search-button{
    background: none;
    box-shadow: none;
    border:none;
    padding: 0;
    margin: 0;
    cursor: pointer;
    appearance: none;
    width: 20px;
    position: relative;
    z-index: 2;
}
svg.search-svg{
    display: block;
    cursor: pointer;
    width: 20px;
    height: 20px;
}


input.input-search{
    width: 400px;
    padding: 5px 45px 5px 10px;
    box-sizing: border-box;
    border-style: rgb(245 245 245);


}`

)(url)