teleren/devto huggingface dataset:
tRPC in 100 seconds
Published: 2023-02-06 17:54:15

tRPC - A way to build entirely typesafe APIs without the need of schemas or code generation.

If you are building an API today, there are two main approaches: REST and GraphQL.

But there is actually another less talked about approach called tRPC with features like:
- Autocompletion
- Automatic typesafety
- Request batching

In REST Land the most basic way to fetch data inside a React Application is to use the browser fetch api, when the browser first mounts in `useEffect` then manage the response in a `useState`. This approach does not have a strong contract between the frontend and the backend: for example if you decide to change the message property from greeting to text, typescript will not throw an error, but in our React Application we get a broken UI.

This is where tRPC comes in. To get started create a new project with npm create `t3-app@latest`. 

tRPC is setup in routes and procedures, where a route is like a folder and a procedure is like a file.

If you open up the exampleRouter, you will see a hello procedure with an input object where name is a string, and an output object where greeting is a string.


To call the procedure in the frontend you have to use a special api object and navigate to the hello procedure by using the example router. Under the hood tRPC uses React Query to make the request

Note that changes to the backend will throw typescript errors in the frontend.

And additionally when making multiple requests, tRPC is going to batch all of them into a single HTTP Request.

There are a couple of instances where you shouldn't use tRPC:
- When your frontend and backend code is not written in TypeScript
- When you have separate backend and frontend teams

Here is the tRPC introduction in video form:
{% embed https://youtu.be/0DyAyLdVW0I %}
PHP 8.1: MySQLi: fetch_column function
Tags: php, mysql, tutorial
Published: 2023-02-06 17:53:12

Another [suggestion made by Kamil Tekiela](https://wiki.php.net/rfc/mysqli_fetch_column) was included in the PHP 8.1 release.
Starting with this release, one more method has become available in the mysqli class - the `fetch_column()` method previously implemented in the PDO library.

Lets create simple table for our tests:

```
create table persons (
    id int primary key, 
    name varchar(64),
    age tinyint
);

insert into persons values (10, 'Alice', 18), (20, 'Bob', 22);

+====+=======+=====+
| id | name  | age |
+====+=======+=====+
| 10 | Alice | 18  |
| 20 | Bob   | 22  |
+----+-------+-----+

```
```
$result = $mysqli->query("SELECT name FROM persons WHERE id = 10");

echo $result->fetch_column();
```
You can [test the above code here](https://phpize.online/sql/mysql57/e61e9314834351c0b4a33f0959cd439b/php/php81/cb90542f4d92ae0efcf08ec696a8e92f/)

If the query returns several columns, the `fetch_column(n)` function can return the value from the column whose number is passed as a function parameter (column numbering starts from 0).

```
$result = $mysqli->query("SELECT name, age FROM persons WHERE id = 10");

echo $result->fetch_column(1);
```
Just like with other fetch_* methods this one will also move the internal result pointer to the next row when called. **So you can not use fetch_column(i) for loop thought one record columns.** 
Next example explain this error:

```
<?php
$result = $mysqli->query("SELECT name, age FROM persons");

$name = $result->fetch_column(0);
$age  = $result->fetch_column(1);

// Returns Alice  name with Bob's age
printf("Name: %s, age: %d", $name, $age);
```
[Test PHP code online](https://phpize.online/sql/mysql57/b77bf62cd00f67bb433719a530ce2c8c/php/php81/d39ac72d052aa9f0009754256c9eec4a/)
Apache AGE : What it is and Tutorials
Tags: apacheage, postgres, cypher
Published: 2023-02-06 17:34:11

Hello everyone! I have been an intern for four months at Bitnine Global Inc. and I've been using PostgreSQL and a very interesting extension called Apache AGE. AGE is an acronym for A Graph Extension and is inspired by Bitnine's AgensGraph, a multi-model database fork of PostgreSQL. The basic principle of AGE is to create a single storage that handles both the relational and graph data model so that the users can use the standard ANSI SQL along with openCypher, one of the most popular graph query languages today.

Why use a graph database? Graph databases are the future of data storage, allowing a more intuitive representation of data, resulting also in a less computer intensive process.

Is rare for relational databases to provide expressivity to suitably describe the most use cases. And looking at many tables at the same time will quickly degrade performance.

When using graphs it is possible to consider everything as a whole, giving a simultaneous view of all the data with the adequate context. Also, the structure of a graph allows for more computationally intensive analysis and enables this at fast speed.

Here's an example of what is possible to do with Apache AGE


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

Here are some tutorials I made for Apache AGE:
* Installation Tutorial for Windows : https://www.youtube.com/watch?v=ddk8VX8Hm-I
* Family Tree Tutorial : https://www.youtube.com/watch?v=A32A54BWAHE

Checkout AGE's official website : https://age.apache.org/
And the Github repo : https://github.com/apache/age
How to Integrate Redis in Django?
Tags: django, redis
Published: 2023-02-06 17:31:49

**Steps:**
1. ```cli
pip install django-redis
```
2. Go to settings and add these lines
```python
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1", // Redis server running on your Machine 
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
```
3. For running redis server, istall **_msi_** from 
https://github.com/MicrosoftArchive/redis/releases
Go to C drive then redis and then redis_cli
Now, you have done setup
4. Go to your view.py file and add these lines at the top
```python
from django.core.cache import cache
```
5. How it works?
```python

def search(request):
    query = request.GET.get('query', '')
    if cache.get(query):
        product = cache.get(query)
        print("Cache hit")
    else:
        product = Product.objects.filter(Q(title__icontains=query)) | Product.objects.filter(Q(description__icontains=query))
        cache.set(query, product)
        print("Cache miss")
    return render(request, 'store/search.html',{
        'query':query,
        'products':product
        })
```
6. In this code, first we get query and then check if **query** key is available in the cache or not. **If** available then get it's value and assign it to the product **Else** You have to get the product value based on the query from the database.
Roman Numerals Decoder Codewars
Tags: romandecoder, romantointeger, codewars, python
Published: 2023-02-06 17:14:58

Today we will solve a Coding Problem, “Roman Numerals Decoder”, designed by Codewars in Python. In this Problem, we are given a String of Roman as Input, and we need to output an integer corresponding to that Roman Number. We Solved a similar Problem related to this where we converted Integers into Roman. You can read that Post here

Description of Roman Numerals Decoder Problem
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.

Example:

Input : XXIX
Output : 29
Help:

Symbol    Value
I          1
V          5
X          10
L          50
C          100
D          500
M          1,000
How do you decode Roman numerals?
Every symbol in Roman has a value associated with it. For example, X has a value of 10. Similarly, V has a value of 5. You need to add all the associated values, and you will get the number. For example, XXV where X=10 and V=5. Adding X+X+V = 10+10+5 = 25. But the Problem Arises when you have numbers like 4, 9, 40, etc. 9 is represented as IX in Roman, but if we apply the above technique. We will get I + X = 1 + 10 = 11. It is not Correct. When decoding Roman numerals, one thing to keep in mind is that, whenever the previous character in Roman is less than the current, we must subtract instead of Add. For Example, 4 is represented as IV in Roman, I has the value of 1, and V has a value of 5. so IV = 1 – 5 = abs(-4) = 4

Now let’s get to the Coding Part.

Roman Numerals Decoder Codewars Python Solution
Firstly, create a dictionary storing each Roman character along with its value.


def solution(roman):
    symbol = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
then, create two variables one for storing the total sum and other for storing the previous value.


To read more visit https://hecodesit.com/roman-numerals-decoder-codewars/
If Else statement in Solidity
Tags: web3, blockchain, ethereum, solidity
Published: 2023-02-06 17:14:28

>Solidity's if-else provides conditional code execution based on a Boolean condition.

##**If statement**

When writing a program, there may be a situation in which you must choose one of a number of possible options from a given set of options. It is necessary to utilize conditional statements in such situations to ensure that your program makes the correct decisions and performs the appropriate actions.

Conditional statements are supported in Solidity, and they can be used to conduct multiple actions depending on distinct conditions. In this section, we will go through the if statement.
```
pragma solidity ^0.8.0;

contract IfStatement{

    function globalVariables(uint a) public returns(string memory){
        if (a<10){
            return "Welcome to My Blog";
        }
    }
} 
```
##**If Else statement** 
```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract IfElse {
    function person(uint x) public returns (string memory) {
        if (x < 10) {
            return "person A";
        } else if (x < 20) {
            return "person B";
        } else {
            return "person C";
        }
    }
} 
```
##**Nested If Else Statement**
```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract IfElse {
    function person(uint x) public returns (string memory) {
        if (x < 10) {
            return "person A";
        } else if (x < 20) {
            if (x<15 && x>10){
                return "person B";
            }
            else if (x>15 && x<20){
                return "person C";
            }
       
        } else {
            return "person D";
        }
    }
}
```
For more content, follow me on - https://linktr.ee/shlokkumar2303
Making Error Messages Accessible
Tags: accessiblity, webdev, a11y, web
Published: 2023-02-06 17:05:01

In order to provide a user-friendly experience, it is crucial to make sure that errors in digital application forms are easily accessible. This not only ensures accessibility of the forms themselves, but also makes it easier for users to understand and resolve any mistakes. 

Here, we will outline several ways to make error messages accessible for users.

**1 . Provide clear error messages**

The error message should clearly describe the problem and suggest a solution.

**2 . Use accessible error styling**

Make sure the error messages are visually noticeable and distinguishable from other content on the page, for example, by using color contrast or adding a visible border around the error message.

**3 . Associate error messages with specific fields**

Link error messages with specific form fields using the aria-describedby attribute on the form field and the id attribute on the error message.

**4 . Make error messages keyboard accessible**

Ensure that keyboard-only users can access the error messages by including them in the keyboard tab order.

**5 . Use accessible error symbols**

Consider using symbols such as an exclamation mark or an asterisk to indicate that an error has occurred, but make sure the symbols are also described in text for screen reader users.

Here's an example of HTML code:

```HTML
<label for="email">Email:</label>
<input type="email" id="email" name="email" required aria-describedby="email-error">
<div id="email-error" role="alert" class="error-message">
  Please enter a valid email address.
</div>

```

Happy Learning!!

Follow me on [Twitter](https://twitter.com/hellonehha)
Trace based Testing and Global Warming?
Tags: opensource, codenewbie, devjournal, ai
Published: 2023-02-06 17:01:08

As the world becomes increasingly digitized, the effects of climate change are becoming more and more apparent. The way we live our lives is having a profound impact on the planet, and it’s time we take responsibility for our actions.

One small way we can do this is by ensuring that the software we write is as energy-efficient as possible. This is where trace-based testing comes in.

[Trace-based testing](https://tracetest.io/) is a method of testing software that analyzes the energy consumption of individual code paths. By understanding which code paths are the most energy-hungry, we can make changes to reduce the overall energy consumption of our software.

In addition to being more energy-efficient, trace-based testing has a number of other benefits. It can help us identify and fix bugs more quickly, and it can improve the overall performance of our software.

[Trace-based testing](https://tracetest.io/blog/v09-release-notes) is already being used by some of the world’s leading companies, including Google, Facebook, and Netflix. As the effects of climate change become more and more apparent, we expect more and more companies to adopt trace-based testing in an effort to reduce their carbon footprints.


--Follow **@makedatelesford** for more ai open source content explorations--


About the writer:
Name- Makeda
Job- Product Marketer for Monokle, Tracetest, Kubefirst.


**Tracetest.io**
https://tracetest.io/
For QA, Dev, & Ops
Tracetest allows easy creation of end-to-end tests via a simple user interface. Make your application bulletproof and stable. Even less technical users can create tests, enabling you to increase your test coverage.

**Monokle.io** 
https://monokle.io/
Monokle is a set of tools for creating and maintaining high-quality Kubernetes configurations throughout the entire application lifecycle.

**Kubefirst.io** 
https://kubefirst.io/
Helps organizations adopt kubernetes faster and more securely by providing a more comprehensive starting point.
Also helps development teams securely ship their applications faster with our scalable GitOps application delivery workflows.
On-device Transcription with 3 lines of Python
Tags: 100daysofcode, challenge, python, programming
Published: 2023-02-06 16:52:34

On day 26, we'll cover on-device transcription with 3 lines of Python.

Requirements:
1. Picovoice AccessKey - you can grab yours from the [Picovoice Console](https://console.picovoice.ai/) for free.
2. Leopard Speech-to-Text Python SDK
```
pip install pvleopard
```

Let's get started!

1. Import Leopard Speech-to-Text
```
import pvleopard
```
2. Create an instance with your AccessKey:
```
handle = pvleopard.create(access_key)
```
Don't forget to replace the access_key with the one you grabbed from the Picovoice Console.
3. Transcribe an audio file:
```
transcript, words = handle.process_file(audio_path)
```
Don't forget to replace the audio_path with the path for the file you want to transcribe.

## DONE!

This tutorial is first published on [picovoice.ai](https://picovoice.ai/blog/transcribe-speech-to-text-with-three-lines-of-python/)
How to type hex colors in typescript ?
Tags: typescript, programming
Published: 2023-02-06 16:45:19

As typescript [**doesn't** accept regex in types](https://github.com/microsoft/TypeScript/issues/41160), we had to find a way
to type our hex colors in our design system. Indeed, it wouldn't be very efficient to make a string type like that:

```typescript
export type ColorValueHex = string;
```
as it will accept all strings. 
For that, we came up with 2 solutions: a simple but less rigorous 
and an exhaustive one but more complex. We'll present those two solutions and explain which one we had to choose.

## The simple and straightforward solution:

The idea is to use the string template feature of typescript to shrink the type a little: 

```typescript
export type ColorValueHex = `#${string}`;
```

With that, we don't allow all types of string but only the ones beginning with the '#' character. Moreover, it is 
quite readable and maintainable thanks to its simplicity.

However, we wanted to push it a little further to check if it would be possible to tackle all the cases.

## The exhaustive one :

```typescript
type HexaNumber = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type HexaLetter = 'A' | 'B' | 'C' | 'D' | 'E' | 'F';
type HexaChar = HexaLetter | HexaNumber;
type Hexa3 = `${HexaChar}${HexaChar}${HexaChar}`;
type Hexa6 = `${Hexa3}${Hexa3}`;
type Hexa8 = `${Hexa6}${HexaChar}${HexaChar}`;
type ColorValueHexComplex = `#${Hexa3 | Hexa6 | Hexa8}`;
```

We cover all the use cases, but we faced another issue. We found that typescript put in memory all possible the possible values 
to evaluate a type. It meant to us 16^8=4,294,967,296 namely more than 4 billions ! So we had the _TS2590: Expression produces a union type that is too complex to represent_
error from our 16Gb RAM macs.

NB: Instead of doing an union type, we could have done a type Range using tail recursion instead of writing the number and letters one by one. Here is an example of Range type:

```typescript
type Range<N extends number, Acc extends Array<number> = []> = (Acc['length'] extends N ? Acc : Range<N, [...Acc, Acc['length']]>);
type NumberRange = Mapped<9>[number];
```

However, we kept the previous one mainly for readability purposes (the unions types are quite small). 

## Conclusion

Finally, we came up with the first one. Pushing it into the last solution allowed us to reach the limit of typescript and learn about how
typescript runs under the wheel.
So until big changes in typescript, we advice that the best way to type an hex color is to use following type: 

```typescript
export type ColorValueHex = `#${string}`;
```
start small
Tags: start, small
Published: 2023-02-06 16:42:25

I've been not reading nor writing for a year. No excuses, I had plenty of time to do so even during heavy work load and babysitting. I had to start small, nope, I had to start tiny, nano. 

It is always never late. My time and availability will get worse, never get better. Thus I will have to start now. Regrets are rubbish. Not worth a penny. Every day is a new fresh chance to star over. I do not have more than 24 hours a day, so therefore I have to focus **TODAY** only. 

Let's stay simple. Go forward. Do not look back. 
I have to manage very tiny things a day. One at a time. Get away from lists of lists of todo actions.
react-webcam + TypeScript
Tags: react, typescript, camera, webcam
Published: 2023-02-06 16:38:42

react-webcam allows you to implement camera shooting functionality in your React app.
[](https://www.npmjs.com/package/react-webcam)
{% codesandbox https://codesandbox.io/embed/camera-typescript-forked-bigb7u?fontsize=14&hidenavigation=1&theme=dark %}


Click [Start] in the above demo to start the camera. If you are asked for camera shooting permission, please allow it. (We do not send the captured data to the outside)

Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the end of camera shooting, and [Capture] on the lower left is the button to capture the captured image.

Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the button to end the camera shooting, and [Capture] on the lower left is the button to capture the captured video.

When capturing, the capture of the captured video was displayed.

```javascript 
import { useRef, useState, useCallback } from "react";
import Webcam from "react-webcam";
import "./styles.css";

const videoConstraints = {
  width: 720,
  height: 360,
  facingMode: "user"
};

export const App = () => {
  const [isCaptureEnable, setCaptureEnable] = useState<boolean>(false);
  const webcamRef = useRef<Webcam>(null);
  const [url, setUrl] = useState<string | null>(null);
  const capture = useCallback(() => {
    const imageSrc = webcamRef.current?.getScreenshot();
    if (imageSrc) {
      setUrl(imageSrc);
    }
  }, [webcamRef]);

  return (
    <>
      <header>
        <h1>camera app</h1>
      </header>
      {isCaptureEnable || (
        <button onClick={() => setCaptureEnable(true)}>start</button>
      )}
      {isCaptureEnable && (
        <>
          <div>
            <button onClick={() => setCaptureEnable(false)}>end </button>
          </div>
          <div>
            <Webcam
              audio={false}
              width={540}
              height={360}
              ref={webcamRef}
              screenshotFormat="image/jpeg"
              videoConstraints={videoConstraints}
            />
          </div>
          <button onClick={capture}>capture</button>
        </>
      )}
      {url && (
        <>
          <div>
            <button
              onClick={() => {
                setUrl(null);
              }}
            >
              delete
            </button>
          </div>
          <div>
            <img src={url} alt="Screenshot" />
          </div>
        </>
      )}
    </>
  );
};

```


- getScreenshot():You can use the Webcam imported by import Webcam from "react-webcam" for the type of still image data acquired by

- getScreenshot():The still image data obtained by <img> can be displayed on the screen by specifying it as it is in the src property.
Paracetamol.ts💊| #05: Explica este código TypeScript
Tags: typescript, programming, spanish, webdev
Published: 2023-02-06 16:25:35

## **<center>Explica este código TypeScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark> </center>

```ts
function add(x: number | string, y: number | string) {
  if (typeof x === 'number' && typeof y === 'number') return x + y;
  if (typeof x === 'string' && typeof y === 'string') return x.concat(y);
  throw new Error('Parameters must be numbers or strings');
}
console.log(add('one', 'two'));  //🤔
console.log(add(1, 2));          //🤔
console.log(add('one', 2));      //🤔
```

- A. `TypeError`, `"12"`, `undefined`
- B. `"onetwo"`, `3`, `Uncaught Error: Parameters must be numbers or strings`
- C. `"onetwo"`, `"12"`, `null`
- D. `Ninguno de los anteriores`

Respuesta en el primer comentario.

---