收集、管理和分享有用的代码片段,提高开发效率
发送SMTP邮件
import javax.mail.*;
import javax.mail.inet.*;
public class EmailSender {
public static void sendEmail(String to, String from, String subject, String body) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthenticator getPasswordAuthenticator() {
return new PasswordAuthenticator("username", "password");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
}
}
绘制热力图
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
sns.heatmap(data, annot=True, fmt="d")
plt.show()
使用nlohmann/json
#include "nlohmann/json.hpp"
#include <iostream>
using namespace std;
using json = nlohmann::json;
int main() {
string jsonStr = "\n {\n \"name\": \"John\",\n \"age\": 30,\n \"city\": \"New York\"\n }\n";
auto j = json::parse(jsonStr);
cout << "Name: " << j["name"] << endl;
cout << "Age: " << j["age"] << endl;
cout << "City: " << j["city"] << endl;
return 0;
}
TCP服务器
public class SimpleServer {
public static void main(String[] args) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server listening on port 8080");
while (true) {
Socket clientSocket = serverSocket.accept();
new Thread(() -> {
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.write("Echo: " + inputLine);
out.newLine();
out.flush();
}
} finally {
clientSocket.close();
}
}).start();
}
}
}
}
基本测试用例
#include <catch2/catch.hpp>
int add(int a, int b) {
return a + b;
}
�CATCH_TEST("Add function", "[add]") {
REQUIRE(add(1, 1) == 2);
REQUIRE(add(2, 3) == 5);
}
并发HTTP请求
import asyncio
import aiohttp
async def fetch_url(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
async def main():
urls3 = [
'http://example.com',
'http://example.org',
'http://example.net'
]
tasks = [fetch_url(url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(len(result))
asyncio.run(main())
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类