2024-08-09

在Python中,可以使用matplotlib库来绘制多个图形、子图以及图中图。以下是一个示例代码,展示了如何使用matplotlib来创建包含子图的复合图形,以及如何在一个图形内嵌套另一个图形。




import matplotlib.pyplot as plt
import numpy as np
 
# 创建数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
 
# 创建一个复合图形,包含两个子图
fig, (ax1, ax2) = plt.subplots(2)
 
# 在第一个子图上绘制正弦波
ax1.plot(x, y1)
ax1.set_title('Sine Wave')
 
# 在第二个子图上绘制余弦波
ax2.plot(x, y2)
ax2.set_title('Cosine Wave')
 
# 在图中图的情况下,在第一个子图中创建一个新的子图
ax_inner = ax1.inset_axes((0.2, 0.2, 0.4, 0.4))  # 设置子图的位置和大小
ax_inner.plot(x[25:75], y1[25:75])  # 绘制中间图的数据
ax_inner.set_xlim(5, 45)  # 设置中间图的x轴范围
ax_inner.set_ylim(-1, 1)  # 设置中间图的y轴范围
ax_inner.set_title('Zoomed In Sine Wave')
 
# 显示图形
plt.show()

这段代码首先导入了matplotlib.pyplot和numpy模块。然后创建了两组数据,分别用于绘制正弦和余弦波。接着,使用plt.subplots(2)创建了一个包含两个子图的复合图形。最后,在每个子图上绘制了相应的波形,并在第一个子图中添加了一个嵌套的子图来显示数据的放大视图。使用plt.show()显示了最终的图形。

2024-08-09



import pandas as pd
 
# 读取Excel文件
df = pd.read_excel('input.xlsx')
 
# 将DataFrame保存为文本文件,使用逗号分隔
df.to_csv('output.txt', sep=',', index=False)

这段代码使用了pandas库来实现从Excel文件到文本文件的转换。首先,使用read_excel函数读取Excel文件,然后使用to_csv函数将数据保存到文本文件中,指定分隔符为逗号。index=False参数表示在输出文本文件中不包含行索引。

2024-08-09

这是一个使用Python实现的跳动爱心的简单示例。这里我们使用了turtle模块来绘制图形,并通过简单的算法来实现跳动的效果。




import turtle
import math
 
# 设置窗口大小
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("跳动的爱心")
 
# 设置爱心参数
size = 200  # 爱心大小
jump_height = 100  # 跳动高度
 
# 绘制心形
def draw_heart(t, size):
    t.color("red", "pink")
    t.startfill()
    t.begin_poly()
 
    # 左心
    t.left(140)
    t.forward(size)
    t.right(20)
    t.forward(size / 2)
    t.left(150)
    t.forward(size / 2)
    t.right(20)
    t.forward(size)
    t.left(140)
 
    # 右心
    t.forward(size)
    t.right(20)
    t.forward(size / 2)
    t.left(150)
    t.forward(size / 2)
    t.right(20)
    t.forward(size)
 
    t.color("black")
    t.end_poly()
    t.goto(t.xcor() - 3, t.ycor() + 2)
    t.begin_fill()
    t.goto(t.xcor() + 3, t.ycor() - 2)
    t.end_fill()
    t.begin_poly()
 
    # 右心
    t.left(140)
    t.forward(size)
    t.right(20)
    t.forward(size / 2)
    t.left(150)
    t.forward(size / 2)
    t.right(20)
    t.forward(size)
 
    # 左心
    t.forward(size)
    t.right(20)
    t.forward(size / 2)
    t.left(150)
    t.forward(size / 2)
    t.right(20)
    t.forward(size)
 
    t.end_poly()
    t.goto(t.xcor() - 3, t.ycor() - 2)
    t.begin_fill()
    t.goto(t.xcor() + 3, t.ycor() + 2)
    t.end_fill()
    t.endfill()
 
# 创建心形对象
heart = turtle.Turtle()
draw_heart(heart, size)
 
# 心形跳动函数
def jump():
    for _ in range(2):
        for size in range(100, 200):
            heart.shapesize(size / 100, size / 100)
            heart.sety(heart.ycor() + jump_height)
            wn.update()
            heart.sety(heart.ycor() - jump_height)
            wn.update()
 
        for size in range(200, 100, -1):
            heart.shapesize(size / 100, size / 100)
            heart.sety(heart.ycor() + jump_height)
            wn.update()
            heart.sety(heart.ycor() - jump_height)
            wn.update()
 
# 启动跳动
jump()
 
# 保持窗口打开
wn.mainloop()

这段代码使用了turtle模块来绘制心形,并通过调整形状大小来模拟心形跳动的效果。jump函数定义了心形跳动的动作,通过循环和窗口更新(wn.update())来模拟心形上

2024-08-09



import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
public class SortExample {
 
    // 二维数组按照第一列排序
    public static void sort2DArray(int[][] array) {
        Arrays.sort(array, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[0], o2[0]);
            }
        });
    }
 
    // List按照自定义规则排序
    public static void sortListWithLambda(List<String> list) {
        list.sort((s1, s2) -> s1.compareTo(s2));
    }
 
    // List按照对象属性排序
    public static <T> void sortListByObjectProperty(List<T> list, final String propertyName) {
        list.sort(new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                try {
                    // 使用反射获取属性值
                    java.lang.reflect.Field field = o1.getClass().getDeclaredField(propertyName);
                    field.setAccessible(true);
                    Object val1 = field.get(o1);
                    Object val2 = field.get(o2);
                    return ((Comparable) val1).compareTo(val2);
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
 
    public static void main(String[] args) {
        // 二维数组排序示例
        int[][] array = {{2, 1}, {4, 3}, {1, 2}};
        sort2DArray(array);
        System.out.println(Arrays.deepToString(array));
 
        // List排序示例
        List<String> strings = Arrays.asList("banana", "apple", "cherry");
        sortListWithLambda(strings);
        System.out.println(strings);
 
        // 对象列表排序示例
        List<Person> people = Arrays.asList(new Person("John", 30), new Person("Alice", 25));
        sortListByObjectProperty(people, "age");
        System.out.println(people.stream().map(p -> p.getName() + ": " + p.getAge()).collect(Collectors.toList()));
    }
 
    static class Person {
        private String name;
        private int age;
 
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
 
        public String getName() {
            return name;
        }
 
        public int getAge() {
            return age;
        }
    }
}

这个代码示例展示了如何使用Java的Arrays.sort

2024-08-09



from metpy.units import units
from metpy.calc import cape, dewpoint, theta_e, total_variate
import numpy as np
 
# 假设我们有以下数据:
temperature = np.array([20, 18, 15, 12]) * units.degC
pressure = np.array([1000, 850, 700, 500]) * units.hPa
specific_humidity = np.array([0.01, 0.02, 0.03, 0.04]) * units.kg / units.kg
 
# 计算LCL的高度
lcl_height = theta_e(temperature[0], specific_humidity[0], pressure[0]) - temperature[0]
 
# 计算对流层的高度
convective_temp = temperature - lcl_height
 
# 计算对流层的温度和湿度的总变异
t_var = total_variate(convective_temp, temperature)
h_var = total_variate(convective_temp, specific_humidity)
 
# 计算CAPE
cape_val = cape(convective_temp, specific_humidity, pressure, t_var, h_var)
 
print(f'CAPE值为: {cape_val:.2f} J/kg')

这段代码展示了如何使用Metpy库中的函数来计算CAPE值。首先,我们导入了必要的Metpy模块和numpy。然后,我们假设有气压、温度和特定湿度的数据,并使用Metpy提供的函数来计算LCL高度、对流层的气象元素、对流层气象参数的总变异以及最终的CAPE值。最后,我们打印出CAPE值,这里的结果是一个单位为J/kg的数值。

2024-08-09

冒泡排序是一种简单的排序算法,它重复地遍历要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。重复进行直到没有再需要交换的元素,这意味着数列已经排序完成。

以下是冒泡排序的Python实现:




def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr
 
# 使用示例
array = [64, 34, 25, 12, 22, 11, 90]
sorted_array = bubble_sort(array)
print("Sorted array is:", sorted_array)

这段代码首先定义了一个名为bubble_sort的函数,该函数接收一个列表arr作为参数,并通过两层循环实现冒泡排序。外层循环确定需要遍历的次数,内层循环用于比较并交换元素。最后返回排序后的数组。在使用示例中,我们创建了一个未排序的数组array,调用bubble_sort函数对其进行排序,并打印出排序后的结果。

2024-08-09



import geopandas as gpd
from shapely.geometry import Point
 
# 创建一个GeoDataFrame,包含一个点和其相关属性
data = {'location': ['P1'], 'latitude': [40.7537], 'longitude': [-73.9848]}
df = gpd.GeoDataFrame(data, geometry=gpd.points_from_xy(data.longitude, data.latitude))
 
# 打印GeoDataFrame
print(df)
 
# 将GeoDataFrame的坐标系统设置为WGS84
df.set_crs(epsg=4326, inplace=True)
 
# 创建一个点对象
point = Point(116.405285, 39.904989)
 
# 将点对象转换为GeoDataFrame
point_gdf = gpd.GeoDataFrame({'geometry': [point]})
point_gdf.crs = df.crs  # 确保两个GeoDataFrame具有相同的坐标参考系统
 
# 计算点与GeoDataFrame中所有点之间的距离
df['distance'] = df.distance(point_gdf)
 
# 打印距离计算后的GeoDataFrame
print(df)

这段代码首先导入geopandas库和shapely库中的Point类,然后创建一个GeoDataFrame,包含一个点和其相关属性。接着,将GeoDataFrame的坐标系统设置为WGS84,并创建一个点对象。最后,将点对象转换为GeoDataFrame,并计算它与原GeoDataFrame中所有点之间的距离。

2024-08-09



import pandas as pd
 
# 创建一个简单的DataFrame
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
        'Age': [28, 23, 34, 29]}
df = pd.DataFrame(data)
 
# 打印DataFrame
print(df)
 
# 将DataFrame导出到CSV文件
df.to_csv('output.csv', index=False)
 
# 从CSV文件读取数据到新的DataFrame
df_from_csv = pd.read_csv('output.csv')
 
# 打印新的DataFrame
print(df_from_csv)

这段代码展示了如何使用pandas库创建一个简单的DataFrame,并将其导出为CSV文件,然后再从CSV文件读取数据到新的DataFrame。这个过程是数据处理和分析的常见步骤,pandas库提供了丰富的功能来处理和分析数据。

2024-08-09



from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
 
class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
 
    def initUI(self):
        # 设置窗口的标题
        self.setWindowTitle('PyQt5 示例')
        # 设置窗口的大小
        self.setGeometry(300, 300, 400, 300)
        # 创建一个按钮
        self.button = QPushButton('点击我', self)
        # 设置按钮的点击事件
        self.button.clicked.connect(self.on_click)
 
    def on_click(self):
        # 当按钮被点击时,弹出一个对话框
        print('按钮被点击')
 
if __name__ == '__main__':
    app = QApplication([])
    ex = MyApp()
    ex.show()
    app.exec_()

这段代码演示了如何使用PyQt5创建一个简单的窗口应用程序,其中包含一个按钮和点击事件的处理。当用户点击按钮时,程序会在控制台打印一条消息。这个例子是PyQt5图形化界面编程的入门级示例,适合初学者学习和练习。

2024-08-09

以下是一个简化的代码示例,展示了如何在Spring Boot应用中使用Neo4j来创建和查询企业级分布式应用拓扑图:




import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
 
@NodeEntity
public class Server {
    Long id;
    String name;
    // 省略其他属性和方法
}
 
@RelationshipEntity(type="DEPLOYS")
public class Deploys {
    Long id;
    Server server;
    Application application;
    // 省略其他属性和方法
}
 
@NodeEntity
public class Application {
    Long id;
    String name;
    // 省略其他属性和方法
}
 
@Service
public class TopologyService {
 
    @Autowired
    private Neo4jClient neo4jClient;
 
    public void createApplication(Application application) {
        // 使用Neo4jClient创建应用程序节点
        neo4jClient.create(application);
    }
 
    public void createDeploymentRelationship(Server server, Application application) {
        // 创建服务器和应用程序之间的部署关系
        Deploys deploys = new Deploys(server, application);
        neo4jClient.create(deploys);
    }
 
    public List<Application> getApplicationsDeployedOnServer(Server server) {
        // 获取特定服务器上部署的应用程序列表
        return neo4jClient.query()
            .matching("(server:Server {id: $serverId})-[deploys:DEPLOYS]->(application:Application)")
            .withParam("serverId", server.getId())
            .returning("application")
            .as(Application.class)
            .fetch();
    }
}

在这个示例中,我们定义了ServerApplication和它们之间的Deploys关系。然后,我们创建了一个TopologyService,它使用Neo4jClient与图数据库进行交互。createApplication方法创建一个新的应用程序节点,而createDeploymentRelationship方法在给定的服务器和应用程序之间创建一个部署关系。最后,getApplicationsDeployedOnServer方法获取特定服务器上部署的应用程序列表。

这个简化的代码示例展示了如何在Spring Boot应用中集成Neo4j,并使用它来维护企业级分布式应用拓扑图。在实际应用中,你需要进一步完善Service层的实现,以及添加必要的控制器层来处理HTTP请求,并配置Neo4j相关的配置文件等。