这两天体验了下最新生产力工具Cursor,基于最新的 GPT-4 大模型,目前免费,国内可访问,不限次数,跨平台,你确定不来体验一把?官方的 Slogan :
Build Software. Fast. Write, edit, and chat about your code with GPT-4
In partnership with OpenAI

Cursor编程的上下文是你所在的代码文件,即如果你的文件后缀名为.py,那么在具体沟通时,就无需再出现“使用Python实现……”这种多余的前提,可以用更具体的限制;Accept或者Reject;Prompt,Ctrl+Z, Reject;Ctrl+K,生成代码或者对选定的代码段进行优化; Ctrl+L,对聊模式,对编程问题或者选定的代码段直接提问;


以下通过12个简单的问题,从语言支持、语法支持、业务场景、代码解释、代码优化等方面来体验一把这个编程生产力利器。
理论上,对于复杂的任务,只要分解到GPT能够理解的那一步,都可以胜任。程序员的AI助手(它竟然可以帮我们找Bug~~),自然语言编程真的来了。至于下面生成的代码能不能用,还需要进行实际验证,但目测从语言支持、语义理解以及逻辑推理等方面来看,可用率至少80%吧。
编程语言支持:
TypeScript,HTML,CSS,Python,C,Rust,Go,CSharp,Java,PHP,SQL等数十种。
// Welcome to Cursor
// 1. Try generating with command K on a new line. Ask for a new react component of an error popup.
// 2. Then, select the outputted code and hit chat. Ask if there's a bug. Ask how to improve.
// 3. Try selecting some code and hitting edit. Ask the bot to add a button that updates a statefield.
// 4. To try out cursor on your own projects, go to file menu (top left) and open a folder.
const bcrypt = require('bcryptjs');
const password = 'myPassword123';
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
console.log(hash);
const isMatch = bcrypt.compareSync('myPassword123', hash);
console.log(isMatch); // true

# Welcome to Cursor
# 1. Try generating with command K on a new line. Ask for a pytorch script of a feedforward neural network
# 2. Then, select the outputted code and hit chat. Ask if there's a bug. Ask how to improve.
# 3. Try selecting some code and hitting edit. Ask the bot to add residual layers.
# 4. To try out cursor on your own projects, go to the file menu (top left) and open a folder.
# K-Means Clustering Algorithm
import numpy as np
import matplotlib.pyplot as plt
class KMeans:
def __init__(self, k=2, max_iter=100):
self.k = k
self.max_iter = max_iter
def fit(self, X):
self.centroids = {}
# Initialize centroids randomly
for i in range(self.k):
self.centroids[i] = X[np.random.choice(len(X))]
# Iterate until convergence or max iterations reached
for i in range(self.max_iter):
self.clusters = {}
for j in range(self.k):
self.clusters[j] = []
# Assign each data point to the closest centroid
for x in X:
distances = [np.linalg.norm(x - self.centroids[c]) for c in self.centroids]
closest_centroid = distances.index(min(distances))
self.clusters[closest_centroid].append(x)
# Update centroids to be the mean of their assigned data points
for c in self.clusters:
self.centroids[c] = np.mean(self.clusters[c], axis=0)
def predict(self, X):
predictions = []
for x in X:
distances = [np.linalg.norm(x - self.centroids[c]) for c in self.centroids]
closest_centroid = distances.index(min(distances))
predictions.append(closest_centroid)
return predictions
# Example usage
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
kmeans = KMeans(k=2)
kmeans.fit(X)
predictions = kmeans.predict(X)
colors = ['r', 'g', 'b', 'c', 'm', 'y']
for i in range(len(X)):
plt.scatter(X[i][0], X[i][1], color=colors[predictions[i]])
plt.show()

public static String friendlyTime(long timestamp) {
long current = System.currentTimeMillis();
long diff = current - timestamp;
if (diff < 10 * 60 * 1000) {
return "刚刚";
} else if (diff < 24 * 60 * 60 * 1000) {
return "今天";
} else if (diff < 2 * 24 * 60 * 60 * 1000) {
return "昨天";
} else if (diff < 3 * 24 * 60 * 60 * 1000) {
return "前天";
} else {
return "更早之前";
}
}

public class Array {
public static void main(String[] args) {
int[] arr = {1, 7, 8, 4, 3, 6, 2, 5, 9};
Arrays.sort(arr); // sort the array in ascending order
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

public static void main(String[] args) {
String[] arr1 = {"q", "w", "e", "r", "t"};
String[] arr2 = {"a", "w", "d", "s", "r", "g"};
Set<String> set1 = new HashSet<>(Arrays.asList(arr1));
Set<String> set2 = new HashSet<>(Arrays.asList(arr2));
// Intersection
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
// Union
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);
}


USE poetry;
SELECT poems.title, poems.content, poems_author.name
FROM poems
JOIN poems_author
ON poems.author_id = poems_author.id
LIMIT 10;

public class Min {
public static void main(String[] args) {
int[] arr = {8, 1, 4, 0, -3};
int min = Arrays.stream(arr).min().getAsInt();
System.out.println("The minimum value in the array is: " + min);
}
}

import torch
from PIL import Image
import requests
from io import BytesIO
# Load model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# Define class names
class_names = ['smoke', 'fire']
# Define function to predict image
def predict_image(image_url):
# Load image from URL
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
# Predict image
results = model(img)
# Get class predictions
class_predictions = results.pred[0].softmax(-1)
# Get class indices
class_indices = class_predictions.argmax(-1).tolist()
# Get class names
class_names_predicted = [class_names[i] for i in class_indices]
return class_names_predicted

import java.sql.*;
public class Database {
public static void main(String[] args) {
try {
// Connect to local database
String url = "jdbc:mysql://localhost:3306/poetry";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
// Read first 5 rows from poems table
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM poems LIMIT 5");
// Print results
while (resultSet.next()) {
System.out.println(resultSet.getString("title") + " by " + resultSet.getString("author") + " " + resultSet.getString("content") + " " + resultSet.getString("style") + " " + resultSet.getString("dynasty") + " " + resultSet.getString("notes"));
}
// Export results to Excel
ResultSetToExcelConverter converter = new ResultSetToExcelConverter(resultSet);
converter.export("poems.xlsx");
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=ACCESS_TOKEN");
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent("Results from database query: " + resultSet.toString());
request.setText(text);
client.execute(request);
// Close connection
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("Error connecting to database: " + e.getMessage());
}
}
}

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse;
import org.eclipse.milo.opcua.stack.core.types.structured.WriteValue;
import org.eclipse.milo.opcua.stack.core.types.structured.WriteResponse;
import java.util.concurrent.CompletableFuture;
public class OPCClient {
public static void main(String[] args) throws Exception {
// Create a new OPC UA client
OpcUaClient client = OpcUaClient.create("opc.tcp://localhost:12686/example");
// Connect to the server
client.connect().get();
// Read a value from the server
NodeId nodeId = new NodeId(2, "/HelloWorld/ScalarTypes/Int32");
ReadValueId readValueId = new ReadValueId(nodeId, QualifiedName.DEFAULT, null, null);
CompletableFuture<ReadResponse> readResponse = client.read(readValueId);
Variant value = readResponse.get().getResults()[0].getValue().getValue();
System.out.println("Value: " + value);
// Write a value to the server
WriteValue writeValue = new WriteValue(nodeId, QualifiedName.DEFAULT, new Variant(42));
CompletableFuture<WriteResponse> writeResponse = client.write(writeValue);
Boolean success = writeResponse.get().getResults()[0].isGood();
System.out.println("Write success: " + success);
// Disconnect from the server
client.disconnect().get();
}
}

public static int test(int n) {
int cnt = 0;
while(0 != n) {
n = n & (n - 1);
++cnt;
}
return cnt;
}
public static void main(String[] args) {
System.out.println(test(15));
}
}
先将上述代码写入一个.java文件,然后 Ctrl+K 输入以下问题。
// 这段代码是一个Java程序,其中定义了一个名为test的静态方法,该方法接受一个整数参数n并返回一个整数。该方法使用while循环计算n的二进制表示中1的个数,并将其存储在cnt变量中。最后,该方法返回cnt的值。在main方法中,该程序调用test方法并将15作为参数传递给它,然后将结果打印到控制台。

public class Improve {
public static int test(int n) {
int cnt = 0;
while(0 != n) {
if((n & 1) != 0) {
++cnt;
n >>= 1;
} else {
n >>= 1;
}
}
return cnt; }
public static void main(String[] args) {
System.out.println(test(15));
}
}
先将上述代码写入一个.java文件,然后选择需要优化的代码段或者全选, Ctrl+K 输入以下问题。
public class Improve {
public static int test(int n) {
int cnt = 0;
cnt = Integer.bitCount(n);
return cnt;
}
public static void main(String[] args) {
System.out.println(test(15));
}
}
从结果看, Cursor 将我们自己编写的通过位运算右移计算二进制表示中1的个数,改成了一个内置方法调用。

其实,除了上述的入门体验,还有其他很多事情可以做,eg: 编写测试用例,解决力扣编程问题,网络爬虫,制作网页,小游戏编程,you name it,这一切仅受限于我们的想象力。
以下引用池建强的一句话:
人们需要警惕的是,当年因为汽车的诞生而失业的马车夫,他们并不是转行去干司机了,而是真失业了,或者去干别的苦力活。
当上时代司机的,是另一群人。
If you have any questions or any bugs are found, please feel free to contact me.
Your comments and suggestions are welcome!
几个月前,我读了一篇关于rubygem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:
网络编程套接字网络编程基础知识理解源`IP`地址和目的`IP`地址理解源MAC地址和目的MAC地址认识端口号理解端口号和进程ID理解源端口号和目的端口号认识`TCP`协议认识`UDP`协议网络字节序socket编程接口`sockaddr``UDP`网络程序服务器端代码逻辑:需要用到的接口服务器端代码`udp`客户端代码逻辑`udp`客户端代码`TCP`网络程序服务器代码逻辑多个版本服务器单进程版本多进程版本多线程版本线程池版本服务器端代码客户端代码逻辑客户端代码TCP协议通讯流程TCP协议的客户端/服务器程序流程三次握手(建立连接)数据传输四次挥手(断开连接)TCP和UDP对比网络编程基础知识
我是HanamiWorld的新人。我已经写了这段代码:moduleWeb::Views::HomeclassIndexincludeWeb::ViewincludeHanami::Helpers::HtmlHelperdeftitlehtml.headerdoh1'Testsearchengine',id:'title'hrdiv(id:'test')dolink_to('Home',"/",class:'mnu_orizontal')link_to('About',"/",class:'mnu_orizontal')endendendendend我在模板上调用了title方法。htm
我完全不是程序员,正在学习使用Ruby和Rails框架进行编程。我目前正在使用Ruby1.8.7和Rails3.0.3,但我想知道我是否应该升级到Ruby1.9,因为我真的没有任何升级的“遗留”成本。缺点是什么?我是否会遇到与普通gem的兼容性问题,或者甚至其他我不太了解甚至无法预料的问题? 最佳答案 你应该升级。不要坚持从1.8.7开始。如果您发现不支持1.9.2的gem,请避免使用它们(因为它们很可能不被维护)。如果您对gem是否兼容1.9.2有任何疑问,您可以在以下位置查看:http://www.railsplugins.or
我创建了一个由于“在运行时执行的单例元类定义”而无法编码的对象(这段代码的描述是否正确?)。这是通过以下代码执行的:#defineclassXthatmyusesingletonclassmetaprogrammingfeatures#throughcallofmethod:break_marshalling!classXdefbreak_marshalling!meta_class=class我该怎么做才能使对象编码正确?是否可以从对象instance_of_x的classX中“移除”单例组件?我真的需要一个建议,因为我们的一些对象需要通过Marshal.dump序列化机制进行缓存。
我正在查看Ruby日志记录库Logging.logger方法并从sourceatgithub提出问题与这段代码有关:logger=::Logging::Logger.new(name)logger.add_appendersappenderlogger.additive=falseclass我知道类 最佳答案 这实际上删除了方法(当它实际被执行时)。这是确保close不会被调用两次的保障措施。看起来好像有嵌套的“class 关于Ruby元编程问题,我们在StackOverflow上找到一
使用Paperclip,我想从这样的URL抓取图像:require'open-uri'user.photo=open(url)问题是我最后得到一个像“open-uri20110915-4852-1o7k5uw”这样的文件名。有什么方法可以更改user.photo上的文件名?作为一个额外的变化,Paperclip将我的文件存储在S3上,所以如果我可以在初始分配中设置我想要的文件名就更好了,这样图像就会上传到正确的S3key。像这样:user.photo=open(url),:filename=>URI.parse(url).path 最佳答案
我正在开发一个xcode自动构建系统。在执行一些预构建验证时,我想检查指定的证书文件是否已被撤销。我了解securityverify-cert验证其他证书属性但不验证吊销。我如何检查撤销?我正在用Ruby编写构建系统,但我对任何语言的想法都持开放态度。我阅读了这个答案(Openssl-Howtocheckifacertificateisrevokedornot),但指向底部的链接(DoesOpenSSLautomaticallyhandleCRLs(CertificateRevocationLists)now?)进入的Material对我的目的来说有点过于复杂(用户上传已撤销的证书是一
关闭。这个问题是off-topic.它目前不接受答案。想改进这个问题吗?Updatethequestion所以它是on-topic用于堆栈溢出。关闭11年前。Improvethisquestion我不经常使用ruby-通常它加起来相当于每两个月或更长时间编写一次脚本。我的大部分编程都是使用C++进行的,这与ruby有很大不同。由于我与ruby之间的差距如此之大,我总是忘记语言的基本方面(比如解析文本文件和其他简单的东西)。我想每天练习一些基本的东西,我想知道是否有一些我可以订阅的网站,并且会向我发送当天的Ruby问题或类似的东西。有人知道这样的站点/Internet服务吗?
我如何将像“root_path”这样的Rails路由助手作为类方法添加到像my_model.rb这样的类中?所以我的课是这样的:ClassMyModeldefself.fooreturnself.root_pathendendMyModel.foo以上不起作用,因为ClassMyModel不响应root_path这是我所知道的:我可以使用includeRails.application.routes.url_helpers,但这只会将模块的方法添加为实例方法我试过扩展Rails.application.routes.url_helpers但它没用请随时给我上课:)