teleren/devto huggingface dataset:
Strings
Tags: swift, javascript, 100daysofcode
Published: 2023-08-20 07:57:02

## Strings


### 1️⃣ Declaration

#### Javascript

```js
// Both Single and Double quotes are OK to create strings in JS
var string1 = "Hello Js!!" ✅
var string2 = 'Hello Js!!' ✅

```
#### Swift

```swift
// Only Double quotes are OK to create strings in JS
var string1 = "Hello Js!!" ✅
var string2 = 'Hello Js!!' ❌ 
```

### 2️⃣ Length

#### Javascript

```js

"Hello world!!".length // 13 (counts empty spaces too)

```
#### Swift

```swift
"Hello world!!".count // 13 (counts empty spaces too)
```

### 3️⃣ Case Transformation

#### Javascript

```js

"Hello world!!".toLowerCase() // hello world!!
"Hello world!!".toUpperCase() // HELLO WORLD!! 

```
#### Swift

```swift
"Hello world!!".lowercased() // hello world!!
"Hello world!!".uppercased() // HELLO WORLD!! 
```

### 4️⃣ Template literals

#### Javascript

```js
const name = "Krishna"

const message = `Hello there, i am ${name}.`
```
#### Swift

```swift
let name = "Krishna"

let message = "Hello there, i am \(name)."
```

### 5️⃣ Split

#### Javascript

```js
var string = "Hello world!!"

string.split("")
```
#### Swift

```swift
var string = "Hello world!!"

string.split(separator: "")
```


### 6️⃣ Multi-line strings

#### Javascript

```js
// most used way
var string = `
A long time ago 
in a galaxy far far away
javascript is being used for coding`

```
#### Swift

```swift
// """ are always to be alone
var string = """
A long time ago 
in a galaxy far far away
Swift is being used for coding
"""
```

### 7️⃣ Concatination

#### Javascript

```js

var string = "Hello"
var string2 = 'world'

var string3 = string + string2 // string.concat(string2)
```
#### Swift

```swift
var string = "Hello"
var string2 = 'world'

var string3 = string + string2
```

### 8️⃣ Typecasting

#### Javascript

```js

var someNumber = 12345

var asString = String(someNumber) // -OR- someNumber.toString() -OR- `${someNumber}`
```
#### Swift

```swift
var someNumber = 12345

var asString = String(someNumber) // -OR- '\(someNumber)'
```

_More examples are added on the go_
JS dev learning Swift
Tags: javascript, swift, 100daysofcode
Published: 2023-08-20 07:39:50

I've always had a strong desire to create useful applications that could assist people in various aspects of their lives, both in their work and personal activities. While I did start working on these [ideas](https://www.producthunt.com/@sarath_damaraju)  a while ago, my efforts took a backseat due to my busy work schedule in the past few years. However, I am now determined to wholeheartedly commit myself to developing these practical applications once again.

Recently, I've been exploring Electron.js as a platform for building these apps, but I've encountered some challenges that don't seem worth the effort, especially at the early stages of development. Because of this, I'm considering exploring alternatives beyond JavaScript. I'm particularly interested in creating apps using native programming languages. To start off on this journey, I've decided to learn Swift.

**My take-aways from this journey are:-**

🎯 To expand my skills by learning new programming languages and tools outside the realm of JavaScript.

🎯 To create applications that I personally find valuable and would love to use on a daily basis.


And finally, the primary objective of this series is to provide a side-by-side comparison of the syntax and code structures used in JavaScript and Swift. The intention is to create a handy "Cheat Sheet" that individuals can refer to for quick guidance.

_[This article is written by me and modified with help of chat-gpt]_
How to fetch Rank Math sitemap from WordPress and show it in Next.js
Tags: nextjs, wordpress, rankmath, webdev
Published: 2023-08-20 07:36:33

In this blog I will guide you how you can fetch the sitemaps from WordPress and show it in Next.js .
When migrating from WordPress to Next.js we face issues while generating sitemaps because WordPress does not provide any rest api for us to get the posts , pages, categories links in a systematic format.
In WordPress we use some plugins to generate the sitemaps, one of that plugin is RankMath.

The RankMath plugin create separates routes for XML sitemaps,

```
/sitemap_index.xml
/post-sitemap.xml
/page-sitemap.xml
/category-sitemap.xml
```

In Next.js we will use the `getServerSideProps` function to fetch these sitemaps on the server

Let's begin


- Download the static files from [github link](https://github.com/sarthak090/rankmath-stylesheets/tree/main)

- Edit Files in the sylesheets and add your name and url at required places.

- Save these files to `public` directory.

- In `.env` file add NEXT_PUBLIC_WP_CMS_URL variable and make it equal to `your_wordpress_site_url.com`

- Create a file in the directory called `pages/sitemap/[slug].tsx`.

Now in the `sitemap/[slug].tsx` enter the following codes.

```tsx
 

import { GetServerSideProps } from "next";

export default function Sitemap( ) {
  return (
    <>
      
    </>
  );
}

export const getServerSideProps: GetServerSideProps = async ({
  res,
  params,
}) => {
  const { slug } = params!;
 
  if (slug && slug.includes(".xml")) {
    const url = process.env.NEXT_PUBLIC_WP_CMS_URL + `/${slug}`;
    

    const resp = await fetch(url).then((r) => r.text());

    let format = resp
      .replace(`//www.your_wordpress_site.com/news-sitemap.xsl`, "/v.xsl")
      .replace("//www.your_wordpress_site.com/main-sitemap.xsl", "/main-sitemap.xsl")
      .replace(
        "//www.your_wordpress_site.com/video-sitemap.xsl",
        "/video-sitemap.xsl"
      )
 
      .replaceAll(`www.your_wordpress_site.com.com`, "www.your_next_js_site.com")
      
 
    res.setHeader("Content-Type", "text/xml");

    res.write(format);
    res.end();

    return {
      props: {},
    };
  } else {
     return {
        props: { },
        notFound:true
      };

      
  }
};

```

I hope this helps if you get stuck at any place let me know , I would love to help you.
Breadth First Search
Published: 2023-08-20 07:21:15

from queue import Queue

class Graph(): 
    def __init__(self, vert):
        self.Vertices = vert
        self.graph = [[0 for column in range(vert)] for row in range(vert)]
        
    def isValid(self, v, colour, c):
        for i in range(self.Vertices):
            if self.graph[v][i] == 1 and colour[i] == c: 
                return False
        return True

    def isKColorableBFS(self, k):
        for start_vertex in range(self.Vertices):
            visited = [False] * self.Vertices
            queue = Queue()
            queue.put(start_vertex)

            # At first, creating a color array to keep track of assigned colors
            color = [-1] * self.Vertices
            color[start_vertex] = 0

            while not queue.empty():
                current_vertex = queue.get()

                for neighbor in range(self.Vertices):
                    if self.graph[current_vertex][neighbor] == 1 and visited[neighbor] == False:
                        visited[neighbor] = True
                        queue.put(neighbor)

                        # Checking if the neighbor is already colored with the same color
                        if color[neighbor] == color[current_vertex]:
                            return False

                        # Assigning an available color to the neighbor
                        if color[neighbor] == -1:
                            available_colors = set(range(k))
                            for i in range(self.Vertices):
                                if self.graph[neighbor][i] == 1 and color[i] != -1:
                                    available_colors.discard(color[i])
                            if len(available_colors) == 0:
                                return False
                            color[neighbor] = available_colors.pop()

        return True
        
if __name__ == "__main__":
    g = Graph(6)
   
    g.graph = [[0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0], [1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 1, 0]]
    
    k = 3
    
    if g.isKColorableBFS(k):
        print("The graph is", k, "-colorable.")
    else:
        print("The graph is not", k, "-colorable.")
I am getting the wrong output i.e. 'The graph is not 3 colorable' . Can someone help me to get correct output and fix the error.
Extract audio meta data (album, artist, duration, etc) in Pyhton
Tags: python, coding, programming
Published: 2023-08-20 07:07:08

## Hi 🙂🖐

Welcome to a new post. Today I will share with you how to extract meta data from an audio file, such as album, artist, and more. To do this, I will use a library called **tinytag**, which is a library for reading the music meta data of most common audio files in pure Python.

## step 1

install tinytag from `pip install tinytag`

## step 2

```python

from tinytag import TinyTag

song = TinyTag.get('test.mp3')
print(song.album)
print(song.year)
print(song.artist)
print(song.duration)

```
You can use **`print(song.as_dict())`** to print all meta tags

**Note**
Some audio files do not have meta tags.

**Form more information about tinytag**

https://github.com/devsnd/tinytag


**Now we're done 🤗**

**Don't forget to like and follow 🙂**
How Do You Manage Your Schedule Effectively While Working Remotely?
Tags: discuss, carreer
Published: 2023-08-20 07:00:00

_This week we're chatting all things remote work, and we want to hear from you about your experiences, pros, cons, and advice for those transitioning or considering remote work options._

Let's dive into today's topic of conversation... 

> How do you structure your daily schedule to make the most of remote work flexibility?Share techniques for setting boundaries between work and personal life to avoid burnout and any time management tools or strategies do you find helpful in optimizing productivity?

Follow the DEVteam for more discussions and online camaraderie!

{% embed [https://dev.to/devteam](https://dev.to/devteam) %}
What is Optical fiber
Tags: internet, testdev, cse
Published: 2023-08-20 06:57:54

Optical fiber is a thin, flexible, and transparent strand made of glass or plastic that is used to transmit digital information in the form of light pulses. It's designed to carry data over long distances at incredibly high speeds by utilizing the principle of total internal reflection. This technology is widely used for high-speed internet connections, telephone networks, cable television, and other telecommunications applications due to its ability to transmit data with minimal signal loss and electromagnetic interference.
REST API using AWS SAM + AMPLIFY - Part 1
Tags: awssam, aws, serverless, tutorial
Published: 2023-08-20 06:52:09

# Introduction
This project is aimed at providing a comprehensive guide and structure to build a full-stack application using AWS Amplify and AWS Serverless Application Model (SAM). We leverage the powerful features of these services to create a scalable, secure, and easily maintainable web application.

The idea of this project is not to focus on the front end (UX/UI) design but rather on how to build an application using Amplify and AWS SAM.

## About the project
AWS Amplify enables developers to develop and deploy cloud-powered mobile and web applications. It includes a broad set of tools and services that can create scalable, full stack applications, with a focus on simplicity and ease of use.

AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications. It extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application.

The combination of Amplify and AWS SAM allows developers to rapidly build and scale applications without worrying about managing servers. This project provides a ready-to-use template to bootstrap your next full stack application.


---



## Project structure
The project is architecturally segmented into two principal components:


**Frontend, Powered by AWS Amplify:** The frontend is responsible for rendering user interfaces, managing user state, and facilitating interactions with backend resources. It is developed and managed through AWS Amplify. The interface features a tabular display of automobile information, enabling users to perform actions such as editing, saving, and deleting rows. Additionally, it offers a form component to facilitate the inclusion of new entries. [GitHub Repository for Frontend](https://github.com/Ethanlloyd21/amplify-sam-app)

![Full Stack CRUD App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksrwxl4vu18lnym1ujk6.png)

![Create, read, update, delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85uawow6ljybrs67insy.png)

---

**Backend, Orchestrated by AWS SAM:** This segment encompasses serverless functions via AWS Lambda, API endpoints through AWS API Gateway, and data storage using AWS DynamoDB. The backend supports comprehensive CRUD (Create, Read, Update, Delete) operations through a RESTful API. The architecture and management of this component are facilitated using AWS SAM. [GitHub Repository for Backend](https://github.com/Ethanlloyd21/amplify-sam-app-backend)


![rest api](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2xadju35bgawiv1w6ppg.png)

---

# Next [Part 2: Pre-requisites](https://dev.to/ethanlloyd21/getting-started-with-aws-sam-2ha2)

**_To use AWS SAM make sure these pre-requisites are completed._**


Skip this step if you already have an AWS account, and have both AWS CLI and AWS SAM installed on your computer.
[Move to Part 3!](https://dev.to/ethanlloyd21/amplify-aws-sam-part-3-create-react-github-4mh3)
A 股个股资金流 API 数据接口
Published: 2023-08-20 06:40:14

A 股个股资金流 API 数据接口

全量股票资金流数据，全量A股数据，最长30日历史数据

![gugudata_api_cover](https://static.gugudata.com/api_cover_stockcn_cashflow.png)

# 1. 产品功能

- 支持所有A股资金流数据查询；
- 每日定时更新数据；
- 支持多达 30 日历史数据查询；
- 超高的查询效率，数据秒级返回；
- 数据持续更新与维护；
- 全接口支持 HTTPS（TLS v1.0 / v1.1 / v1.2 / v1.3）；
- 全面兼容 Apple ATS；
- 全国多节点 CDN 部署；
- 接口极速响应，多台服务器构建 API 接口负载均衡；
- [接口调用状态与状态监控](https://www.gugudata.com/status)

# 2. API 文档

**接口详情:** [https://www.gugudata.com/api/details/stockcncashflow](https://www.gugudata.com/api/details/stockcncashflow)

**接口地址:** https://api.gugudata.com/stock/cn/stock-cash-flow

**返回格式:** application/json; charset=utf-8

**请求方式:** GET

**请求协议:** HTTPS

**请求示例:** https://api.gugudata.com/stock/cn/stock-cash-flow?appkey=YOUR_APPKEY&symbol=YOUR_VALUE

**数据预览:** [https://www.gugudata.com/preview/stockcncashflow](https://www.gugudata.com/preview/stockcncashflow)

**接口测试:** [https://api.gugudata.com/stock/cn/stock-cash-flow/demo](https://api.gugudata.com/stock/cn/stock-cash-flow/demo)

# 3. 请求参数

| 参数名 | 参数类型 | 是否必须 |   默认值    |        备注         |
| :----: | :------: | :------: | :---------: | :-----------------: |
| appkey |  string  |    是    | YOUR_APPKEY | 付费后获取的 APPKEY |
| symbol |  string  |    是    | YOUR_VALUE  | 股票代码，如 600036 |

# 4. 返回参数

|             参数名             | 参数类型 |                 备注                 |
| :----------------------------: | :------: | :----------------------------------: |
|     DataStatus.StatusCode      |   int    |            接口返回状态码            |
|  DataStatus.StatusDescription  |  string  |           接口返回状态说明           |
|  DataStatus.ResponseDateTime   |  string  |           接口数据返回时间           |
|   DataStatus.DataTotalCount    |   int    | 此条件下的总数据量，一般用于分页计算 |
|          Data.Symbol           |  string  |               股票代码               |
|         Data.StockName         |  string  |               股票名称               |
|          Data.DateKey          |  string  |     数据日期，格式为 2023-05-10      |
|           Data.Close           |  double  |                最新价                |
|       Data.ChangePercent       |  double  |                涨跌幅                |
|    Data.MainNetInflowAmount    |  double  |           主力净流入-净额            |
|    Data.MainNetInflowRatio     |  double  |          主力净流入-净占比           |
| Data.SuperLargeNetInflowAmount |  double  |          超大单净流入-净额           |
| Data.SuperLargeNetInflowRatio  |  double  |         超大单净流入-净占比          |
|   Data.LargeNetInflowAmount    |  double  |           大单净流入-净额            |
|    Data.LargeNetInflowRatio    |  double  |          大单净流入-净占比           |
|   Data.MediumNetInflowAmount   |  double  |           中单净流入-净额            |
|   Data.MediumNetInflowRatio    |  double  |          中单净流入-净占比           |
|   Data.SmallNetInflowAmount    |  double  |           小单净流入-净额            |
|    Data.SmallNetInflowRatio    |  double  |          小单净流入-净占比           |
A 股个股资金流排行 API 数据接口
Published: 2023-08-20 06:40:00

A 股个股资金流排行 API 数据接口

全量股票资金流排名，多时间区间，全量A股数据。

![gugudata_api_cover](https://static.gugudata.com/api_cover_stockcncashflowrank.jpg)

# 1. 产品功能

- 支持所有A股资金流数据查询；
- 每日定时更新数据；
- 支持多时间段查询；
- 超高的查询效率，数据秒级返回；
- 数据持续更新与维护；
- 全接口支持 HTTPS（TLS v1.0 / v1.1 / v1.2 / v1.3）；
- 全面兼容 Apple ATS；
- 全国多节点 CDN 部署；
- 接口极速响应，多台服务器构建 API 接口负载均衡；
- [接口调用状态与状态监控](https://www.gugudata.com/status)

# 2. API 文档

**接口详情:** [https://www.gugudata.com/api/details/stockcncashflowrank](https://www.gugudata.com/api/details/stockcncashflowrank)

**接口地址:** https://api.gugudata.com/stock/cn/stock-cash-flow-rank

**返回格式:** application/json; charset=utf-8

**请求方式:** GET

**请求协议:** HTTPS

**请求示例:** https://api.gugudata.com/stock/cn/stock-cash-flow-rank?appkey=YOUR_APPKEY&indicator=YOUR_VALUE

**数据预览:** [https://www.gugudata.com/preview/stockcncashflowrank](https://www.gugudata.com/preview/stockcncashflowrank)

**接口测试:** [https://api.gugudata.com/stock/cn/stock-cash-flow-rank/demo](https://api.gugudata.com/stock/cn/stock-cash-flow-rank/demo)

# 3. 请求参数

|  参数名   | 参数类型 | 是否必须 |   默认值    |                       备注                       |
| :-------: | :------: | :------: | :---------: | :----------------------------------------------: |
|  appkey   |  string  |    是    | YOUR_APPKEY |               付费后获取的 APPKEY                |
| indicator |  string  |    是    | YOUR_VALUE  | 时间指标，可选参数为：今日 ｜ 3日 ｜ 5日 ｜ 10日 |

# 4. 返回参数

|             参数名             | 参数类型 |                 备注                 |
| :----------------------------: | :------: | :----------------------------------: |
|     DataStatus.StatusCode      |   int    |            接口返回状态码            |
|  DataStatus.StatusDescription  |  string  |           接口返回状态说明           |
|  DataStatus.ResponseDateTime   |  string  |           接口数据返回时间           |
|   DataStatus.DataTotalCount    |   int    | 此条件下的总数据量，一般用于分页计算 |
|          Data.Symbol           |  string  |               股票代码               |
|         Data.StockName         |  string  |               股票名称               |
|          Data.Latest           |  double  |                最新价                |
|       Data.ChangePercent       |  double  |                涨跌幅                |
|    Data.MainNetInflowAmount    |  double  |           主力净流入-净额            |
|    Data.MainNetInflowRatio     |  double  |          主力净流入-净占比           |
| Data.SuperLargeNetInflowAmount |  double  |          超大单净流入-净额           |
| Data.SuperLargeNetInflowRatio  |  double  |         超大单净流入-净占比          |
|   Data.LargeNetInflowAmount    |  double  |           大单净流入-净额            |
|    Data.LargeNetInflowRatio    |  double  |          大单净流入-净占比           |
|   Data.MediumNetInflowAmount   |  double  |           中单净流入-净额            |
|   Data.MediumNetInflowRatio    |  double  |          中单净流入-净占比           |
|   Data.SmallNetInflowAmount    |  double  |           小单净流入-净额            |
|    Data.SmallNetInflowRatio    |  double  |          小单净流入-净占比           |
Beautiful background animation only with HTML and CSS
Tags: webdev, css, html, beginners
Published: 2023-08-20 06:38:44

## Preview
Have you ever wondered how people create those beautiful background shapes that are animated? Well, it is much easier than you think let's have a look at what I am talking about,

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

You see these look so beautiful in websites, making them look more eye-catching. They are animated so it's so cool!! isn't it?

> [Demo here](https://preetsuthar.me)

Let's create it then :)

## Get started
First of all head over to [this website](https://bgjar.com/animated-shape) 

![bgjar.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gohe7y4flhjbfbqr1u3.png)

You'll see something like this hover mouse over `Animated shapes` and then click on `Customize`

![Animated Shapes -> Customize](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bhxvikfp3igy4xj307x.png)


Now simply customize it as you wish to and don't forget to tick the `enable animations` option :)

Once you are done click on `get code` at the bottom and copy the SVG code

![Get SVG code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ew3npiw1so98w3whhyd.png)

## Coding Time :)

Once you copy the SVG code headover to your website code folder create a new file `nameOfTheFile.svg` you can name it whatever you want but don't forget to put `.svg` extension. Now in the same file paste the SVG code you copied!

Now head over to your main CSS file, In this file we'll set the background for the body.

`main.css`

```css
  background-image: url("/path/to/your/image.svg");
  background-repeat: no-repeat;
  background-size: cover;
```

And voila!! we're done!! enjoy some beautiful eye-catching animations in the body's background
Understanding Instances in Python
Published: 2023-08-20 06:30:41

Instances in Python play a crucial role in object-oriented programming (OOP). They allow us to create and work with objects based on the blueprint provided by a class. In this article, we'll explore various aspects of instances, including attributes, methods, creation, access, and calling.


## <u>1. Instance Attributes </u>

Instance attributes are variables defined within a class's methods, typically within the constructor method (__init__). They store data unique to each instance and are accessed using the self keyword.
_Example:_

```
class Car:
    def __init__(self, make, model, year):
        # Instance attributes
        self.make = make
        self.model = model
        self.year = year
```

## <u>2. Instance Methods </u>
Instance methods are functions within a class designed to perform actions specific to instances. They take the 'self' parameter as their first argument, representing the instance itself.

_Example:_

```
class Car:
    # ...
    
    # Instance method
    def start_engine(self):
        print(f"{self.year} {self.make} {self.model}'s engine is now running.")

    # Instance method
    def stop_engine(self):
        print(f"{self.year} {self.make} {self.model}'s engine is now stopped.")
```

##<u>3. Creating Instances </u>

To create instances, we use the class as a blueprint. Each instance will have its own set of attributes and methods defined by the class.

_Example:_

```
# Creating instances of the Car class
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Ford", "Mustang", 2022)
```

##<u> 4. Accessing Instance Attributes </u>

To access instance attributes, we use the variable name followed by a dot and the attribute name.

_Example:_

```
print(f"{car1.year} {car1.make} {car1.model}")
print(f"{car2.year} {car2.make} {car2.model}")
# Output:
# 2020 Toyota Camry
# 2022 Ford Mustang
```

##<u>5. Calling Instance Methods </u>

To call instance methods, we use the variable name, followed by a dot, the method name, and parentheses.

_Example:_

```
car1.start_engine()  # Start the engine of car1
car2.start_engine()  # Start the engine of car2
car1.stop_engine()   # Stop the engine of car1
car2.stop_engine()   # Stop the engine of car2

```
In conclusion, understanding instances in Python is fundamental to working with objects and classes in OOP. Instances allow us to create, customize, and interact with objects, making our code more organized and modular.