Learn Prompt-ChatGPT 精选案例:代码助理

2023-09-18 11:03:26

你可以使用 ChatGPT 进行代码生成、生成测试用例、注释、审查和漏洞检测。

代码生成

我们可以让 ChatGPT 自动生成一个排序算法中的快速排序的Python代码。

简单的代码生成对于 ChatGPT 来说小事一桩。

测试用例

用例来源出自StuGRua

在待测函数函数定义清晰的情况下,单元测试可以通过 ChatGPT 来生成。

写下列代码中CompressPicture函数的单测,要求覆盖全部逻辑。
断言使用require包。
测试用例以testCases的形式输出。

// CompressPicture the picture by resizing it to the specified width.
func CompressPicture(picData []byte, width uint) ([]byte, error) {
   // Decode the input image.
   oldBuffer := bytes.NewBuffer(picData)
   inputImg, _, err := image.Decode(oldBuffer)
   if err != nil {
      return nil, err
   }
   // Resize the image to the specified width.
   outputImg := resize.Resize(width, 0, inputImg, resize.Lanczos3)
   // Encode the output image as PNG and write it to a buffer.
   newBuffer := new(bytes.Buffer)
   err = png.Encode(newBuffer, outputImg)
   if err != nil {
      return nil, err
   }
   // Return the compressed image as a byte slice.
   return newBuffer.Bytes(), nil
}


# ChatGPT生成代码块如下:

func TestCompressPicture(t *testing.T) {
   // Setup test data
   imgData, err := os.ReadFile("test-image.png")
   if err != nil {
      t.Fatalf("failed to read test image file: %v", err)
   }
   testCases := []struct {
      name  string
      width uint
   }{
      {"compress with a valid width", 500},
      {"compress with an invalid width", 0},
   }
   for _, tc := range testCases {
      t.Run(tc.name, func(t *testing.T) {
         // Invoke the function being tested.
         compressedData, err := CompressPicture(imgData, tc.width)

         // Check the result.
         if err != nil {
            t.Fatalf("unexpected error: %v", err)
         }
         if len(compressedData) == 0 {
            t.Fatalf("compressed data is empty")
         }
         create, err := os.Create("test-image-compressed.png")
         if err != nil {
            return
         }
         defer create.Close()
         _, err = create.Write(compressedData)
      })

   }
}

ChatGP T单次对话有长度限制,所以一次尽量只进行一个函数的单元测试生成。

代码注释 & 格式优化

ChatGPT 可以通过阅读代码,理解函数的输入、输出、功能以及用途,然后生成相应的 API 文档和注释。

Please add line comments to this Python code and reformat it to make it easier to read:

import openai
openai.api_key = "YOUR_API_KEY"

def generate_response(prompt):
    response = openai.Completion.create(engine="davinci",prompt=prompt,temperature=0.5,max_tokens=1024,n=1,stop=None)
    return response.choices[0].text.strip()

while True:
    prompt = input("请输入你的问题:")
    response = generate_response(prompt)
    print("答案:", response)

ChatGPT给每一句话都加上了解释,并且将过长的语句转化成更加易读的格式。

import openai  # Import the openai module

# Set the API key for the openai module
openai.api_key = "YOUR_API_KEY"  # Replace with your actual OpenAI API key

# Define a function for generating a response from OpenAI's language model given a prompt
def generate_response(prompt):
    # Create an OpenAI completion with the specified parameters
    response = openai.Completion.create(
        engine="davinci",  # Use the 'davinci' language model
        prompt=prompt,  # Use the provided prompt
        temperature=0.5,  # Use a temperature of 0.5, which means the model will generate diverse responses
        max_tokens=1024,  # Generate up to 1024 tokens of output
        n=1,  # Generate a single response
        stop=None  # Do not use a stop sequence to end the generated text
    )
    # Extract the generated text from the response and return it
    return response.choices[0].text.strip()

# Continuously prompt the user for questions and generate responses using the generate_response function
while True:
    prompt = input("Please enter your question: ")  # Prompt the user for a question
    response = generate_response(prompt)  # Generate a response to the question using the generate_response function
    print("Answer:", response)  # Print the generated response

代码调试

通过之前的几个步骤,你已经了解了如何编写正确且具有测试用例的代码。

在日常开发中,除了编写代码之外,我们还会遇到两个比较棘手的开发步骤。一个是解决运行现有的代码后出现的错误;另一个是如何在当前编程语言中复现其他编程语言已经支持的处理逻辑呢?

我们先解决第一个问题。一般来说,写完代码后运行,如果代码中有错误,解释器会提示错误信息,按照提示信息,通常可以很快找出错误并进行修改。但有时候错误提示信息不是那么明确,当你检查了几遍仍然无法找出问题,就会比较困扰。ChatGPT 可以结合已有的错误信息,帮助我们分析代码中潜在的问题。

这里我选择了一个stack overflow上python跟SQL数据库连接错误的例子:Error while trying to connect to sql server with python using pyodbc

ChatGPT扮演成了一个python专家:

You are a python expert who can pinpoint errors in your code through error messages and provide easy-to-understand solutions.

error```
Traceback (most recent call last):
File "[test.py](http://test.py/)", line 7, in <module>
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL
Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Login failed for user 'SA'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC
Driver 17 for SQL Server][SQL Server]Login failed for user 'SA'. (18456)")

code```

import pyodbc

server = 'SERVER'

database = 'DBNAME'

username = 'SA'

password = 'SQLPWD'

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

Please analyse "code" for possible causes, solutions and the correct code depending on the "error”.  


The error message indicates that the login for the SQL Server failed for the user 'SA'. There could be several reasons for this error, but one possible reason is that the provided password is incorrect or the 'SA' account is disabled. Here are some steps to troubleshoot and fix the error:

Verify the username and password: Double-check that the provided username and password are correct. You can try logging in to the SQL Server using these credentials to ensure that they are valid.

Check if the 'SA' account is disabled: If the 'SA' account is disabled, you will not be able to log in to the SQL Server using this account. You can check the account status in SQL Server Management Studio or by running a query on the server:

SELECT name, is_disabled
FROM sys.sql_logins
WHERE name = 'SA'

If the 'is_disabled' column value is 1, then the account is disabled. To enable the account, you can run the following query:

ALTER LOGIN SA WITH PASSWORD = '<new_password>', CHECK_POLICY = OFF, CHECK_EXPIRATION = OFF;

Note that it's not recommended to use the 'SA' account for regular database operations as it has elevated privileges.

Check the SQL Server authentication mode: If the SQL Server authentication mode is set to 'Windows Authentication mode only', you will not be able to log in using SQL Server authentication. You can check the authentication mode in SQL Server Management Studio by right-clicking on the server instance, selecting Properties, and navigating to the Security tab.

ChatGPT 给出的解决方法是:

  • 验证用户名和密码
  • 检查 "SA "账户是否被禁用
  • 检查SQL Server的认证模式

而网页中最受欢迎的回复是:

  • SA被禁止访问
  • 服务器认证选择错误
  • SQL服务器没有开放远程访问

通过比较,我们很容易得到ChatGPT在代码调试方面的可行性。

代码互翻

ChatGPT 提供的另一个非常有用的功能是能够将程序从一种语言移植到另一种语言。

这里我在 Leetcode 找了一道常见算法题最长回文子串的 C++ 实现,转化成 Python 语言。

备注

最长回文子串题目:

给你一个字符串 s,找到 s 中最长的回文子串。 如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。

You are an expert program developer with extensive experience in writing C++ and Python. Please convert this C++ program to Python:

code```
class Solution {
public:
    string longestPalindrome(string s) {
        int len=s.size();
        if(len==0||len==1)
            return s;
        int start=0;
        int max=1;
        vector<vector<int>>  dp(len,vector<int>(len));
        for(int i=0;i<len;i++)
        {
            dp[i][i]=1;
            if(i<len-1&&s[i]==s[i+1])
            {
                dp[i][i+1]=1;
                max=2;
                start=i;
            }
        }
        for(int l=3;l<=len;l++)
        {
            for(int i=0;i+l-1<len;i++)
            {
                int j=l+i-1;
                if(s[i]==s[j]&&dp[i+1][j-1]==1)
                {
                    dp[i][j]=1;
                    start=i;
                    max=l;
                }
            }
        }
        return s.substr(start,max);
    }
};

ChatGPT输出的代码部份如下:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        if n == 0 or n == 1:
            return s
        start = 0
        max_len = 1
        dp = [[0] * n for _ in range(n)]
        for i in range(n):
            dp[i][i] = 1
            if i < n - 1 and s[i] == s[i+1]:
                dp[i][i+1] = 1
                start = i
                max_len = 2
        for l in range(3, n+1):
            for i in range(n-l+1):
                j = i + l - 1
                if s[i] == s[j] and dp[i+1][j-1] == 1:
                    dp[i][j] = 1
                    start = i
                    max_len = l
        return s[start:start+max_len]

代码顺利通过测试:

code

IDE 推荐

这里我推荐的是Cursor.so,它本身是一个集成了 GPT-4, 国内直接可以访问的,优秀而强大的免费代码生成器,可以帮助你快速编写、编辑和讨论代码。它支持多种编程语言,如 Python, Java, C#, JavaScript 等,并且可以根据你的输入和需求自动生成代码片段。

更多推荐

方案:浅析利用AI智能识别与视频监控技术打造智慧水产养殖监管系统

一、方案背景针对目前水产养殖集约、高产、高效、生态、安全的发展需求,基于智能传感、智慧物联网、人工智能、视频监控等技术打造智慧水产系统,成为当前行业的发展趋势。传统的人工观察水产养殖方式较为单一,难以及时发现人员非法入侵、偷盗、偷钓、水质污染等管理问题。二、方案概述TSINGSEE青犀视频智慧水产养殖方案主要是围绕视频

TDengine 与煤矿智能 AI 视频管理系统实现兼容性互认

煤矿行业是一个充满危险和复杂性的领域,具备产业规模大、分布地域广、安全性要求高等特点,为了实现智能化预警、预测等目的,煤矿企业纷纷采用现代化的技术来提高安全性、生产效率和管理水平。煤矿智能AI视频管理系统可以助力企业更好地进行矿工工作环境监测、异常情况报警等工作,从而提高安全性并减少事故风险,在煤矿项目中已经得到了广泛

做接口测试如何上次文件

【软件测试面试突击班】如何逼自己一周刷完软件测试八股文教程,刷完面试就稳了,你也可以当高薪软件测试工程师(自动化测试)在日常工作中,经常有上传文件功能的测试场景,因此,本文介绍两种主流编写上传文件接口测试脚本的方法。首先,要知道文件上传的一般原理:客户端根据文件路径读取文件内容,将文件内容转换成二进制文件流的格式传输给

PASCAL VOC2012数据集详细介绍

PASCALVOC2012数据集详细介绍0、数据集介绍2、PascalVOC数据集目标类别3、数据集下载与目录结构4、目标检测任务5、语义分割任务6、实例分割任务7、类别索引与名称对应关系0、数据集介绍2、PascalVOC数据集目标类别在PascalVOC数据集中主要包含20个目标类别,下图展示了所有类别的名称以及所

关于String、StringBuffer、StringBuilder

1.String可以被继承吗?String类由final修饰,所以不能被继承。扩展阅读在Java中,String类被设计为不可变类,主要表现在它保存字符串的成员变量是final的。Java9之前字符串采用char[]数组来保存字符,即privatefinalchar[]value;Java9做了改进,采用byte[]数

【人工智能】企业如何使用 AI与人工智能的定义、研究价值、发展阶段的深刻讨论

前言人工智能(ArtificialIntelligence),英文缩写为AI。它是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门新的技术科学。人工智能是新一轮科技革命和产业变革的重要驱动力量。📕作者简介:热爱跑步的恒川,致力于C/C++、Java、Python等多编程语言,热爱跑步,喜爱音乐

Maven 直接依赖、间接依赖、依赖冲突、依赖仲裁

文章目录直接依赖和间接依赖依赖冲突Maven的依赖仲裁最短路径优先先声明优先手动解决依赖冲突直接依赖和间接依赖在项目中直接引入的依赖叫做直接依赖,而那些被动引入的就叫间接依赖比如上图中,A是我们的项目,我们在项目中直接引入了B模块,所以B和A的关系就是直接依赖,而B工程内部引入了C,所以B和C也是直接依赖关系,如果B工

Python编程指南:利用HTTP和HTTPS适配器实现智能路由

嗨,爬虫大佬们!今天我要为大家分享一篇关于如何利用HTTP和HTTPS适配器来实现智能路由的Python编程指南。在现代互联网应用中,路由功能起着至关重要的作用,而利用Python编程语言实现智能路由则可以为我们的应用带来更高的灵活性和性能优化。接下来,让我们一起深入了解这个令人激动的主题吧!1、了解HTTP和HTTP

简单易上手,亚马逊云科技Amazon CodeWhisperer个性化辅助功能成为开发者好帮手

AmazonCodeWhisperer介绍AmazonCodeWhisperer是亚马逊云科技出品的一款基于机器学习的通用代码生成器,可实时提供代码建议。类似Cursor和GithubCopilot编码工具。在编写代码时,它会自动根据您现有的代码和注释生成建议。从单行代码建议到完整的函数,它可为您提供各种大小和范围的个

关于React Hooks的面试题及其答案

请解释一下ReactHooks是什么,以及它的优点和缺点是什么?Hooks是React16.8版本引入的一种新特性,它允许你在不写class的情况下操作state和其他React特性。Hooks是一种特殊的函数,可以让你“钩入”React的特性。它的优点是让编写组件更简单方便,同时可以自定义hook把公共的逻辑提取出来

面试中的技术趋势:如何展示你跟进最新技术的能力

🌷🍁博主猫头虎(🐅🐾)带您GotoNewWorld✨🍁🦄博客首页——🐅🐾猫头虎的博客🎐🐳《面试题大全专栏》🦕文章图文并茂🦖生动形象🐅简单易学!欢迎大家来踩踩~🌺🌊《IDEA开发秘籍专栏》🐾学会IDEA常用操作,工作效率翻倍~💐🌊《100天精通Golang(基础入门篇)》🐅学会Gol

热文推荐