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

news2024/9/25 9:38:57

你可以使用 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 等,并且可以根据你的输入和需求自动生成代码片段。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1019359.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

什么是气传导耳机?气传导耳机值得入手吗?

​随着生活节奏的加快&#xff0c;人们越来越关注听力健康。气传导耳机以其独特的传导方式和舒适的佩戴感受&#xff0c;逐渐成为耳机市场的新宠。气传导耳机不入耳设计听音&#xff0c;让你在享受音乐的同时&#xff0c;也能保护你的听力安全。今天我们就一起来看看几款值得大…

无涯教程-JavaScript - COMBINA函数

描述 COMBINA函数返回给定数量的项目的组合数量(重复)。 语法 COMBINA (number, number_chosen)争论 Argument描述Required/OptionalNumber 必须大于或等于0,并且大于或等于Number_chosen。 非整数值将被截断。 RequiredNumber_chosen 必须大于或等于0。 非整数值将被截断。…

国际上被广泛认可的电子邮箱服务有哪些?

随着全球化的发展&#xff0c;越来越多的企业开始涉足国际贸易。在众多的邮箱服务提供商中&#xff0c;哪些是国际上比较认可的呢&#xff1f;本文将为您详细介绍几款在全球范围内广受好评的邮箱服务&#xff1a;Gmail(谷歌邮箱)、Outlook(微软邮箱)、Yahoo Mail(雅虎邮箱)、Zo…

品牌营销|小红书母婴消费的发展趋势,与创新路径在哪里

随着社会的发展与进步&#xff0c;母婴消费已经成为现代家庭生活中的重要组成部分。人们对于孩子的关爱和需求日益增长&#xff0c;母婴市场也变得愈发繁荣。今天来分享下品牌营销&#xff0c;小红书母婴消费的发展趋势&#xff0c;与创新路径在哪里&#xff1f; 一、母婴消费的…

【Redis面试题(46道)】

文章目录 Redis面试题&#xff08;46道&#xff09;基础1.说说什么是Redis?2.Redis可以用来干什么&#xff1f;3.Redis 有哪些数据结构&#xff1f;4.Redis为什么快呢&#xff1f;5.能说一下I/O多路复用吗&#xff1f;6. Redis为什么早期选择单线程&#xff1f;7.Redis6.0使用…

抖音带货怎么找货源合作?

随着社交媒体的快速发展&#xff0c;抖音已成为销售商品的重要平台。越来越多的个人和企业开始在抖音上销售​​商品&#xff0c;但寻找合适的货源进行合作是一个很大的挑战。本文将为您介绍一些寻找合作货源的方法和技巧。 如何寻找抖音合作的货源&#xff1f; 确定你的目标市…

数据库管理-第104期 RAC上升级SSH的坑(20230918)

数据库管理-第104期 RAC上升级SSH的坑&#xff08;20230918&#xff09; 最近一些版本的OpenSSH和OpenSSL都爆出了比较严重的漏洞&#xff0c;但是Oracle数据库尤其是RAC升级SSH和SSL其实是有一定风险的&#xff0c;这里就借助我的OCM环境&#xff0c;做一次SSH升级的演示及排…

用ModelScope给大家送上中秋祝福

用ModelScope来阐述中秋的意义 第一 中秋节的背景 接下来我们继续深入一下看看ModelScope的理解 可以看当我们讨论家庭团聚时&#xff0c;ModelScope 对这个主题的理解的确十分准确。然而&#xff0c;有时候我们在表达这个概念时可能会变得有些过于正式和僵硬&#xff0c;这样…

【码银送书第七期】七本考研书籍

八九月的朋友圈刮起了一股晒通知书潮&#xff0c;频频有大佬晒出“研究生入学通知书”&#xff0c;看着让人既羡慕又焦虑。果然应了那句老话——比你优秀的人&#xff0c;还比你努力。 心里痒痒&#xff0c;想考研的技术人儿~别再犹豫了。小编咨询了一大波上岸的大佬&#xff…

论文解读 | YOLO系列开山之作:统一的实时对象检测

原创 | 文 BFT机器人 01 摘要 YOLO是一种新的目标检测方法&#xff0c;与以前的方法不同之处在于它将目标检测问题视为回归问题&#xff0c;同时预测边界框和类别概率。这一方法使用单个神经网络&#xff0c;可以从完整图像中直接预测目标边界框和类别概率&#xff0c;实现端…

二叉树的概念、存储及遍历

一、二叉树的概念 1、二叉树的定义 二叉树&#xff08; binary tree&#xff09;是 n 个结点的有限集合&#xff0c;该集合或为空集&#xff08;空二叉树&#xff09;&#xff0c;或由一个根结点与两棵互不相交的&#xff0c;称为根结点的左子树、右子树的二叉树构成。 二叉树的…

ClickHouse进阶(十七):clickhouse优化-写出查询优化

进入正文前&#xff0c;感谢宝子们订阅专题、点赞、评论、收藏&#xff01;关注IT贫道&#xff0c;获取高质量博客内容&#xff01; &#x1f3e1;个人主页&#xff1a;含各种IT体系技术,IT贫道_大数据OLAP体系技术栈,Apache Doris,Kerberos安全认证-CSDN博客 &#x1f4cc;订…

4G工业路由器,开启智能工厂,这就是关键所在

​提到工业物联网,首先联想到的就是数据传输。要把海量的工业数据从设备端传到控制中心,无线数传终端就发挥着重要作用。今天就跟着小编来看看它的“联”是怎么建立的吧! 原文&#xff1a;https://www.key-iot.com/iotlist/1838.html 一提到无线数传终端,相信大家首先想到的是…

Python 元组的常用方法

视频版教程 Python3零基础7天入门实战视频教程 下标索引用法和列表一样&#xff0c;唯一区别就是不能修改元素 实例&#xff1a; # 下标索引用法和列表一样&#xff0c;唯一区别就是不能修改元素 t1 ("java", "python", "c") # t1[1] "…

【PyTorch 攻略 (3/7)】线性组件、激活函数

一、说明 神经网络是由层连接的神经元的集合。每个神经元都是一个小型计算单元&#xff0c;执行简单的计算来共同解决问题。它们按图层组织。有三种类型的层&#xff1a;输入层、隐藏层和输出层。每层包含许多神经元&#xff0c;但输入层除外。神经网络模仿人脑处理信息的方式。…

虹科分享 | 谷歌Vertex AI平台使用Redis搭建大语言模型

文章来源&#xff1a;虹科云科技 点此阅读原文 基础模型和高性能数据层这两个基本组件始终是创建高效、可扩展语言模型应用的关键&#xff0c;利用Redis搭建大语言模型&#xff0c;能够实现高效可扩展的语义搜索、检索增强生成、LLM 缓存机制、LLM记忆和持久化。有Redis加持的大…

Docker启动Mysql容器并进行目录挂载

一、创建挂载目录 mkdir -p 当前层级下创建 mkdir -p mysql/data mkdir -p mysql/conf 进入到conf目录下创建配置文件touch hym.conf 并把配置文件hmy.conf下增加以下内容使用vim hym.conf即可添加(cv进去就行) Esc :wq 保存 [mysqld] skip-name-resolve character_set_…

设备树叠加层

设备树覆盖 设备树 (DT)是描述不可发现硬件的命名节点和属性的数据结构。内核&#xff08;例如 Android 中使用的 Linux 内核&#xff09;使用 DT 来支持 Android 设备使用的各种硬件配置。硬件供应商提供他们自己的设备树源 (DTS)文件&#xff0c;这些文件使用设备树编译器编…

UINT64整型数据在格式化时使用了不匹配的格式化符%d导致其他参数无法打印的问题排查

目录 1、问题描述 2、格式化函数内部解析待格式化参数的完整机制说明 2.1、传递给被调用函数的参数是通过栈传递的 2.2、格式化函数是如何从栈上找到待格式化的参数值&#xff0c;并完成格式化的&#xff1f; 2.3、字符串格式化符%s对应的异常问题场景说明 2.4、为了方便…

node 之 express 框架(初级)

一、express 热更新 1、安装扩展 npm install node-dev -D2、在根目录下的 package.json 文件中进行配置 3、之后的启动执行下面的命令即可 npm run dev二、mvc中的 模板引擎 1、ejs模板引擎的安装 npm install ejs -s2、在根目录下的app.js文件中配置 app.set(view engin…