2024-08-15

Remi是一个用于转换Python代码为HTML和JavaScript的库,以便可以在网络上运行GUI应用程序。Remi提供了一种简单的方法来创建动态网页,可以在浏览器中运行。

以下是一个简单的Remi示例,展示了如何创建一个简单的GUI界面:




import remi.gui as gui
from remi import start, App
 
class MyApp(App):
    def main(self):
        # creating a container VBox type, vertical (you can use also HBox or Widget)
        main_container = gui.VBox(width=300, height=200)
        # adding a button
        btn = gu.Button('Press me', style={'margin': '10px'})
        # setting action
        btn.onclick.do(self.on_button_pressed)
        # adding the button to the main container
        main_container.append(btn)
        # returning the root widget
        return main_container
 
    def on_button_pressed(self, widget):
        # setting a different style to the button
        widget.style.update({'background-color': 'red'})
 
# starts the webserver
start(MyApp)

这段代码定义了一个简单的应用程序,其中包含一个按钮。当按钮被按下时,on_button_pressed 方法会被调用,改变按钮的样式。然后,使用start函数启动应用程序,Remi将自动生成HTML和JavaScript代码,并在浏览器中显示GUI界面。

2024-08-15

要在Python中将长文HTML自动转换为PDF,可以使用weasyprint库。以下是一个简单的例子:

首先,安装weasyprint库:




pip install weasyprint

然后,使用以下Python代码将HTML转换为PDF:




from weasyprint import HTML
 
# 替换为你的HTML文件路径或URL
html_source = 'your_long_html_file.html'
pdf_file = 'output.pdf'
 
# 将HTML转换为PDF
HTML(html_source).write_pdf(pdf_file)

确保你的HTML文件包含所有必要的元素,以便weasyprint可以正确地渲染它。如果HTML文件较大或者包含复杂的CSS,可能需要额外的调整来确保最佳的转换效果。

2024-08-15

在Python中,可以使用matplotlibIPythonmatplotlib魔法命令来生成图表,并将其嵌入到HTML中。以下是一个简单的例子:

首先,安装所需的库(如果尚未安装):




pip install matplotlib ipython

然后,在Jupyter Notebook或IPython shell中使用以下代码生成图表并嵌入HTML:




%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
 
# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
 
# 创建图表
plt.plot(x, y)
plt.title('Sine Wave')
 
# 显示图表
plt.show()

上面的代码会在Notebook中直接显示图表。如果你想将图表嵌入到HTML中,可以将输出保存到文件:




# 保存图表为HTML
plt.savefig('sine_wave.html')

这会在当前目录下生成一个sine_wave.html文件,你可以用浏览器打开这个文件,查看图表。如果你需要将HTML直接嵌入到另一个HTML文件中,可以将sine_wave.html文件的内容复制到目标HTML文件的适当位置。

2024-08-15

在提供代码示例之前,我需要澄清一点:您是要创建一个小程序还是一个后端服务?因为您提到了“小程序【2024年毕设】”,我假设您想要的是一个后端服务的代码示例。

以下是使用不同编程语言创建一个简单的后端服务的示例。这些示例都使用了最基本的框架或库来保持示例的简洁。

Java:




import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

PHP:




<?php
 
$app->get('/hello', function () {
    echo 'Hello, World!';
});

Node.js:




const express = require('express');
const app = express();
 
app.get('/hello', (req, res) => {
    res.send('Hello, World!');
});
 
app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Python:




from flask import Flask
app = Flask(__name__)
 
@app.route('/hello')
def hello():
    return 'Hello, World!'

在每个例子中,我们创建了一个简单的HTTP GET端点/hello,它返回“Hello, World!”消息。这些代码示例都可以运行在相应的环境中,并且可以通过HTTP请求访问。

请注意,这些示例都没有详细的错误处理、数据库连接、认证等功能,因为我们的重点是展示如何创建一个简单的后端服务。在实际应用中,您需要添加这些功能。

2024-08-15

由于篇幅所限,以下仅展示了体育中心预约系统的部分核心功能,包括场地列表展示、场地预约流程等。具体的数据库设计、API路由设计、前端页面设计等将根据具体项目需求来实现。




# Python 3.x
# 体育中心预约系统场地列表API示例
 
from fastapi import FastAPI
from pydantic import BaseModel
 
app = FastAPI()
 
class Stadium(BaseModel):
    id: int
    name: str
    capacity: int
    location: str
 
# 假设这是从数据库获取的体育中心场地列表
stadiua = {1: Stadium(id=1, name="足球场", capacity=10000, location="中心地址"),
           2: Stadium(id=2, name="篮球场", capacity=5000, location="中心地址"),
           ...
          }
 
@app.get("/stadiua/")
def read_stadiua():
    return stadiua
 
@app.get("/stadiua/{stadium_id}")
def read_stadium(stadium_id: int):
    return stadiua.get(stadium_id)
 
# 预约流程API示例
@app.post("/stadiua/{stadium_id}/book")
def book_stadium(stadium_id: int, booking: dict):
    # 这里应包含对预约信息的验证和保存逻辑
    # 例如:保存到数据库,发送确认邮件等
    return {"message": "Successfully booked stadium."}

在这个示例中,我们使用了FastAPI框架来快速设计一个API,并使用了pydantic库来定义数据模型。这个API提供了获取体育中心所有场地列表以及对特定场地进行预约的接口。在实际应用中,你需要实现与数据库的交互,并添加额外的安全性和验证机制。

2024-08-15

本示例提供了一个超市进销存管理系统的简化版本,主要包括产品管理和销售管理的核心功能。具体实现语言使用Java,PHP,Node.js和Python中的一种。

以下是使用Java实现的简单进销存管理系统示例:




// 产品类(Product)
public class Product {
    private String name;
    private double price;
    private int quantity;
 
    // 构造函数
    public Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }
 
    // 获取产品信息
    public String getInfo() {
        return "Name: " + name + ", Price: " + price + ", Quantity: " + quantity;
    }
 
    // 销售产品
    public void sellProduct(int quantitySold) {
        this.quantity -= quantitySold;
    }
 
    // 其他的getter和setter方法
}
 
// 销售类(Sale)
public class Sale {
    private Product productSold;
    private int quantitySold;
    private double totalSale;
 
    // 构造函数
    public Sale(Product productSold, int quantitySold) {
        this.productSold = productSold;
        this.quantitySold = quantitySold;
        this.totalSale = productSold.getPrice() * quantitySold;
        productSold.sellProduct(quantitySold);
    }
 
    // 获取销售信息
    public String getSaleInfo() {
        return "Product: " + productSold.getName() + ", Quantity: " + quantitySold + ", Total Sale: " + totalSale;
    }
}
 
// 主类(SupermarketSystem)
public class SupermarketSystem {
    private List<Product> products = new ArrayList<>();
 
    // 添加产品
    public void addProduct(Product product) {
        products.add(product);
    }
 
    // 查看产品列表
    public void viewProductList() {
        for (Product product : products) {
            System.out.println(product.getInfo());
        }
    }
 
    // 进行销售
    public Sale makeSale(String productName, int quantity) {
        for (Product product : products) {
            if (product.getName().equals(productName)) {
                return new Sale(product, quantity);
            }
        }
        return null;
    }
 
    public static void main(String[] args) {
        SupermarketSystem supermarket = new SupermarketSystem();
        supermarket.addProduct(new Product("Apple", 1.0, 100));
        supermarket.addProduct(new Product("Banana", 0.50, 150));
        supermarket.viewProductList();
 
        Sale sale = supermarket.makeSale("Apple", 10);
        if (sale != null) {
            System.out.println(sale.getSaleInfo(
2024-08-15



import random
 
def go_back_n_receiver(window_size):
    """
    实现GBN接收方的模拟
    :param window_size: 接收窗口大小
    :return: 输出丢失的分组序号和重传的分组序号
    """
    expected_sequence = 0  # 期望的下一个序号
    received_packets = []  # 已接收的分组序号列表
    lost_packets = []  # 丢失的分组序号列表
    retransmitted_packets = []  # 重传的分组序号列表
 
    while True:
        sequence = random.randint(0, window_size - 1)  # 模拟收到的分组序号
        if sequence not in received_packets:  # 如果分组未重复
            received_packets.append(sequence)  # 加入接收列表
            received_packets.sort()  # 排序以便于处理
 
            # 如果序号正确,输出信息
            if sequence == expected_sequence:
                print(f"Received packet: {sequence}")
                expected_sequence = (expected_sequence + 1) % (window_size + 1)
            else:
                # 如果序号不正确且不在接收窗口内,则为丢失分组
                if sequence not in range(expected_sequence, expected_sequence + window_size):
                    lost_packets.append(sequence)
                    print(f"Lost packet: {sequence}")
                # 如果是重复分组,则为重传分组
                else:
                    retransmitted_packets.append(sequence)
                    print(f"Retransmitted packet: {sequence}")
 
    return lost_packets, retransmitted_packets
 
# 使用示例
lost_packets, retransmitted_packets = go_back_n_receiver(window_size=5)
print(f"Lost packets: {lost_packets}")
print(f"Retransmitted packets: {retransmitted_packets}")

这段代码模拟了GBN协议中接收方的行为。它随机生成分组序号,并将其与期望的序号进行比较。如果序号正确,输出接收信息;如果序号不正确且不在接收窗口内,则记为丢失分组;如果是重复分组,则记为重传分组。最后返回丢失的分组序号和重传的分组序号。

2024-08-15

Python 调用 Go 语言函数的一种方法是通过 cgo。cgo 允许 Go 程序员调用 C 语言代码,而 C 语言又可以调用各种库,包括 C 编译的二进制。因此,可以通过 cgo 调用编译好的 Go 二进制。

以下是一个简单的例子:

  1. 首先,你需要一个 Go 程序,并将其编译为共享库。



// hello.go
package main
 
import "C"
 
//export Hello
func Hello(name *C.char) *C.char {
    return C.CString("Hello, " + C.GoString(name))
}
 
func main() {}

编译为共享库:




go build -buildmode=c-shared -o libhello.so hello.go
  1. 然后,在 Python 中使用 ctypes 来加载并调用这个共享库中的函数。



from ctypes import cdll, c_char_p
 
# 加载共享库
lib = cdll.LoadLibrary('./libhello.so')
 
# 设置参数类型
lib.Hello.argtypes = [c_char_p]
 
# 设置返回类型
lib.Hello.restype = c_char_p
 
# 调用函数
result = lib.Hello(b'World')
 
# 打印结果
print(result.decode('utf-8'))

请注意,这只是一个基本示例,实际使用时可能需要处理内存释放、错误处理等。另外,这种方法有一定的局限性,例如需要将 Go 程序编译为与 Python 兼容的格式,并且可能需要处理不同的平台差异。

另一种方法是使用 gRPC 或者 HTTP 服务来实现跨语言通信,这样可以避免直接调用 Go 函数,但会增加实现的复杂度。

2024-08-15

题目:删除排序链表中的重复元素

解法:遍历链表,并比较当前节点与下一节点的值,如果发现重复,则跳过下一节点并释放它。

Java 实现:




public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
 
        ListNode current = head;
        while (current.next != null) {
            if (current.val == current.next.val) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
 
        return head;
    }
}

C 实现:




struct ListNode* deleteDuplicates(struct ListNode* head) {
    if (head == NULL) {
        return head;
    }
 
    struct ListNode* current = head;
    while (current->next != NULL) {
        if (current->val == current->next->val) {
            current->next = current->next->next;
        } else {
            current = current->next;
        }
    }
 
    return head;
}

Python3 实现:




class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
 
        current = head
        while current.next:
            if current.val == current.next.val:
                current.next = current.next.next
            else:
                current = current.next
        return head

Go 实现:




/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    if head == nil {
        return head
    }
 
    current := head
    for current.Next != nil {
        if current.Val == current.Next.Val {
            current.Next = current.Next.Next
        } else {
            current = current.Next
        }
    }
 
    return head
}
2024-08-15

在Python和Go之间互相调用一个函数有两种常见的方法:使用Cython或者使用gRPC。

  1. 使用Cython:

    Cython是一个可以将Python代码编译为C的编译器,可以用来调用Go编写的函数。

Go代码(example.go):




package main
 
import "C"
 
//export Sum
func Sum(a, b int) int {
    return a + b
}
 
func main() {}

Python代码(example.pyx):




# distutils: language = c++
# distutils: sources = example.go
from cpython.ref cimport PyCapsule
 
cdef extern from "Python.h":
    object PyCapsule_New(void *pointer, char *name, PyCapsuleDestructor destructor)
 
cdef extern from "example.h":
    int Sum(int a, int b)
 
def py_sum(a, b):
    return Sum(a, b)
  1. 使用gRPC:

    gRPC是一个高性能、开源和通用的RPC(远程过程调用)框架,它可以在多种语言之间工作。

Go代码(greeter_server.go):




package main
 
import (
    "net"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"
)
 
const (
    port = ":50051"
)
 
// server structure
type server struct{}
 
// GreeterClient is the client API for Greeter service.
// We can define multiple gRPC service in the same .proto file.
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GreeterClient interface {
    SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}
 
func (s *server) SayHello(ctx context.Context, in *HelloRequest) (*HelloReply, error) {
    return &HelloReply{Message: "Hello " + in.Name}, nil
}
 
func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        panic(err)
    }
    s := grpc.NewServer()
    reflection.Register(s)
    RegisterGreeterServer(s, &server{})
    if err := s.Serve(lis); err != nil {
        panic(err)
    }
}

Python代码(greeter_client.py):




import grpc
 
from greeter_pb2 import HelloRequest
from greeter_pb2_grpc import GreeterStub
 
with grpc.insecure_channel('localhost:50051') as channel:
    stub = GreeterStub(channel)
    response = stub.SayHello(HelloRequest(Name='World'))
 
print("Greeter client received: " + response.Message)

在这两种方法中,使用Cython的方法更为直接,但是它需要你写Cython代码并且处理C类型的数据。使用gRPC的方法更为复杂,但是它提供了一个更为通用和灵活的方式来在不同语言之间进行通信。