teleren/devto huggingface dataset:
Embarking on a React Adventure? First, Master These 5 JS concepts! 🚀
Published: 2023-08-21 07:36:59

So you decided to dive into the world of React, a library used by millions of people and promises to make building user interfaces a breeze. 

Before building your first to-do list, you might want to master some JavaScript concepts first. Here are five fundamental JavaScript concepts you should master before venturing into React:

## 1. Unveiling the DOM Magic:

Understanding the Document Object Model (DOM) is key to comprehending React's significance. The DOM represents the structure of a web page as a tree of objects, allowing developers to interact with webpage elements using JavaScript. Think of the DOM as a virtual representation of your webpage's content. It takes all those HTML tags, CSS styles, and JavaScript interactions and turns them into a cohesive performance. 

React operates in harmony with the DOM. Updating a React component triggers a process that reconciles the virtual DOM (a lightweight representation of the actual DOM) with the real DOM. This ensures that only the necessary parts of the page are updated, making your applications efficient and responsive.

## 2. The Dance of the Component Lifecycle

React components have a lifecycle consisting of different stages, from initialization to rendering, updating, and unmounting. Each stage presents opportunities to perform actions, such as fetching data, updating the state, and cleaning up resources.

With the introduction of React hooks in versions 16.3 and later, lifecycle methods have been augmented by hooks like useState and useEffect. These hooks simplify state management and side effect handling within components.


## 3. Casting ES6+ Charms

Beneath every React component, there is a foundation of modern JS concepts. Some valuable reads will be Arrow functions, Destructuring, Classes, and Modules. Don't forget to master your basics about `const` and `let` which gives you better control of your variables.

## 4. State and props sorcery

The heartbeat of React components is definitely their state and props.
- State: You can manage your local, mutable data within a component. Changing the state triggers powerful re-rendering spells that breathe life into your UI.
- Props: These flow from parent to child components, allowing them to communicate harmoniously.

## 5. JavaScript Tooling: Your Wizard's Toolkit

Modern web development relies on various tools and libraries. Familiarize yourself with essential tools like:

- Node.js and npm/yarn: Package managers for installing and managing dependencies.
- Webpack or Parcel: Bundlers that optimize assets for production.
- Babel: A transpiler for writing modern JavaScript that is compatible with various browsers.
Creating Salesforce aura component
Tags: salesforce
Published: 2023-08-21 07:21:08

Salesforce Aura Components provide a powerful framework for building dynamic and responsive user interfaces within the Salesforce platform. In this tutorial, we'll walk you through the process of creating a 5-minute read Aura Component, perfect for displaying quick and informative content to your users. By the end of this tutorial, you'll have a functional Aura Component that you can integrate into your Salesforce org.


## Prerequisites
:

Basic understanding of Salesforce development.
Salesforce Developer Edition or Sandbox environment.

**Step 1: Set Up Your Development Environment
**

- 
Log in to your Salesforce Developer Edition or Sandbox environment.

- 
Navigate to the "Developer Console" under the "Developer Console" tab.

- 
Click on "File" > "New" > "Aura Component".

- 
Name your component "FiveMinuteRead" and choose the appropriate target folder.

Step 2: Designing the Aura Component

Open the newly created "FiveMinuteRead" component in the Developer Console.
Replace the default code with the following code snippet:

```
<aura:component>
    <aura:attribute name="title" type="String" default="Title" />
    <aura:attribute name="content" type="String" default="Content goes here." />

    <div class="container">
        <h2 class="title">{!v.title}</h2>
        <div class="content">{!v.content}</div>
    </div>
</aura:component>
```
Step 3: Styling the Aura Component

Create a CSS file (e.g., "FiveMinuteReadStyle.css") to style the component.
Add the following CSS code to style the component:

```
.THIS .container {
    border: 1px solid #ccc;
    padding: 10px;
    margin: 10px;
    border-radius: 5px;
    background-color: #f9f9f9;
}

.THIS .title {
    font-size: 18px;
    margin-bottom: 10px;
}

.THIS .content {
    font-size: 14px;
    color: #555;
}

```
Step 4: Implementing the Aura Component

Navigate back to your "FiveMinuteRead" component in the Developer Console.
Under the <aura:component> tag, include the following line to link the CSS file:

```
<ltng:require styles="{!$Resource.FiveMinuteReadResource + '/FiveMinuteReadStyle.css'}" />

```

Step 5: Using the Aura Component

Create a new Lightning App Page by navigating to "App Builder" and creating a new Lightning Page.
Drag and drop the "FiveMinuteRead" component onto the Lightning Page.
Customize the component attributes such as the title and content.
Save and activate the Lightning Page.

Conclusion:

In just a few simple steps, you've created a dynamic and responsive  read Aura Component in Salesforce. This component can be easily customized and integrated into your Salesforce org to provide quick and informative content to your users. With the flexibility of Aura Components, the possibilities for enhancing your user experience are virtually endless. Happy coding!
Находки по разработке 2
Tags: news, javascript, python, php
Published: 2023-08-21 07:17:39

## Прикол недели 

Звездочки на Гитхабе можно купить

{% embed https://twitter.com/ThePrimeagen/status/1691852299449033133
 %}

## codelimit - новый Python линтер 

Делает одну простую вещь - считает длину строк

{% embed https://github.com/getcodelimit/codelimit %}

## Пыха выглядит хорошо

Датаклассы, паттерн матчинг - кайф

{% embed https://twitter.com/brendt_gd/status/1690606737118642176 %}
{% embed https://twitter.com/brendt_gd/status/1690955334020366336 %}

Чел крутой, чисто пхп приколы постит

## Скоро [Bun](https://bun.sh/) 1.0 выйдет

Уже сейчас можно гонять тесты быстрее чем в Vitest и Jest

{% embed https://twitter.com/jarredsumner/status/1692267817339609180 %}

## Неплохая статья про бранчевание и пулл реквесты

Пушим все в мастер и лучше кодить парно или в команде (mob programming называется) - жаль что я один 💀

https://craftbettersoftware.com/p/the-best-git-branching-strategy

## knip - топ-темка для чистоты js-проекта

Ищет неиспользуемый стафф, типа зависимостей, импортов - на питон бы такое

{% embed https://github.com/webpro/knip %}

## alpinejs - хорошее дополнение htmx

Это когда надо добавить реактивности, когда у тебя вместо фронтенда серверный html-шаблонизатор (типа той же джанги)
https://alpinejs.dev/

{% embed https://twitter.com/ThePrimeagen/status/1692533505526272026 %}

## PyScript - норм альтернатива шаблонизаторству

Можно писать на питоне сразу взаимодействуя с документом

https://pyscript.net/ 
https://pyscript.com/@07924187-45b9-4482-97a0-94ee74d0ae48/your-info/latest

## [SkeletonUI](https://www.skeleton.dev/) - Svelte-UI кит на базе TailwindCSS

Это то чего не хватает Svelte, а то уже у next есть shadcn, у nuxt - nuxtui

{% embed https://twitter.com/SkeletonUI/status/1691495875757875201 %}

Хотя есть [daisyui](https://daisyui.com/) - который вообще фреймворк агностик 🤔
 
Хотя уже и [shadcn на svelte портанули](https://www.shadcn-svelte.com/) - в какое замечательное время живем
 
{% embed https://twitter.com/huntabyte/status/1692391552209830086 %}

## Новый пост от батьки Фаулера 

Про то как совмещать TDD и AI-coding

{% embed https://twitter.com/martinfowler/status/1692250553647018184 %}
My npm package for simple state management in React
Tags: showdev, javascript, typescript, npm
Published: 2023-08-21 07:01:19

Welcome dev community!

Today I would like to introduce you to my npm package, which can be useful for any beginner or advanced JavaScript developer.

To check it out, just install it quickly and easily via npm

```sh
$ npm install react-atomize-store
# or
$ yarn add react-atomize-store
```

A lightweight state management library that simplifies state handling in your applications. Easily manage and update your app's state with minimal code. With built-in support for IndexedDB, it provides a seamless way to persist your state, making it perfect for storing login tokens or other sensitive information securely.

Only two lines to begin with and already on the entire application you can use your state.
```js
import { useAtom } from "react-atomize-store";
const App = () => {
  const [count, setCount] = useAtom("count");
}
```

Best of all, it also works with React DevTools, where you can enable or disable it from the user's need.

```js
import { useStore } from "react-atomize-store";

const App = () => {
  useStore(
    {
      count: 0,
      username: "adam",
      feeds: [],
      keypair: {},
    },
    true, // enable Redux DevTools
    ["keypair"] // atoms to store in IndexedDB
  );

  return <div>App</div>;
};
```

There's even no need to add a useStore if you don't need to modify default values and settings, because useAtom already works by itself on your entire React application.

```js
import { useAtom } from "react-atomize-store";

const Dashboard = () => {
  const [feeds, setFeeds] = useAtom("feeds");
  const [count, setCount] = useAtom("count");

  // Adding a new item to the 'feeds' array
  setFeeds((prev) => [...prev, feed]);

  // Overwriting the 'feeds' array with an empty array
  setFeeds([]);

  // Removing an element from the 'feeds' array
  setFeeds((prev) => prev.filter((item) => item.id !== feedId));

  setCount((prev) => prev + 1);

  console.log(feeds, count);

  return <div>Dashboard</div>;
};
```

{% github skorotkiewicz/react-atomize-store no-readme %}

I invite you to test and write a few opinions what you think about the package.
I will gladly accept PR!
How to add router progress bar in Next Js 13
Tags: nextjs, webdev, route, progress
Published: 2023-08-21 06:51:28

![route change progress bar example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpiwjynqw0zvnk9jb7rl.gif)

## Getting Started

If you've found yourself struggling to implement a reliable router progress bar for your Next.js 13 project, don't worry – I've got a straightforward solution for you. Many of the existing packages for creating a route change progress bar became ineffective with Next js App route. But after some extensive searching, I stumbled upon a fantastic option that not only works flawlessly but is also incredibly simple to integrate.

Assuming you already have your Next.js app or website project set up, the first step is to install the nextjs-toploader package. This package will be the key to achieving the progress bar functionality you're looking for.

```bash
npm i nextjs-toploader
```
Or

```bash
yarn add nextjs-toploader
```

### In app/layout.js
Import the `NextTopLoader` component from the `nextjs-toploader`. And place the `NextTopLoader` component right above the `{children}` content, ensuring it's within the `<body>` of the JSX structure.

```jsx
import NextTopLoader from 'nextjs-toploader';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <NextTopLoader />
        {children}
      </body>
    </html>
  );
}
```

### Customization
Customize the router progress bar to your preferences is simple. Just add the desired props to the `NextTopLoader` component:

```jsx
<NextTopLoader
  color="#2299DD"
  initialPosition={0.08}
  crawlSpeed={200}
  height={3}
  crawl={true}
  showSpinner={true}
  easing="ease"
  speed={200}
  shadow="0 0 10px #2299DD,0 0 5px #2299DD"
/>
```

These props gives you control over various aspects, from color and animation speed to visual effects. Feel free to experiment and create a progress bar that aligns perfectly with your Next.js 13 project.


I hope the information provided here proves valuable in enhancing your Next.js 13 project. Adding a route change progress bar to your Next.js 13 project through the `nextjs-toploader` package is both easy and effective. If you have any further questions or need assistance, don't hesitate to reach out.

Happy coding!
how to split list In python every [n] number
Tags: python, coding, programming
Published: 2023-08-21 06:46:22

{% embed https://www.youtube.com/watch?v=f4Lhh5CMTlk %}

## code 

```python

def every(arr, every_num):
	new_list = []
	for i in range(0, len(arr), every_num):
		new_list.append(arr[i: i + every_num])

	return new_list


mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = every(mylist, 4)
print(result)

```
How to Use Absolute Paths For Module Imports in Angular
Published: 2023-08-21 06:40:46

Many of us feel confused while we need to import module which is not in the same folder or near by. To make this task easier, We can make the path absolute so that we do not need to worry about path.

From long time, I was feeling need of a solution which could resolve the problem of importing module available in nested folder. Recently I found a way to resolve it which I am going to share with you, It's very easy and quick.

Let's say we have to use the service class inside any component which is available in nexted folder then the import statement will look like below:

``````import { ReferralService } from '../../../../../_services/referral.service';``````

Such imports are too long, hard to maintain and very annoying in bigger projects. So now I follow the latest approach to perform the same task. Now let's move to the solution part.

open your tsconfig.json file(in some version of angular you can find tsconfig.base.json also, open this instead). Inside compiler option make sure you have below settings:

``````"compilerOptions": {

  ...

  "baseUrl": "./",

  ...

 
}``````

If the baseUrl is same then now you can define your own absoulte path as many as you want. In our case, since we are trying to change the path for the environment then add the below line into compilerOption inside tsconfig.json file.

``````"compilerOptions": {

  ...

  "baseUrl": "./",

  "paths":{

   "@services/*": ["src/app/_services/*"],

  }

  ...

 
}``````

Now from any part of the application why not it's at availabe the the most nested folder, any service class can be imported using below statement.

``````import { ReferralService } from '@services/referral.service';``````

In the above line we have mapped the './src/app/_services' with @services, Here @ symbol is not mendatory. And the best thing is that, We can define any number of absolute path as per the requirement in our application.

 

**Conclusion**

Using absolute path in the angular app makes our code clean, easy to read, and easy to maintain.

I hope this article helped you to improve your coding in Angular. You can also find other demos/articles at [Angular Sample Projects](https://jsonworld.com/blog/how-to-use-absolute-paths-for-module-imports-in-angular) here to start working on enterprise-level applications.

Let me know your thoughts over email **pankaj.itdeveloper@gmail.com.** I would love to hear them and If you like this article, share it with your friends.

Thanks!

This article is originally posted over [jsonworld](jsonworld.com)
Postgresql C Unit testing
Tags: postgres, database, testing
Published: 2023-08-21 06:28:16

## Introduction

Unit testing is a crucial aspect of software development that allows developers to verify the correctness of their code and catch bugs early in the development process. When it comes to PostgreSQL C Extensions, unit testing becomes essential to ensure the reliability and stability of the extensions. In this blog post, we will explore how to set up and perform unit testing for PostgreSQL C Extensions.


## Setting up the Unit Testing Framework

To get started with unit testing for PostgreSQL C Extensions, follow these steps:

1. Create a new directory for your unit tests within your PostgreSQL extension project. For example, you can create a directory named `tests`.

2. Inside the `tests` directory, create a new C source file (e.g., `test_extension.c`) that will contain your unit tests.

3. Include the necessary headers in your `test_extension.c` file. This includes the CUnit headers and the headers specific to your extension that you want to test.

4. Define the test functions using the CUnit framework. Each test function should contain the necessary setup, execution, and assertion logic to validate a specific aspect of your extension's functionality.

5. Implement the test functions to exercise the functionalities of your extension. Use the CUnit assertion macros to check if the actual results match the expected results.

6. Create a test suite that groups related test functions together. This allows you to organize your tests and execute them as a cohesive unit.

7. In the main function of your `test_extension.c` file, initialize the CUnit framework, create the test suite, and add the test functions to the suite.

8. Run the unit tests by executing the compiled test executable. Ensure that the PostgreSQL server is running and that your extension is installed and loaded.



## Compiling and Running Unit Tests

To compile and run the unit tests, follow these steps:

1. Compile the unit test source file (`test_extension.c`) and link it with the necessary libraries and header files. 
Make sure to include the CUnit library and the headers specific to your PostgreSQL extension.


2. Run the compiled unit test executable. 
Ensure that your PostgreSQL server is running and that your extension is installed and loaded.


## Conclusion

Unit testing is a vital aspect of PostgreSQL C Extension development. By setting up a unit testing framework and writing comprehensive tests, you can ensure the correctness and robustness of your extensions.

Remember, unit testing is an iterative process. 
As you develop and enhance your PostgreSQL C Extension, it's essential to continuously update and expand your unit tests to cover new functionalities and edge cases. This will help catch regressions and ensure the overall quality of your extension.

By investing time and effort into unit testing, you can improve the reliability, maintainability, and overall user experience of your PostgreSQL C Extensions.
Manager Handbook for Distributed AntDB-T - P17
Tags: database
Published: 2023-08-21 06:20:50

## Modify parameters

The global parameters ofdoctor are modified by the commandset doctor, and the meaning of the parameters is as follows:

• enable: General switch, 1 is on, 0 is off. The default is 0.

• forceswitch: Whether to force the switch on the abnormal node, 1 is yes, 0 is no, default is 0.

• switchinterval: The longest time to self-heal again after the last self-healing failure, default is 30s.

• nodedeadline: The longest time to self-heal after node failure, default is 30s.

• agentdeadline: The maximum time for self-healing after agent process failure, default is 5s.

The command to modify the parameters is as follows:

```
set doctor (switchinterval=10);  
set doctor (nodedeadline=10);  
set doctor (forceswitch=1);  
```
After the modification is completed, check whether it takes effect:

```
postgres=# list doctor;  
 type  |  subtype  |  key  | value |  comment   
-----------+-----------------+----------------+-------+--------------------------------------------------------------------------------------------------------------  
 PARAMETER | --  | enable  | 1  | 0:false, 1:true. If true, doctor processes will be launched, or else, doctor processes exit.  
 PARAMETER | --  | forceswitch  | 1  | 0:false, 1:true. Whether force to switch the master/slave, note that force switch may cause data loss.  
 PARAMETER | --  | switchinterval | 10  | In seconds, The time interval for doctor retry the switching if an error occurred in the previous switching.  
 PARAMETER | --  | nodedeadline  | 10  | In seconds. The maximum time for doctor tolerate a NODE running abnormally.  
 PARAMETER | --  | agentdeadline  | 5  | In seconds. The maximum time for doctor tolerate a AGENT running abnormally.  
 NODE  | gtmcoord master | gcn1  | t  | enable doctor  
 NODE  | gtmcoord slave  | gcn2  | t  | enable doctor  
 NODE  | coordinator  | cn1  | t  | enable doctor  
 NODE  | coordinator  | cn2  | t  | enable doctor  
 NODE  | coordinator  | cn3  | t  | enable doctor  
 NODE  | datanode master | dn1_1  | t  | enable doctor  
 NODE  | datanode master | dn2_1  | t  | enable doctor  
 NODE  | datanode master | dn3_1  | t  | enable doctor  
 NODE  | datanode slave  | dn1_2  | t  | enable doctor  
 NODE  | datanode slave  | dn1_3  | t  | enable doctor  
 NODE  | datanode slave  | dn2_2  | t  | enable doctor  
 NODE  | datanode master | dn4_1  | t  | enable doctor  
 NODE  | coordinator  | cn4  | t  | enable doctor  
 NODE  | datanode slave  | dn3_2  | t  | enable doctor  
 NODE  | datanode slave  | dn4_2  | t  | enable doctor  
HOST | -- | adb01 | t | enable doctor 
HOST | -- | adb02 | t | enable doctor 
(22 rows) 
```
Weekly Challenge 230
Tags: perl, python, theweeklychallenge
Published: 2023-08-20 08:03:43

Each week Mohammad S. Anwar sends out [The Weekly Challenge](https://theweeklychallenge.org/), a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-230/), [My solutions](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-230/sgreen)

## Task 1: Separate Digits

### Task

You are given an array of positive integers.

Write a script to separate the given array into single digits.

### My solution

Two relatively straight forward tasks this week, so doesn't really need much explanation. For this task I can treat the integers as strings. Iterating a string will produce the individual characters. I then use a double `for` loop to flatten this to a single list.

```python
solution = [ digit for i in ints for digit in i]
```

In Perl, I use the `split` method to get the individual digits of the number, and map to achieve this for all numbers.

```perl
my @solution = ( map { split // } @ints );
```

### Examples

```bash
$ ./ch-1.py 1 34 5 6
(1, 3, 4, 5, 6)

$ ./ch-1.py 1 24 51 60
(1, 2, 4, 5, 1, 6, 0)
```

## Task 2: Count Words

### Task

You are given an array of words made up of alphabetic characters and a prefix.

Write a script to return the count of words that starts with the given prefix.

### My solution

For this task, I pop the last item of the list, and assign this to the `prefix` variable. I then use the startswith() method on the string to count the number of words that start with the prefix.

```python
solution = sum(1 for word in words if word.lower().startswith(prefix.lower()))
```

For the Perl solution, we can use the `grep` function to find words that start with the prefix.

```perl
    my @solution = grep { substr( lc $_, 0, $len ) eq lc($prefix) } @words;
```

### Examples

```bash
$ ./ch-2.py pay attention practive attend at
2

$ ./ch-2.py janet julia java javascript ja
3
```