我们大多数人完成大学时可能不再需要写数学。但是,作为软件开发人员,拥有一些基本的数学技能非常重要,因为有时我们确实需要它们。 After a few years of working as a software engineer for the backend role in different domains, this experience made me realize that our interaction with any website on the world's biggest database World Wide Web (WWW) is secured and encrypted when HTTPS/SSL enabled, to make sure these protocols are secured then math is a central part of this formula, where different cryptography techniques employed such as digital signatures, one-way hashing functions, and key exchange协议。在某些领域(例如区块链)中,它们在技术上工作的基本原则是基于单向哈希函数以及数字理论的,在该范围内,非正式地给出了[数学] q [/MATH]和[MATH] P = Q * K [/MATH],那么它在计算上是无法确定的数字[MATH] K [/MATH],在这种情况下可以是私人KEY。从其他任何地方都可以找到哈希功能,从使用不同技术(例如可调地理存储(CAS))设计(不可变的)缓存服务到使用校验和使用校验和的错误检测服务,以便使用MD5或CRC(CYCLIC RECHUNDANCH CHECK)验证数据完整性。
我们之间的分散数学也很普遍。关系数据库采用了SET理论中的许多概念,其中表代表关系的关系,其中每一行被视为元组,并且表中的所有行都被视为一组元组。 SQL操作,例如联合,相交或除外,也对应于设定的理论操作。编写代码和图表时,布尔代数用于控制流和决策。例如,逻辑对于程序的正确性至关重要,例如,我们可以写下一阶逻辑语句,例如[Math] Forall I,j:(1 leq i 概率和统计数据在我们的工作中也起着重要作用。例如,我们如何设计哈希功能来最大程度地减少碰撞的机会,但同时又是高效且性能?那时我们需要使用概率来计算碰撞的机会。从用户行为预测到响应时间预测的各种任务,也可以经常使用诸如线性回归的统计技术。例如,如果负载是15个并发到Web服务的请求,那么这些请求的预期响应时间是什么? 最近,我有机会将我所学到的所有知识都投入了更认真的练习中,并在途中学习了一些新的有趣的主题,例如数据压缩, Kolmogorov复杂性,熵的概念,名为四重奏树(一个未根除的二进制树(一种未根除的二进制树),具有至少4个节点,至少是针对系统发育分类的4个节点),用于设计有效地进行了实力的效率和型号的构造,以构建一个函数型的型号,以进行构建型转换。我花了很多时间与他们相处。最后,在概念层面上理解它们并不太遥远,编写代码来测试我们的理解以形成它们的连贯图片,这可能需要更多的工作,但是您越了解它,就越有趣的事情就会展现出来,您将更加欣赏基础知识。 我们都知道,布尔类型的值可以采用一个正确或false的确切值:[Math] Mathbb {b} = { text {true}, text {felts {false} } [/MATH]。布尔代数研究了我们可以与它们一起做的这些布尔值和操作。我们可以在编码中使用它,以使我们的代码通过简化逻辑条件更易于理解。 我想给出的第一个示例是,我们可以使用de Morgan的定律来简化我们的代码。该规则可以表示如下:[MATH] neg(a land B) equiv equiv neg a lor neg b \ neg(a lor b) equiv equiv equiv neg a neg a land land neg b [/MATH] 这意味着A和B的否定与A或B的否定为A和B。A或B的否定与A或B相同。 我们可以使用de Morgan的定律将布尔表达转变为相当的东西以提高可读性: 此外,它具有短路评估的额外好处,这意味着,如果第一个布尔表达式已经是正确的,那么不需要计算其余的if语句。 例如,我们想找出状态未完成且付款未能失败的订单: 同样,DE Morgan定律也可以通过进行短路评估来优化SQL查询性能: 假设我们正在研究电子商务应用程序,客户可以在其中订购产品,然后在提交订单之前,我们的服务将检查折扣排除规则,并在其他人排除的情况下删除一些折扣。如果我们有2个折扣互相折扣,那么我们将保持更高的优先级。我们可以定义以下内容: 篮子[MATH] B [/MATH]:目前在篮子中的一组折扣 排除集[数学] 优先函数[MATH] P(C)[/MATH]:返回折扣数值优先级的函数[MATH] C [/MATH] 相互排除:如果[Math] C'在E(C)[/MATH] [/MATH]和[MATH] C in E(C')中,则两个折扣[MATH] C [/MATH]和[MATH] C'[/MATH]是相互排斥的。 单方面排除:折扣[MATH] C [/MATH]如果[Math] C'在E(C)[/MATH] [/MATH]和[MATH] C notin E(C'C'(C')[/MATH] [/MATH)中,将折扣排除在篮子中的折扣[MATH] C'[/MATH]。 我们还假设为简单起见,篮子里没有圆形排除 现在,让我们在Python中写下给定的定义和要求的代码: 图理论概念也可以在软件开发中广泛使用,最受欢迎的用例之一是依赖性解决方案。给定需要部署的服务列表,这里有些服务可能取决于其他服务,因此我们需要按正确的顺序部署服务,在该服务中必须在服务本身之前启动一项服务的依赖性。 首先,我们可以定义一些我们将用于此问题的图理论定义: [MATH] G =(V,E)[/MATH] [MATH] V [/MATH]:一组顶点,每个都代表服务 [MATH] E [/MATH]:有向边的集合,其中[MATH](S_I,S_J)[/MATH]表示[MATH] S_I [/MATH]取决于[MATH] S_J [/MATH] 拓扑排序: 找到一个订单[MATH] [S_1,S_2,S_3,…,S_N] [/MATH],以便: [Math] forall(s_i,s_j)在e:[/MATH]服务[MATH] S_J [/MATH]服务[MATH] S_I [/MATH]之前已部署S_J [/MATH] 如果有循环依赖性,则部署顺序无效 为了找到部署的正确顺序,我们使用有向图来表示服务和依赖关系,我们将首先部署零依赖项的服务(该节点的传入依赖关系为零)。我们将每项服务添加到队列中,检查其依赖项,并将收入度增加一个服务的每个依赖关系,一旦部署了服务,就必须将其从队列中删除,并且依赖服务的服务必须相应地更新其依赖性列表,最后,我们在系统中部署了每个服务,否则,E否则将在图形中进行某个圆周周期,我们将无法部署该服务。这是Python中的实现: 我们每天都在使用Internet和Web应用程序。如果启用了HTTPS,则确定我们的设备与Web服务器之间的连接,因此,如果有黑客试图拦截请求并提取有效载荷以获取我们的敏感信息,例如信用卡号,则此尝试将失败,因为数据已加密。为了使信息安全,E和双方都可以验证对方的合法性,数学在此过程中起着核心作用。 为了使数据安全,HTTPS主要使用对称密钥加密来交换各方之间的数据。这意味着它使用相同的密钥进行加密(将普通数据转换为人类无法读取的东西)和解密(将无法读取的内容转换为原始的普通消息)。 为此,双方都必须就可以使用的共享秘密密钥达成共识,以便在发送实际消息之前相互通信。但是,如何通过不安全的渠道共享共享的秘密密钥呢?当时,我们需要了解Diffie-Hellman密钥交换(DHKE),该交流利用模块化算术,质数和共同的秘密。以下是如何使用DHKE来实现这一目标的步骤: 双方都同意可以自由共享的公共参数: 一个大的素数[数学] P [/MATH] 原始的根模量[数学] P [/MATH],称为[MATH] G [/MATH] 聚会[数学] A [/MATH]选择一个私人秘密[MATH] A [/MATH](随机数)并计算公共价值,然后将其发送给Party [Math] B [/Math]: [数学] a_ {public} = g^{a} mod P [/Math] [数学]然后将A_ {public} [/MATH]发送到Party [Math] B [/Math] 同样,Party [Math] B [/Math]选择一个私人秘密[MATH] B [/MATH],并从私钥中计算公共价值,然后将其发送给Party [Math] A [/Math]: [数学] b_ {public} = g^b mod p [/数学] [MATH] B_ {public} [/MATH]然后发送到派对[MATH] A [/MATH] 双方都计算共同的秘密: Party [Math] A [/MATH]计算:[MATH] text {共享秘密} =(b_ {public})^a mod p [/math] Party [Math] B [/MATH]计算:[MATH] text {共享秘密} =(a_ {public})^b mod p [/math] [MATH] text {sharedSecret} _a =(b_ {public})^a mod p =(g^b mod p)^a = g^{ba} mod p [/math] [MATH] text {sharedSecret} _b =(a_ {public})^b mod p =(g^a mod p)^b = g^{ab} mod p [/math] [MATH] text {sharedSecret} _a = g^{ba} mod p = g^{ab} mod p = text {sharedSecret} _b [/Math] 一旦双方从DHKE获得共享密钥,然后将密钥在AES(高级加密标准)中使用,以对实际消息进行加密和解密。这是Python实施: 有时,我们需要找出位置或字节的总数,以分配哈希表中的键。当将两个不同的键映射到相同的哈希值时,此时我们会有哈希碰撞。我们需要做出明智的决定,以最大程度地减少此事件的机会,但还需要考虑将需要多少空间,以便我们可以在正确性和存储效率之间进行平衡。任何偶然发生的事情都有一定的概率,当时,我们可以在实施任何哈希功能之前从学校中学到的一些基本概率理论。 实际案例的一个例子之一是,我们需要实施一个有效的不变的缓存策略,在该策略中,每个缓存条目都如此小,以至于我们可以永远存储它。当用户将文件上传到我们的应用程序时,我们希望从中存储一些有用的信息。因此,稍后,如果文件的内容没有更改,那么我们可以使用缓存的值而不是再次进行计算。我们确实使用CRC(循环冗余检查)来生成缓存键和缓存值。 如果我们将CRC-16用于缓存生成,那么这意味着我们有一个总[MATH] 2^{16} = 65536 [/MATH],该值可能会落入内部。似乎有很多空间可以备用空间,但是如果我们已经缓存999个文件并且没有碰撞,则可以将系统上1000碰撞的机会计算为: [MATH] text {给定:} \ n = 2^{16} text {(CRC-16)}}} \ k = 1000 text {(缓存条目的数量)} \ \ text {k entries is kenties is:} cortion is:} \ p contimis conties}的可能性 prod_ {i = 0}^{k-1} frac {ni} {n} \ p( text {collision})= 1 - p( text {no collision})\ p( text {collision}) frac {2^{16} -i} {2^{16}} \ p( text {collision})= 1 - frac {65536 cdot 65535 cdot 65535 cdot 65534 cdot… text {计算此确切的值:} \ p( text {collision})= 0.999548…[/MATH] 因此,如果使用CRC-16,则在1000个文件上至少发生1次碰撞的概率是关于[Math] 99.95 %[/MATH]。几乎可以肯定,我们希望我们的服务可以处理这一数量的文件,这就是为什么我们然后将CRC-32用于缓存密钥生成目的,并且具有与上面相同的步骤,至少要获得一个哈希碰撞的概率几乎是[MATH] 0.0116 %%[/MATH]用于1000个文件。 假设我们有一个小数据集,在该数据集中,我们在系统中以一定数量的并发请求跟踪系统中的实际响应时间: 现在,我们可以对服务器中的响应时间进行预测30个并发请求。我们可以使用线性回归对响应时间和并发请求的数量进行建模。这是公式: [数学] y = beta_0 + beta_1 x [/MATH] 我们将[数学] y [/MATH]作为系统中的响应时间,它是一个因变量,取决于[Math] X [/Math]的值。我们在这里拥有的[MATH] X [/MATH]变量是我们在系统中想要的并发请求的数量。 因此,在这里,我们已经知道[MATH] X = 30 [/MATH],我们需要根据公式:[MATH] BETA_0 [/MATH]和[MATH] BETA_1 [/MATH]基于公式: [MATH] beta_1 = frac { sum_ {i = 1}^n(x_i - bar {x})(y_i - bar {y})} { sum_ {i = 1} bar {x} [/MATH] 要查找[MATH] bar {x} [/MATH],我们只需要计算左列中不同并发请求的平均值,并且类似地计算出[MATH] BAR {y} [/MATH]我们计算右列中的平均响应时间。 目前,我们有足够的信息编写一些Python代码来预测30个并发请求的响应时间: 对于30个并发请求,我们预计我们的系统将需要600毫秒来响应 在处理Cormarearn 2.0的时间里,我们需要创建一个四重奏树的3D可视化,以显示不同输入对象的NCD矩阵的分层群集。为了让用户放大和缩小以不同的尺度观看树,同时保持每个节点的层次结构顺序和相对位置,我需要使用线性转换,我们在线性代数类中研究的线性转换来解决此问题。我们在这里使用的一种特殊的转换是扩展,如果满足这2个属性,则是线性转换: 添加性:[MATH] T(U + V)= T(U) + T(V)[/MATH](向量添加) 同质性:[MATH] T(CU)= CT(U)[/MATH](标量乘法) 为了简化这一点,当有2个坐标[Math](x,y)[/Math]时,我们可以尝试使用2D四重奏树,然后我们将[Math] S [/Math]用作缩放系数。如果[Math] S> 1 [/Math],则树会展开,而如果[Math] S <1 [/Math],则树会收缩。 [数学](x',y')[/MATH]的缩放位置可以计算为: [MATH] begin {bmatrix} x { prime} \ y { prime} end {bmatrix} begin {bmatrix} s&0 \ 0&s end&s end End {bmatrix} 如果我们对四重奏树有5个不同的节点,则具有给定的位置: [MATH] MATHBF {p} _ text {prinitial} = begin {bmatrix} 0&0 \ 1&1&1&1&1&1&1&1&-1&-1&-1&-1&-1&-1 end {bmatrix} [bmatrix} [/math]。 这意味着我们的第一个节点的值为(0,0),第二个节点,值(1,1)等。然后,我们尝试将树缩放2倍。这就是我们的工作方式: [MATH] MATHBF {P} _ text {变换} = Mathbf {p} _ text {prinist} cdot begin begin {bmatrix} s&0&s&s&s&s&s end end end end end end end end end en 最终位置( s = 2 ): [MATH] MATHBF {p} _ text {变换} = begin {bmatrix} 0&0&0 \ 2&2&2 \ - 2&2&2 \ 2&-2&-2 - 2&-2&-2&-2&-2&-2 end {bmatrix}布尔代数和逻辑
if not (is_logged_in and has_permission): return ACCESS_DENIED
if not (is_logged_in and has_permission): return ACCESS_DENIED
if not is_logged_in or not has_permission: return ACCESS_DENIED
if not is_logged_in or not has_permission: return ACCESS_DENIED
select * from orders where not (status = 'completed' and payment = 'failed')
select * from orders where not ( status = 'completed' and payment = 'failed' )
select * from orders where status != 'completed' or payment != 'failed'
select * from orders where status != 'completed' or payment != 'failed'
使用设定操作的排除规则
class Discount: def __init__(self, name, priority): self.name = name # Unique name of the discount self.priority = priority # Priority of the discount self.exclusions = set() # Set of discounts this discount excludes def add_exclusion(self, discount): self.exclusions.add(discount) def __repr__(self): return f"Discount(name={self.name}, priority={self.priority})" def resolve_discounts(basket_discounts): """ Resolves discounts in a basket_discounts based on exclusion and priority rules. Parameters: basket_discounts (set): A set of Discount objects in the basket_discounts. Returns: set: A stable basket_discounts with all conflicts resolved. """ to_remove = set() # Track discounts to be removed for discount in basket_discounts: for excluded in discount.exclusions: if excluded in basket_discounts: # Only handle conflicts within the basket_discounts # Resolve based on priority if discount.priority >excluded.priority: to_remove.add(excluded) else: to_remove.add(discount) break basket_discounts -= to_remove return basket_discounts if __name__ == "__main__": discount_a = Discount("A", 3) discount_b = Discount("B", 2) discount_c = Discount("C", 1) discount_a.add_exclusion(discount_b) discount_b.add_exclusion(discount_c) discount_c.add_exclusion(discount_a) basket_discounts = {discount_a, discount_b, discount_c} stable_basket_discounts = resolve_discounts(basket_discounts) print("Basket discounts: ", stable_basket_discounts) # Basket discounts: {Discount(name=A, priority=3)}
class Discount : def __init__ (self, name, priority): self .name = name # Unique name of the discount self .priority = priority # Priority of the discount self .exclusions = set () # Set of discounts this discount excludes def add_exclusion (self, discount): self .exclusions.add(discount) def __repr__ (self): return f "Discount(name= {self .name } , priority= {self .priority } )"def resolve_discounts (basket_discounts): """ Resolves discounts in a basket_discounts based on exclusion and priority rules. Parameters: basket_discounts (set): A set of Discount objects in the basket_discounts. Returns: set: A stable basket_discounts with all conflicts resolved. """ to_remove = set () # Track discounts to be removed for discount in basket_discounts: for excluded in discount.exclusions: if excluded in basket_discounts: # Only handle conflicts within the basket_discounts # Resolve based on priority if discount.priority > excluded.priority: to_remove.add(excluded) else : to_remove.add(discount) break basket_discounts -= to_remove return basket_discountsif __name__ == "__main__" : discount_a = Discount( "A" , 3 ) discount_b = Discount( "B" , 2 ) discount_c = Discount( "C" , 1 ) discount_a.add_exclusion(discount_b) discount_b.add_exclusion(discount_c) discount_c.add_exclusion(discount_a) basket_discounts = {discount_a, discount_b, discount_c} stable_basket_discounts = resolve_discounts(basket_discounts) print ( "Basket discounts: " , stable_basket_discounts) # Basket discounts: {Discount(name=A, priority=3)}
图理论和依赖分辨率
from collections import defaultdict, deque def resolve_dependencies(services, service_dependencies): """ Resolve the deployment order of services based on multiple dependencies. Parameters: services (list): List of all services. service_dependencies (dict): Dictionary where each service is mapped to a list of services it depends on. Returns: list: Deployment order of services, or raises an error if a cycle is detected. """ # Build graph and in-degree map graph = defaultdict(list) in_degree = {service: 0 for service in services} # For each service, add its dependencies in the graph and update in-degrees for service, dependencies in service_dependencies.items(): for dependency in dependencies: graph[dependency].append(service) in_degree[service] += 1 # Initialize queue with nodes having in-degree = 0 queue = deque([s for s in services if in_degree[s] == 0]) deployment_order = [] while queue: current = queue.popleft() deployment_order.append(current) for neighbor in graph[current]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) # Check if there are nodes left with non-zero in-degree (cycle detection) if len(deployment_order) != len(services): raise ValueError("Circular dependency detected, deployment order is not possible.") return deployment_order # Example Usage if __name__ == "__main__": services = ["Database", "API", "Frontend", "Cache"] service_dependencies = { "API": ["Database"], # API depends on Database "Frontend": ["API"], # Frontend depends on API "Cache": ["Database"], # Cache depends on Database "Database": [] # Database has no dependencies } try: order = resolve_dependencies(services, service_dependencies) print("Deployment Order:", order) except ValueError as e: print(e) # Deployment Order: ['Database', 'API', 'Cache', 'Frontend']
from collections import defaultdict, dequedef resolve_dependencies (services, service_dependencies): """ Resolve the deployment order of services based on multiple dependencies. Parameters: services (list): List of all services. service_dependencies (dict): Dictionary where each service is mapped to a list of services it depends on. Returns: list: Deployment order of services, or raises an error if a cycle is detected. """ # Build graph and in-degree map graph = defaultdict( list ) in_degree = {service: 0 for service in services} # For each service, add its dependencies in the graph and update in-degrees for service, dependencies in service_dependencies.items(): for dependency in dependencies: graph[dependency].append(service) in_degree[service] += 1 # Initialize queue with nodes having in-degree = 0 queue = deque([s for s in services if in_degree[s] == 0 ]) deployment_order = [] while queue: current = queue.popleft() deployment_order.append(current) for neighbor in graph[current]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0 : queue.append(neighbor) # Check if there are nodes left with non-zero in-degree (cycle detection) if len (deployment_order) != len (services): raise ValueError ( "Circular dependency detected, deployment order is not possible." ) return deployment_order# Example Usageif __name__ == "__main__" : services = [ "Database" , "API" , "Frontend" , "Cache" ] service_dependencies = { "API" : [ "Database" ], # API depends on Database "Frontend" : [ "API" ], # Frontend depends on API "Cache" : [ "Database" ], # Cache depends on Database "Database" : [] # Database has no dependencies } try : order = resolve_dependencies(services, service_dependencies) print ( "Deployment Order:" , order) except ValueError as e: print (e)# Deployment Order: ['Database', 'API', 'Cache', 'Frontend']
模块化算术启用安全连接

import random from hashlib import sha256 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import os # Diffie-Hellman Key Exchange def generate_private_key(): """Generate a private key (random number).""" return random.randint(2, 2**16) def compute_partial_key(private_key, g, p): """Compute the public partial key.""" return pow(g, private_key, p) def compute_shared_key(partial_key, private_key, p): """Compute the shared key.""" return pow(partial_key, private_key, p) # Symmetric Encryption using AES def encrypt_message(key, plaintext): """Encrypt a message using AES.""" key = sha256(key.to_bytes(32, 'big')).digest() # Derive a 256-bit key iv = os.urandom(16) # Random initialization vector cipher = Cipher(algorithms.AES(key), modes.CFB(iv)) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize() return iv, ciphertext def decrypt_message(key, iv, ciphertext): """Decrypt a message using AES.""" key = sha256(key.to_bytes(32, 'big')).digest() # Derive a 256-bit key cipher = Cipher(algorithms.AES(key), modes.CFB(iv)) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() return plaintext.decode() # Main Demonstration if __name__ == "__main__": # Public parameters (agreed upon by both parties) p = 23 # A prime number g = 5 # A primitive root modulo p # Party A generates private and public keys private_key_a = generate_private_key() partial_key_a = compute_partial_key(private_key_a, g, p) # Party B generates private and public keys private_key_b = generate_private_key() partial_key_b = compute_partial_key(private_key_b, g, p) # Both parties compute the shared key shared_key_a = compute_shared_key(partial_key_b, private_key_a, p) shared_key_b = compute_shared_key(partial_key_a, private_key_b, p) # Verify the shared key is the same assert shared_key_a == shared_key_b, "Shared keys do not match!" # Use the shared key for encryption message = "Hello, secure world!" iv, ciphertext = encrypt_message(shared_key_a, message) print("Ciphertext:", ciphertext) # Decrypt the message decrypted_message = decrypt_message(shared_key_b, iv, ciphertext) print("Decrypted Message:", decrypted_message) # Ciphertext: b'Kvx02xc3#oxb2nx0b!%QXXxa5x98uxcaj4' # Decrypted Message: Hello, secure world!
import randomfrom hashlib import sha256from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modesimport os# Diffie-Hellman Key Exchangedef generate_private_key (): """Generate a private key (random number).""" return random.randint( 2 , 2 ** 16 )def compute_partial_key (private_key, g, p): """Compute the public partial key.""" return pow (g, private_key, p)def compute_shared_key (partial_key, private_key, p): """Compute the shared key.""" return pow (partial_key, private_key, p)# Symmetric Encryption using AESdef encrypt_message (key, plaintext): """Encrypt a message using AES.""" key = sha256(key.to_bytes( 32 , 'big' )).digest() # Derive a 256-bit key iv = os.urandom( 16 ) # Random initialization vector cipher = Cipher(algorithms.AES(key), modes.CFB(iv)) encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize() return iv, ciphertextdef decrypt_message (key, iv, ciphertext): """Decrypt a message using AES.""" key = sha256(key.to_bytes( 32 , 'big' )).digest() # Derive a 256-bit key cipher = Cipher(algorithms.AES(key), modes.CFB(iv)) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() return plaintext.decode()# Main Demonstrationif __name__ == "__main__" : # Public parameters (agreed upon by both parties) p = 23 # A prime number g = 5 # A primitive root modulo p # Party A generates private and public keys private_key_a = generate_private_key() partial_key_a = compute_partial_key(private_key_a, g, p) # Party B generates private and public keys private_key_b = generate_private_key() partial_key_b = compute_partial_key(private_key_b, g, p) # Both parties compute the shared key shared_key_a = compute_shared_key(partial_key_b, private_key_a, p) shared_key_b = compute_shared_key(partial_key_a, private_key_b, p) # Verify the shared key is the same assert shared_key_a == shared_key_b, "Shared keys do not match!" # Use the shared key for encryption message = "Hello, secure world!" iv, ciphertext = encrypt_message(shared_key_a, message) print ( "Ciphertext:" , ciphertext) # Decrypt the message decrypted_message = decrypt_message(shared_key_b, iv, ciphertext) print ( "Decrypted Message:" , decrypted_message)# Ciphertext: b'Kvx02xc3#oxb2nx0b!%QXXxa5x98uxcaj4'# Decrypted Message: Hello, secure world!
计算哈希功能发生碰撞的机会
简单的线性回归以预测响应时间
并发请求( x )
响应时间( y )(ms)
5
100
10
200
15
300
20
400
25
500
import numpy as np import matplotlib.pyplot as plt # Dataset: Number of concurrent requests (x) and response time (y) x = np.array([1, 5, 10, 15, 20]) # Number of concurrent requests y = np.array([20, 100, 200, 300, 400]) # Response time in milliseconds # Step 1: Compute the mean of x and y x_mean = np.mean(x) y_mean = np.mean(y) # Step 2: Compute beta_1 (slope) and beta_0 (intercept) beta_1 = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean)**2) beta_0 = y_mean - beta_1 * x_mean print(f"Linear Regression Equation: y = {beta_0:.2f} + {beta_1:.2f}x") # Step 3: Predict response time for 30 concurrent requests def predict_response_time(concurrent_requests): return beta_0 + beta_1 * concurrent_requests x_new = 30 # Number of concurrent requests y_pred = predict_response_time(x_new) print(f"Predicted response time for {x_new} concurrent requests: {y_pred:.2f} ms") # Step 4: Visualization plt.scatter(x, y, color='blue', label='Data points') # Original data points plt.plot(x, beta_0 + beta_1 * x, color='red', label='Regression line') # Regression line # Extrapolation x_extrapolated = np.append(x, x_new) y_extrapolated = beta_0 + beta_1 * x_extrapolated plt.plot(x_extrapolated, y_extrapolated, linestyle='dashed', color='gray', label='Extrapolated line') # Highlight prediction point plt.scatter(x_new, y_pred, color='green', label=f'Prediction (x={x_new})') # Plot labels and legend plt.xlabel('Number of Concurrent Requests') plt.ylabel('Response Time (ms)') plt.title('Response Time Prediction using Linear Regression') plt.legend() plt.grid(True) plt.show()
import numpy as npimport matplotlib.pyplot as plt# Dataset: Number of concurrent requests (x) and response time (y)x = np.array([ 1 , 5 , 10 , 15 , 20 ]) # Number of concurrent requestsy = np.array([ 20 , 100 , 200 , 300 , 400 ]) # Response time in milliseconds# Step 1: Compute the mean of x and yx_mean = np.mean(x)y_mean = np.mean(y)# Step 2: Compute beta_1 (slope) and beta_0 (intercept)beta_1 = np.sum((x - x_mean) * (y - y_mean)) / np.sum((x - x_mean) ** 2 )beta_0 = y_mean - beta_1 * x_meanprint ( f "Linear Regression Equation: y = { beta_0 :.2f } + { beta_1 :.2f } x" )# Step 3: Predict response time for 30 concurrent requestsdef predict_response_time (concurrent_requests): return beta_0 + beta_1 * concurrent_requestsx_new = 30 # Number of concurrent requestsy_pred = predict_response_time(x_new)print ( f "Predicted response time for { x_new } concurrent requests: { y_pred :.2f } ms" )# Step 4: Visualizationplt.scatter(x, y, color = 'blue' , label = 'Data points' ) # Original data pointsplt.plot(x, beta_0 + beta_1 * x, color = 'red' , label = 'Regression line' ) # Regression line# Extrapolationx_extrapolated = np.append(x, x_new)y_extrapolated = beta_0 + beta_1 * x_extrapolatedplt.plot(x_extrapolated, y_extrapolated, linestyle = 'dashed' , color = 'gray' , label = 'Extrapolated line' )# Highlight prediction pointplt.scatter(x_new, y_pred, color = 'green' , label = f 'Prediction (x= { x_new } )' )# Plot labels and legendplt.xlabel( 'Number of Concurrent Requests' )plt.ylabel( 'Response Time (ms)' )plt.title( 'Response Time Prediction using Linear Regression' )plt.legend()plt.grid( True )plt.show()
线性转换和3D四重奏-Tree可视化