teleren/devto huggingface dataset:
行为型设计模式-访问器 Visitor
Tags: designpatterns
Published: 2023-09-07 05:30:52



### 简介

在不改变原有类的前提下，可以新增不同的访问器，每种访问器都可自定义访问策略。

如超市购物车里什么物品都有，顾客遍历访问商品主要查看商品是否过期，包装是否完整，收银员遍历商品主要查看价格。顾客和收银员可以理解为两种Visitor，各自关注的重点就是Visitor中的visit方法实现逻辑。

原始数据结构就像数据库，而访问器就像基于该数据库的业务逻辑，不同访问器按照不同业务规则使用数据。

### 角色

- 抽象Visitor
    
    定义访问每一种Element的方法签名visit
    
- 具体Visitor
    
    实现具体访问方法visit
    
- 抽象Element
    
    定义accept方法，支持将visitor做参数，通过调用accept方法，实现accept→visitor→visit的调用
    
- 具体Element
    
    实现具体方法
    

### 类图

如图，Element中的accept方法以Visitor做参数，其中调用visitor.visit方法，将主动权交给Visitor去处理。实现每新增一种visitor，对原Element无感知

![类图](https://deb-gmi.oss-cn-beijing.aliyuncs.com/img/20210409162438.png)

### 代码

```php

interface Component
{
    public function accept(Visitor $visitor): void;
}

class ConcreteComponentA implements Component
{
    public function accept(Visitor $visitor): void
    {
        $visitor->visitConcreteComponentA($this);
    }

    public function exclusiveMethodOfConcreteComponentA(): string
    {
        return "A";
    }
}

class ConcreteComponentB implements Component
{
    public function accept(Visitor $visitor): void
    {
        $visitor->visitConcreteComponentB($this);
    }

    public function specialMethodOfConcreteComponentB(): string
    {
        return "B";
    }
}

interface Visitor
{
    public function visitConcreteComponentA(ConcreteComponentA $element): void;

    public function visitConcreteComponentB(ConcreteComponentB $element): void;
}

class ConcreteVisitor1 implements Visitor
{
    public function visitConcreteComponentA(ConcreteComponentA $element): void
    {
        echo $element->exclusiveMethodOfConcreteComponentA() . " + ConcreteVisitor1\n";
    }

    public function visitConcreteComponentB(ConcreteComponentB $element): void
    {
        echo $element->specialMethodOfConcreteComponentB() . " + ConcreteVisitor1\n";
    }
}

class ConcreteVisitor2 implements Visitor
{
    public function visitConcreteComponentA(ConcreteComponentA $element): void
    {
        echo $element->exclusiveMethodOfConcreteComponentA() . " + ConcreteVisitor2\n";
    }

    public function visitConcreteComponentB(ConcreteComponentB $element): void
    {
        echo $element->specialMethodOfConcreteComponentB() . " + ConcreteVisitor2\n";
    }
}

function clientCode(array $components, Visitor $visitor)
{
    foreach ($components as $component) {
        $component->accept($visitor);
    }
}

$components = [
    new ConcreteComponentA(),
    new ConcreteComponentB(),
];

echo "The client code works with all visitors via the base Visitor interface:\n";
$visitor1 = new ConcreteVisitor1();
clientCode($components, $visitor1);

echo "It allows the same client code to work with different types of visitors:\n";
$visitor2 = new ConcreteVisitor2();
clientCode($components, $visitor2);
```

output:

```
The client code works with all visitors via the base Visitor interface:
A + ConcreteVisitor1
B + ConcreteVisitor1
It allows the same client code to work with different types of visitors:
A + ConcreteVisitor2
B + ConcreteVisitor2
```
行为型设计模式-模板方法 Template Method
Tags: designpatterns
Published: 2023-09-07 05:28:30



### 简介

父类抽象类定义大的处理流程，部分细节做成抽象方法，留给子类去实现。

如Java的JUnit中， setUp tearDown方法都是留给具体的测试用例来写，Servlet中service处理了一个请求的大部分工作，留下doGet和doPost给业务自定义处理。

另外callback一般分两种方式：同步回调、异步回调，其中同步回调类似于模板方法模式，异步回调类似于观察者模式。

**模板方法要基于继承，而回调更类似组合，**

### 角色

- 抽象模板类
    
    定义大的处理流程，留出部分方法给具体类实现
    
- 具体模板类
    
    实现具体的处理逻辑
    

### 类图

如图，ConcreteClass实现了一些具体逻辑

![类图](https://deb-gmi.oss-cn-beijing.aliyuncs.com/img/20210409152836.png)

### 代码

```php

abstract class AbstractClass
{
    final public function templateMethod(): void
    {
        $this->baseOperation1();
        $this->requiredOperations1();
        $this->baseOperation2();
        $this->hook1();
        $this->requiredOperation2();
        $this->baseOperation3();
        $this->hook2();
    }

    protected function baseOperation1(): void
    {
        echo "AbstractClass says: I am doing the bulk of the work\n";
    }

    protected function baseOperation2(): void
    {
        echo "AbstractClass says: But I let subclasses override some operations\n";
    }

    protected function baseOperation3(): void
    {
        echo "AbstractClass says: But I am doing the bulk of the work anyway\n";
    }

    abstract protected function requiredOperations1(): void;

    abstract protected function requiredOperation2(): void;

    protected function hook1(): void { }

    protected function hook2(): void { }
}

class ConcreteClass1 extends AbstractClass
{
    protected function requiredOperations1(): void
    {
        echo "ConcreteClass1 says: Implemented Operation1\n";
    }

    protected function requiredOperation2(): void
    {
        echo "ConcreteClass1 says: Implemented Operation2\n";
    }
}

class ConcreteClass2 extends AbstractClass
{
    protected function requiredOperations1(): void
    {
        echo "ConcreteClass2 says: Implemented Operation1\n";
    }

    protected function requiredOperation2(): void
    {
        echo "ConcreteClass2 says: Implemented Operation2\n";
    }

    protected function hook1(): void
    {
        echo "ConcreteClass2 says: Overridden Hook1\n";
    }
}

function clientCode(AbstractClass $class)
{
    $class->templateMethod();
}

echo "Same client code can work with different subclasses:\n";
clientCode(new ConcreteClass1());

echo "Same client code can work with different subclasses:\n";
clientCode(new ConcreteClass2());
```

output:

```
Same client code can work with different subclasses:
AbstractClass says: I am doing the bulk of the work
ConcreteClass1 says: Implemented Operation1
AbstractClass says: But I let subclasses override some operations
ConcreteClass1 says: Implemented Operation2
AbstractClass says: But I am doing the bulk of the work anyway
Same client code can work with different subclasses:
AbstractClass says: I am doing the bulk of the work
ConcreteClass2 says: Implemented Operation1
AbstractClass says: But I let subclasses override some operations
ConcreteClass2 says: Overridden Hook1
ConcreteClass2 says: Implemented Operation2
AbstractClass says: But I am doing the bulk of the work anyway
```
AntDB-Oracle Compatibility Developer’s Manual P3–30
Published: 2023-09-07 05:27:48

##### Add Partitions

Use the ALTER TABLE... ADD PARTITION command to add a partition definition.

Summary

ALTER TABLE table\_name ADD PARTITION partition\_name; --add primary partition

ALTER TABLE table\_name MODIFY PARTITION partition\_name ADD SUBPARTITION subpartition\_name; --add subpartition

**argument:**

table\_name

The name of the partition table (optionally mode qualified).

partition\_name

The name of the partition that needs to be added or modified.

subpartition\_name

Added sub-partition names

**Add primary partition**

```
alter table sales_range add partition sales_jun2010 VALUES LESS THAN(TO_DATE('01/07/2010','DD/MM/YYYY'));
```

**Add sub-partition**

```
--Add a primary partition and a child partition
alter table subpar_test2 add partition p4 values('Airplain')
    (subpartition subp41 values less than(to_date('2020-01-01','yyyy-mm-dd')),
     subpartition subp42 values less than(to_date('2021-01-01','yyyy-mm-dd')),
     subpartition subp43 values less than(to_date('2022-01-01','yyyy-mm-dd'))
    );
--Only child partitions of a primary partition are added
alter table subpar_test2 modify partition p4 
 add subpartition subp44 values less than(to_date('2023-01-01','yyyy-mm-dd'));
```
行为型设计模式-策略 Strategy
Tags: designpatterns
Published: 2023-09-07 05:25:28



### 简介

一组实现了同一个策略接口的策略，可以随时指定用哪一种策略完成业务。

策略模式其实跟桥接模式很像，都是通过持有另一个对象，达到组合的效果。

### 角色

- Context 上下文
    
    可设置使用的 Strategy
    
- 抽象 Strategy
- 具体 Strategy

### 类图

如图，Context使用setStrategy方法设置当前使用的策略，在doSomething中，调用策略的execute方法，实现动态使用策略。

![类图](https://deb-gmi.oss-cn-beijing.aliyuncs.com/img/20210409143859.png)

### 代码

```php
class Context
{
    private $strategy;

    public function __construct(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function setStrategy(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    public function doSomeBusinessLogic(): void
    {
        echo "Context: Sorting data using the strategy (not sure how it'll do it)\n";
        $result = $this->strategy->doAlgorithm(["a", "b", "c", "d", "e"]);
        echo implode(",", $result) . "\n";

    }
}

interface Strategy
{
    public function doAlgorithm(array $data): array;
}

class ConcreteStrategyA implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        sort($data);

        return $data;
    }
}

class ConcreteStrategyB implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        rsort($data);

        return $data;
    }
}

$context = new Context(new ConcreteStrategyA());
echo "Client: Strategy is set to normal sorting.\n";
$context->doSomeBusinessLogic();

echo "Client: Strategy is set to reverse sorting.\n";
$context->setStrategy(new ConcreteStrategyB());
$context->doSomeBusinessLogic();
```

output:

```
Client: Strategy is set to normal sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
a,b,c,d,e
Client: Strategy is set to reverse sorting.
Context: Sorting data using the strategy (not sure how it'll do it)
e,d,c,b,a
```
行为型设计模式-状态 State
Tags: designpatterns
Published: 2023-09-07 05:22:52



### 简介

跟状态机密切相关。有限状态机 FSM 包含 状态、事件、动作三个元素。

当发生一个事件时，引发老状态变成新状态，并执行一个动作。

状态和行为间一般是有限制的，如某些行为只能再某些状态下进行，某些状态只能触发某些行为。

简单的状态间转换可使用 if else。

更有条理的可以用查表法：二维表中纵向是状态，横向是事件，value则是新状态和动作。做成二维数组配置，事件发生时结合当前状态，组成[老状态][事件]索引去查二维表，得出value是新状态和动作，如果没有value则不变换

再复杂一些之后，可使用状态模式。

### 角色

- Context 上下文
    
    可视为状态机，其内部持有State引用
    
    可通过改变State的值，来达到改变Context行为的目的
    
- 抽象 State
- 具体 State

### 类图

如图，Context/Machine中可以changeState来改变当前的状态，其中doThis和doThat签名与State一致，这样看起来就像改变状态的同时，改变了Context的行为。

![类图](https://deb-gmi.oss-cn-beijing.aliyuncs.com/img/20210409143155.png)

### 代码

```php
class Context
{
    private $state;

    public function __construct(State $state)
    {
        $this->transitionTo($state);
    }

    public function transitionTo(State $state): void
    {
        echo "Context: Transition to " . get_class($state) . ".\n";
        $this->state = $state;
        $this->state->setContext($this);
    }

    public function request1(): void
    {
        $this->state->handle1();
    }

    public function request2(): void
    {
        $this->state->handle2();
    }
}
abstract class State
{
    protected $context;

    public function setContext(Context $context)
    {
        $this->context = $context;
    }

    abstract public function handle1(): void;

    abstract public function handle2(): void;
}

class ConcreteStateA extends State
{
    public function handle1(): void
    {
        echo "ConcreteStateA handles request1.\n";
        echo "ConcreteStateA wants to change the state of the context.\n";
        $this->context->transitionTo(new ConcreteStateB());
    }

    public function handle2(): void
    {
        echo "ConcreteStateA handles request2.\n";
    }
}

class ConcreteStateB extends State
{
    public function handle1(): void
    {
        echo "ConcreteStateB handles request1.\n";
    }

    public function handle2(): void
    {
        echo "ConcreteStateB handles request2.\n";
        echo "ConcreteStateB wants to change the state of the context.\n";
        $this->context->transitionTo(new ConcreteStateA());
    }
}

$context = new Context(new ConcreteStateA());
$context->request1();
$context->request2();
```

output:

```
Context: Transition to ConcreteStateA.
ConcreteStateA handles request1.
ConcreteStateA wants to change the state of the context.
Context: Transition to ConcreteStateB.
ConcreteStateB handles request2.
ConcreteStateB wants to change the state of the context.
Context: Transition to ConcreteStateA.
```
Nine Ways to Lose Data Using Serverless Without Even Knowing It
Tags: serverless, aws, cloud, architecture
Published: 2023-09-07 05:14:54

**Designing a serverless system can be complex, and without knowing the internal workings of the services, you could easily lose the data.**

A steep learning curve is the main drawback of building serverless applications on AWS. AWS could do a better job of making an ideal developer experience. We’ve seen some small steps of improvement, but the ideal platform is still far away. Not only that, the development experience could be better, but there are also many cases where the actual behavior goes against the initial developer expectation, and you can easily lose data or get unexpected results without a deep understanding of AWS services. A good platform should abstract the details from the developer. But that is not the case with AWS.

Designing a serverless system can be complex, and without knowing the internal workings of the services, you could easily lose the data.
Let’s start with common ground. In more traditional, non-event-driven systems, you write data directly to the database, and losing data means that there is an issue with the database. But serverless systems are, in a large portion, event-driven systems, and data is eventually consistent. Putting data/events into such a system does not necessarily mean that it is immediately written to the database. It can be passed between several event busses, pub-sub, and event streaming systems … and, in most cases, ends up in a NoSQL database, like DynamoDB, which is by their nature eventually consistent. If you put data/event into such a system and it does not eventually end up at the destination or you do not get it when retrieving from the database, you have a problem. The data could also be lost, duplicated, you get older records than expected, etc. This article’s title mentions losing data, but we will actually cover all these cases.

## 1. Duplicate and Unordered Events

[Continue reading...](https://www.serverlesslife.com/Nine_Ways_How_to_Lose_Data_Using_Serverless_Without_Even_Knowing.html)
A narrowing of focus...
Tags: opensource, planning
Published: 2023-09-07 05:00:00

[Awhile ago](https://dev.to/grim/what-were-targeting-with-pidgin-300-alpha1-2fci) I wrote about what we were targeting for Pidgin 3.0.0 Alpha 1.

At the time this felt like a good step forward as we didn't really have a road map or anything and this was precisely that. Except it wasn't, it turned out to be more of a nebulous list with little to no direction. Unfortunately it took awhile for me to realize this, but a solution was pretty easy to find.

So, instead of just going through that list, we're going to focus on getting the new from scratch IRCv3 protocol plugin to the point where I can start using it with Pidgin 3 as a daily driver.

Not only does this give us some much needed direction it will also finally get me using Pidgin 3 as a daily driver. On top of that, it'll create a good cycle as I will be able to find and fix bugs much faster as they'll be directly affecting me.

So realistically not much is going to change from what we were doing before, but the [3.0.0 Alpha 1](https://issues.imfreedom.org/issues?u=1&q=(Scheduled%20versions:%203.0.0-alpha1%20)%20and%20(%23unresolved)) issues will be prioritized to get IRCv3 working using all of the new APIs that we've been developing.

I hope you're enjoying these posts! Remember they go live for patrons at 9AM CST on Mondays and go public at 12AM CST on Thursdays! If there's something specific you'd like to see me cover here, please comment below!
Solving the "Search Insert Position" Problem on LeetCode
Tags: programming, coding, java, beginners
Published: 2023-09-07 04:53:17

## 35. Search Insert Position
**Question Type:** Easy
**Liked by :**14.6K
**Disliked by:** 630

## Companies asked this Question:

_Company name : No of Times_
Amazon 4
Google 2
Apple 8
Microsoft 5
Adobe 4
Yahoo 2
Bloomberg 2
Facebook 7
VMware 5
Uber 4
LinkedIn 2
TikTok 2
tcs 2


Given a sorted `array` of distinct integers and a `target` value, return the `index` if the target is found. If not, return the `index` where it would be if it were inserted in `order`.

You must write an algorithm with `O(log n)` runtime complexity.

**Example 1:**
Input: `nums = [1,3,5,6], target = 5`
Output: `2`

**Example 2:**
Input: `nums = [1,3,5,6], target = 2`
Output: `1`

**Example 3:**
Input: `nums = [1,3,5,6], target = 7`
Output: `4`
 

**Constraints:**

`1 <= nums.length <= 104`
`-104 <= nums[i] <= 104`
`nums` contains **distinct** values sorted in **ascending** order.
`-104 <= target <= 104`

## Approach:

**Initialize Pointers:**
Initialize two pointers, start and end, to represent the search range within the sorted array.start initially points to the first element (index 0), and end points to the last element (index nums.length - 1).

**Binary Search Loop:**
Enter a while loop that continues as long as start is less than or equal to end.

**Calculate Middle Index:**
Calculate the middle index mid as start + (end - start) / 2. This ensures that the middle index is always rounded down to an integer, avoiding potential overflow issues.

**Compare with Target:**
Check if the element at index mid is equal to the target value.
If they are equal, return mid as the index where the target is found.

**Adjust Pointers:**
If the element at index mid is greater than the target, update end to mid - 1 to search in the left half of the current range.
If the element at index mid is less than the target, update start to mid + 1 to search in the right half of the current range.

**Return Insertion Point:**
If the while loop exits without finding the target (i.e., start becomes greater than end), return start as the index where the target should be inserted.



## Code(in Java):

```
class Solution {
    public int searchInsert(int[] nums, int target) {
         int start = 0;
         int end = nums.length - 1;
         
         while(start <= end){
             int mid = start +(end - start) / 2;
             if(nums[mid] == target) return mid;
             if(nums[mid] > target) end = mid - 1;
             if(nums[mid] < target) start = mid + 1;
         }
         return start;
    }
}
```

**Time Complexity Analysis:**
Binary search has a time complexity of O(log n), where n is the number of elements in the array. This approach ensures that the search is performed efficiently.

Happy coding,
shiva
AI-Powered Image to Caption Generator
Tags: imagetocaption, ai, programming, node
Published: 2023-09-07 04:27:00

The Online [Image to Caption Generator](https://image-to-caption.com/), a creation imbued with the incredible power of Artificial Intelligence (AI), stands as a beacon of innovation within the digital landscape. 

This remarkable online utility not only crafts image captions but also serves as an adept image alt text generator. In this era dominated by visual content, the pursuit of novel methods to elevate your images becomes not just a choice but a necessity.

Imagine effortlessly summoning descriptive and enthralling captions for your visuals, ensuring that your audience comprehends the entire narrative you strive to convey. 

Thanks to the marvels of artificial intelligence (AI), this vision has transformed into a tangible reality.

Visit : [https://image-to-caption.com/](https://image-to-caption.com/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74ngml9vgb0ulop9eysq.png)
Artificial Intelligence Image Generator
Tags: ai, aiimagegenaretor, node, learning
Published: 2023-09-07 04:22:19

Our [AI image generator](https://chat-gpt.photos/) is a state-of-the-art solution, powered by advanced artificial intelligence. It effortlessly creates, enhances, and refines images with remarkable precision. 

Whether it's original artwork, photo editing, or graphic design, our versatile AI tool empowers users to transform visual concepts into reality. 

Harnessing deep learning and extensive datasets, it produces high-quality visuals that match human craftsmanship. 

This tool is a game-changer for businesses, artists, and content creators, delivering unparalleled efficiency and creativity in the digital imagery landscape.

Visit Website: [https://chat-gpt.photos/](https://chat-gpt.photos/)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av7p9xpx25yzdc3i6tfk.png)
Simplify Your Data Integration: A Guide to JSON to GraphQL Conversion
Tags: jsontographql, dataintegration, graphqlconversion, combokitnet
Published: 2023-09-07 04:21:03

Are you navigating the dynamic world of data management and APIs? JSON and GraphQL are two powerhouse technologies, but how do you seamlessly convert JSON data into GraphQL? This guide explores the ins and outs of JSON to GraphQL conversion and introduces you to a powerful conversion tool: Combokit.net's JSON to GraphQL Converter.

## Understanding JSON and GraphQL

**JSON:** JSON (JavaScript Object Notation) is a versatile data format used for data transmission and storage. It's easy for humans to read and write and simple for machines to parse and generate.

**GraphQL:** GraphQL is a query language for APIs, allowing developers to request precisely the data they need from a server. It offers flexibility and efficiency over traditional REST APIs.

## Why Convert JSON to GraphQL?

There are several scenarios where JSON to GraphQL conversion is essential:

- Transitioning to GraphQL-based APIs
- Aggregating data from various sources
- Optimizing queries for performance

## The JSON to GraphQL Conversion Process

Discover the manual conversion process and how Combokit.net streamlines it:

1. **Visit the JSON to GraphQL Converter**: Go to [https://combokit.net/json-to-graphql](https://combokit.net/json-to-graphql).
2. **Upload Your JSON Data**: Select your JSON file.
3. **Convert and Customize**: Tailor the schema to your needs.
4. **Download the GraphQL Schema**: Obtain your GraphQL schema file.

## Advantages of Using Combokit.net's JSON to GraphQL Converter

- User-Friendly
- Customization Options
- Error Handling
- Completely Free

## Read the Full Guide

Dive deeper into JSON to GraphQL conversion at [Combokit.net](https://combokit.net/json-to-graphql). Simplify your data integration journey with Combokit.net!

Unlock the full potential of GraphQL data querying. Make your data integration journey smoother with Combokit.net!

[Read more](https://combokit.net/json-to-graphql)
Before the First Step...🐾
Tags: beginners, firstpost
Published: 2023-09-07 04:07:29

##  The beginning may be humble, but the end will be grand 🔥


My name is Noel 👀, and I am currently studying Computer Systems Technology (CST) at BCIT, located in Vancouver. At a not-so-young age, I am feeling extremely happy to be studying interesting computer-related subjects and working on projects in a good environment with good people. This space will serve as a diary, a notepad, and an important place for me. I have high expectations for my future journey and the results that will come from it. 

I wonder what this space represents to all of you.✨✨