teleren/devto huggingface dataset:
用 Google Apps Script，定時從 GitHub、GitLab 取出備份檔並匯入 Postman
Tags: postman, github, gitlab, tutorial
Published: 2023-08-18 14:04:35

## 本篇要解決的問題

在上一篇〈[用 Postman Integrations，自動備份 Postman Collection](https://www.letswrite.tw/postman-integrations-backup/)〉我們已經做到當 Postman 的 Collection 有更新時，自動備份到 GitHub 上，接著這篇是來筆記如何將這些備份檔，定期匯入到另外的 Postman 帳號上，也算是一種二個 Postman 帳號可以彼此同步的方法。

---

## 取得 Access Token

### GitHub

取得 GitHub Access Token 的步驟在上一篇的筆記文就寫過了，本段不再重覆寫，可見上篇「[建立 GitHub 專案及 Access Token](https://www.letswrite.tw/postman-integrations-backup/#%e5%bb%ba%e7%ab%8b-github-%e5%b0%88%e6%a1%88%e5%8f%8a-access-token)」。

### GitLab

點擊 [GitLab 存取憑證](https://gitlab.com/-/profile/personal_access_tokens) 頁面。

點擊「新增令牌」：

![點擊 新增令牌](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ajs7zp2cdqe2gb736mpn.png)

令牌名稱：取一個自己記得住是做什麼用的。

到期時間：刪掉給**空值**，可以存活約一年。

選取範圍：勾選 **api**。

![填寫令牌資訊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkbpr3rjjd9e2k7ns8ou.png)

選好、勾好後，按下「建立 個人存取令牌」，就會看見成功的訊息：

![建立個人存取令牌成功](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcvahzl44n8iepm2n6cw.png)

記得按下複製的按鈕，將令牌存起來，後續的程式碼會用到。

---

## 建立 Postman API Key

打開要匯入 Collections 的 Postman，右上角點擊自己的頭像，接著點擊 **Settings**：

![點擊 Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0sovoq6kuy8g6mnxnpjf.jpg)

左側選單點擊 API keys，接著點擊右上角的 **Generate API Key** 的按鈕：

![點擊 Generate API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1tv34hi3pfrfq8pclao.png)

為 Token 取一個自己記得住是做什麼用的名字後，點擊 **Generate API Key**：

![再次點擊 Generate API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2gi0a3f0t171drn4ywuq.png)

就會看見 Postman 生成了一組 API Key：

![Postman API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/366e5qs9m4k3meonaq1o.png)

一樣按下複製的按鈕然後存起來，下一段寫程式碼會用到。

---

## 從 GitHub 上匯入 Postman Collections

這段的 GitHub 專案，跟下一段的 GitLab 專案，都要是從上一篇 [Postman Integrations](https://www.letswrite.tw/postman-integrations-backup/) 的方式備份 Collections，才有效。主要是資料夾的位置是用預設值，不然就要自己替換檔案路徑。

在 Google 雲端硬碟上新增一個 Google Apps Scripts 的檔案，取好檔名存檔後，程式碼複製貼上以下：

{% embed https://gist.github.com/letswritetw/260dfd44ca3a64523d633642ffe60cd5  %}

---

## 從 GitLab 上匯入 Postman Collections

在 Google 雲端硬碟上新增一個 Google Apps Scripts 的檔案，取好檔名存檔後，程式碼複製貼上以下：

{% embed https://gist.github.com/letswritetw/1b692e33aa3825055491f7e71c8a98e1 %}

---

## 設定排程

Google Apps Script 左側選單點擊 **觸發條件**：

![點擊 觸發條件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2bb5hj01ynskay7j80i.png)

就可以設定要多久時間自動執行一次函式，建議是不要設成每分鐘都執行，因為容易發生卡住的情形，設每 5 分鐘或每 10 分鐘執行一次比較穩定。
How to use LAG & LEAD FUNCTION in SQL SERVER 2008
Tags: sqlserver, sqlserver2008, lag, sqlserver2019
Published: 2023-08-18 14:02:16

The LAG and LEAD functions in SQL Server 2008 are powerful tools that allow you to access data from a previous or subsequent row in a result set. These functions can be extremely useful in various scenarios, such as calculating differences between consecutive rows or finding the next or previous value in a sequence. In this article, we will explore how to use the LAG and LEAD functions and demonstrate their capabilities.

Using the LAG Function
----------------------

The LAG function allows you to access data from a previous row in a result set. It takes three arguments: the column you want to retrieve data from, the number of rows to go back, and the default value to return if the desired row is not available.

Let's say we have a table called `Employees` with columns `EmployeeID`, `FirstName`, and `LastName`. We want to retrieve the previous employee's last name for each employee:

`SELECT EmployeeID, FirstName, LastName, LAG(LastName, 1, 'N/A') OVER (ORDER BY EmployeeID) AS PreviousLastName FROM Employees;`

This query will return the employee ID, first name, last name, and the previous employee's last name for each row. If there is no previous row available, it will return 'N/A' as the default value.

Using the LEAD Function
-----------------------

Similar to the LAG function, the LEAD function allows you to access data from a subsequent row in a result set. It also takes three arguments: the column you want to retrieve data from, the number of rows to go forward, and the default value to return if the desired row is not available.

Let's say we have a table called `Products` with columns `ProductID`, `ProductName`, and `Price`. We want to retrieve the next product's name and price for each product:

`SELECT ProductID, ProductName, Price, LEAD(ProductName, 1, 'N/A') OVER (ORDER BY ProductID) AS NextProductName, LEAD(Price, 1, 0) OVER (ORDER BY ProductID) AS NextPrice FROM Products;`

This query will return the product ID, product name, price, next product's name, and next product's price for each row. If there is no next row available, it will return 'N/A' as the default value for the product name and 0 for the price.

The LAG and LEAD functions in SQL Server 2008 are powerful tools that can greatly simplify complex queries and calculations involving previous or subsequent rows. They provide a convenient way to access data from adjacent rows without the need for self-joins or subqueries.

References:
-----------

*   [Microsoft Documentation: LAG (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-ver15)
*   [Microsoft Documentation: LEAD (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/lead-transact-sql?view=sql-server-ver15)
Parallels Desktop 18: Run Windows on Mac Effortlessly
Tags: parallelsdesktop18, windowsonmac, virtualmachine, seamlessintegration
Published: 2023-08-18 13:58:41

Parallels Desktop 18 is a powerful virtualization software that allows users to seamlessly run Windows on Mac computers. With over 15 years of trusted performance, Parallels Desktop enables users to run more than 200,000 Windows applications on their Mac machines, including [Microsoft Office for Windows](https://www.brandcouponmall.com/brand/microsoft/). In this article, we will explore the features and benefits of Parallels Desktop 18, making it the go-to solution for running Windows on Mac.

## Effortless Windows Integration:

Parallels Desktop 18 offers a smooth integration between Mac and Windows environments. Users can easily copy and paste text or drag-and-drop files between the two operating systems, making file sharing and collaboration a breeze. Additionally, Parallels Desktop allows for seamless interaction with Windows apps right from the Mac Dock, eliminating the need to switch between different interfaces.

## Enhanced Performance:

One of the standout features of Parallels Desktop 18 is its ability to run Windows applications on Mac without compromising performance. Whether you need to use resource-intensive software or graphic-intensive games, Parallels Desktop ensures that your Mac runs smoothly without any slowdowns or disruptions. With up to 32 CPUs and 128GB of RAM available in the Pro Edition, you can push the limits of your virtual machine.

## User-Friendly Interface:

Parallels Desktop is designed to be intuitive and user-friendly. It is simple to install, configure, and use, even for those who are not tech-savvy. The software offers a range of one-touch tools, such as disk space optimization and screenshot capture, to enhance productivity and ease of use. Moreover, Parallels Desktop Pro Edition includes advanced features for software development, testing, and design, catering to professionals in various fields.

## Trusted and Praised by Experts:

With over 7 million users worldwide, Parallels Desktop has gained the trust and praise of both users and experts. Experts mention the fast startup time, reliability, and seamless operation of Parallels Desktop. Reviews highlight the ease of use, performance, and the ability to run both operating systems simultaneously, unlike Apple's native Boot Camp. Parallels Desktop has been commended for its tight integration and flexibility in running Windows apps on a Mac.

## Conclusion:

Parallels Desktop 18 is the ultimate solution for running Windows on Mac without any hassle. With its seamless integration, enhanced performance, and user-friendly interface, it has become the trusted choice for millions of users worldwide. Whether you need to run Windows for work purposes, gaming, or app development, Parallels Desktop provides a seamless and efficient experience. By bridging the gap between Mac and Windows, Parallels Desktop 18 empowers users to embrace the best of both worlds, creating a truly versatile digital workplace.
Auto logout after an hour of inactivity with Spring Security
Tags: java, spring, springboot, springsecurity
Published: 2023-08-18 13:51:46

Have you ever left your computer unattended for a while, only to come back and find that you've been automatically logged out of your favorite website? It can be frustrating, but it's actually a security feature implemented by many websites to protect your sensitive information. In this article, we will explore how to implement auto logout after an hour of inactivity using Spring Security.

Spring Security is a powerful framework that provides authentication and authorization functionalities for Java applications. It allows developers to secure their applications by implementing various security features, including session management.

By default, Spring Security uses a session-based approach to manage user sessions. When a user logs in, a session is created and associated with that user. The session is maintained until the user logs out or the session expires due to inactivity.

However, in some cases, it is desirable to automatically log out users after a certain period of inactivity to enhance security. To achieve this, we can configure Spring Security to expire sessions after a specified time of inactivity.

To implement auto logout after an hour of inactivity, we need to configure the session timeout in our Spring Security configuration file. In the `application.properties` file, add the following line:

`server.servlet.session.timeout=60m`

This configuration sets the session timeout to 60 minutes (1 hour). After 1 hour of inactivity, the user will be automatically logged out.

Additionally, we can display a friendly message to the user before they are logged out. To do this, we can create a custom logout page that displays a funny phrase like "Oops! Looks like you've been inactive for too long. Time to stretch those legs and log in again!"

To create the custom logout page, add the following code to your Spring Security configuration file:

`http.logout() .logoutUrl("/logout") .logoutSuccessUrl("/customLogoutPage") .permitAll();`

This configuration specifies that when a user logs out, they will be redirected to the "/customLogoutPage" URL, which can display the funny phrase and provide a login link for the user to log in again.

Implementing auto logout after an hour of inactivity with Spring Security is a great way to enhance the security of your application. It ensures that users are automatically logged out if they forget to log out themselves, reducing the risk of unauthorized access to their accounts.

References:

*   [Spring Security](https://spring.io/projects/spring-security)
*   [Spring Boot Features - Session Management](https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-session-management)
Introduction to Networking
Tags: swift
Published: 2023-08-18 13:46:09

In the digital age, networking forms the backbone of all our online interactions. Whether it's browsing a website, sending an email, or using a mobile app, all these activities rely on the principles of networking. This article will introduce you to the basics of computer networks, the Internet, the client-server model, and the importance of protocols in networking.

## Basics of Computer Networks

A computer network is a group of computers that are connected to each other for the purpose of communication. Networks may be classified according to a wide variety of characteristics such as the medium used to transport the data, communications protocol used, scale, topology, and organizational scope.

## Introduction to the Internet

The Internet is a global network of networks. It uses the standard Internet Protocol Suite (TCP/IP) to link devices worldwide. It is a network of networks that consists of private, public, academic, business, and government networks of local to global scope, linked by a broad array of electronic, wireless, and optical networking technologies.

## Understanding the Client-Server Model

The client-server model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients. In the client-server architecture, when the client computer sends a request for data to the server through the internet, the server accepts the requested, processes it, and deliver the data packets requested back to the client.

## Overview of Protocols and Their Importance in Networking

In the context of data networking, a protocol is a formal set of rules and conventions that governs how computers exchange information over a network medium. A protocol implements the functions of one or more of the OSI (Open Systems Interconnection) layers. A protocol suite, such as TCP/IP, is a collection of protocols that is used for a certain type of network connection.

Protocols are vital to the smooth running of digital communications. They ensure that data is sent in a format that can be understood by both sender and receiver, and they control vital activities such as error checking and data compression.

In conclusion, understanding the basics of networking is crucial for any software developer. It forms the foundation for many of the activities we perform on a daily basis, and is especially important when developing applications that rely on network connections, such as a weather application.
123
Published: 2023-08-18 13:41:49


First Image: 


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gn4k6ymjxblpn5tkledb.png)
Simplify Your Cross-Database Data Import with dbForge Edge
Published: 2023-08-18 13:39:18

Microsoft Access stands as a notably favored relational database system, replete with numerous advantages. Installation and management are remarkably straightforward, catering to both novices and seasoned database users alike. Its toolkit for data migration is endowed with flexibility. An extensive community and a plethora of valuable online resources facilitate a seamless acquisition of profound insights. Additionally, Access is inclusively accessible through the Microsoft 365 suite's Professional and higher editions, making it a cost-effective extension to Microsoft's flagship office tools encompassing Word, Excel, and Outlook.

However, it's essential to acknowledge the limitations and drawbacks that accompany Access. Its features and capabilities pale in comparison to its more advanced counterpart — Microsoft SQL Server. It comes as no surprise that numerous businesses that commence their journey with Access eventually outgrow its capacities and transition towards more robust database systems such as SQL Server, MySQL, MariaDB, Oracle, or PostgreSQL.

If your circumstance aligns with this scenario, it's plausible that you're grappling with the task of migrating your tables from Access to one of the aforementioned databases. To navigate this migration with minimal disruption, we are poised to illustrate the process using dbForge Edge, a comprehensive multidatabase solution that encompasses all these systems, accompanied by robust integrated development environments (IDEs).

Learn more: https://blog.devart.com/bulk-data-import.html

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr6yv70ztw15o7e30i0o.png)
Удалить дубликаты в отсортированном массиве
Published: 2023-08-18 13:34:59

## Задача. 
Дан отсортированный массив целых чисел, в котором возможны дубликаты. Нужно удалить дубликаты in-place и вернуть число уникальных элементов в массиве. Например, есть массив: [1, 1, 1, 2, 2, 3, 4, 5, 5, 7, 7, 9]. В результате должно получиться [1, 2, 3, 4, 5, 7, 9, .., .., ....] и число уникальных элементов 7. На троеточие я заменил хвост массива, и нам не важно что там будет после преобразования. Мы будем проверять только первые 7, что они отображают все уникальные числа из массива. 

Ссылка на leetcode: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

## Решение
На ум сразу приходят несколько вариантов решения не in-place. Например, использовать второй массив, в который будем копировать элементы только когда nums[i] != nums[i + 1]. Или использовать HashSet , в который будем помещать элементы массива по мере итераций по нему и проверять видели ли мы этот элемент или нет. Но все эти варианты решения  требуют O(n) памяти. 


Можно решить используя Two Pointers(два указателя). Один указатель для итераций по массиву, а второй индекс то, куда мы будем копировать уникальный элемент в том же массиве. Копирование будем делать только тогда, когда текущий элемент отличается от следующего. Плюс edge-case для последнего элемента, который мы всегда копируем.

```java
public int removeDuplicates(int[] nums) {
    int k = 0;
    for (int i = 0; i < nums.length; i++) {
        if (i == nums.length - 1 || nums[i] != nums[i + 1]) {
            nums[k++] = nums[i];
        }
    }
    return k;
}

```
Time Complexity O(n), Space Complexity O(1)

Давайте посмотрим как оно будет работать по шагам для нашего примера.

Вначале i = 0, k = 0:


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

Далее для i = 1 nums[i] = 1, nums[i + 1] = nums[2] = 1, поэтому ничего не делаем и переходим на следующую итерацию:


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

Для i = 2, nums[i] = 1, nums[i + 1] = 2. Поэтому копируем 1 в начало массива и увеличиваем k на 1:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqr7sysfwbqbd6j072fy.png)
Для i = 3 ничего не делаем, т.к. nums[i] = 2, nums[i + 1] = 2. Для i = 4 два соседних элемента не равны. Поэтому копируем и увеличиваем k:

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



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







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



Аналогично повторяем для i = 5 - 10:


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

Для i = 11, i + 1 = 12 за пределами массива. Поэтому сравнения со следующим не делаем, а просто копируем:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzvqday6x9t15zfpjyc8.png)
Common Server Setups for Web Applications
Published: 2023-08-18 13:34:33


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


While going through the basic System design courses , one of the most common term which I came across is SERVERS. Now we know that these are one of the most important components in systems , here is a list of different ways to setup a web service.

1. **Single Server:** This technology is straightforward but could suffer from slow performance due to resource competition and lacks the ability to scale horizontally.

2. **Separate Database Server**: 
In the architecture, an application server and a database server operate with separate resources, allowing individual vertical scaling, but the network latency between them increases due to the database being a network hop away.

3. **Load Balancer**: By distributing work among multiple servers, the system achieves native horizontal scaling and defends against DDOS attacks with rule-based protection, yet introduces complexity that could potentially lead to performance bottlenecks and complicate aspects like SSL termination and stick sessions.

4. **HTTP Accelerator**: By caching web responses in memory to enhance rapid serving, alleviate the web server's CPU load, and utilizing compression for reduced bandwidth consumption, the system requires tuning and could experience decreased performance with a low cache-hit rate.

5. **Master-Slave Database Replication**: Can improve read and write performance. Adds a lot of complexity and failure modes.

6. **Load Balancer + Cache + Replication**: The approach involves integrating load balancing for caching and application servers, along with database replication.

7. **Database-as-a-Service**: Delegate database management to external providers, such as Amazon's RDS and other hosted versions of popular databases, allowing someone else to handle the operation.

8. **Backend as a Service**: When developing a mobile app and aiming to avoid backend intricacies, outsourcing the backend to third-party services like Parse or Firebase lets us focus on the challenging mobile platform aspects, given their popularity and convenience.

9.**Platform as a Service**: Opt for a partially managed backend solution that offers greater flexibility compared to Backend as a Service (BaaS), leveraging options like Google App Engine, Heroku, Salesforce, and various alternatives, allowing us to build our application while delegating most backend responsibilities.

Ref: https://www.digitalocean.com/community/tutorials/5-common-server-setups-for-your-web-application
How do I backup my websites, and why should I improve
Tags: backup
Published: 2023-08-18 13:32:22

---
title: How do I backup my websites, and why should I improve
published: true
description: How do I backup my websites, and why should I improve
tags: Backup
canonical_url: https://ariaieboy.ir/blog/12-how-do-i-backup-my-websites/
series: My Backup Strategy
---
In the old days, I didn't have any backup plans, and the only time I needed my website backed up, I was lucky that my host provider had an automatic backup system. I could restore my website using those backups, but I lost a week of data because the hosting provider would back up the host weekly.

I do not use a shared host these days, and I manage my servers, so I need to back up my websites personally.

## How should I backup?

Determining which data requires backup and the frequency of changes is critical.

To determine the needed data, we can think that our server is gone, and we want to restore our website to its current state.

In my case, I need to know the services that my website needs, for example, the web server, application, database, object storage, and cache services.

Then I need to recreate these services using my website source code and run those on my new server.

After running the services, I first need to restore my databases. And if required, my object storage files.

## How am I backing up my websites

I back up my databases to another server at least once daily. And in some cases, multiple times a day based on the application traffic.

I back up my codebases on my local machine and the remote git repository hosted on GitHub or GitLab.

Since I use docker for development, All my websites have a docker-compose file that can recreate all required services for the website.

## What is missing?

The big missing part is the object storage part. I need to implement a way to automatically back up my files from my self-hosted object storage into another server.

I must implement the 3-2-1 strategy for all my backups.

I need to document the restoration process for each website.

Implement a way to verify the health of the backup files; the last thing I want is a corrupted backup file.