Front-end and back-end interactive calculators

ppinknic 2023-10-21 19:40:56

目录

 

Introduction 

Link to the finished project code

Personal Information

PSP Table

Presentation of the Finished Product

Basic calculator functions

Extended function

Design and Implementation Process

Code Explanation

Front-end:

Back-end:

Personal Journey and Learnings


Introduction 

This blog post is based on a further refinement of the EE308's first assignment.

In this job, in addition to the basic functions of the front end of the web page calculator, the calculation data needs to be stored in the back end to separate the front and back sections of the calculator.

Link to the finished project code

iam-Yue/Assignment2 (github.com)

Personal Information

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentImplement front-end and back-end interactive calculators
MU STU ID and FZU STU ID<21124931_832101117>

PSP Table

PSPEstimated Time(minutes)Actual Time(minutes)
Planning1010
• Estimate1010
Development810980
• Analysis120180
• Design Spec3030
• Design Review2020
• Coding Standard1010
• Design8080
• Coding500600
• Code Review2020
• Test3040
Reporting6060
• Test Repor2020
• Size Measurement1010
• Postmortem & Process Improvement Plan3030
合计8801050

 

Presentation of the Finished Product

Basic calculator functions

1. +, -, *, /, %

 2. Clear and roll back

3. Read history

 

 

Extended function

1. Calculate radical sign, trigonometric function, log

2. Implement bracket computation

 

 

 

3. Better looking UI interface

Design and Implementation Process

Front end:

1. Create an HTML page with an input field and a button for the user to enter the expression to be evaluated.
2. Add a div element to the page to display the results.
3. Use JavaScript to monitor the button click event. When the user clicks the button, the expression in the input box is obtained and sent to the back-end.
4. Use CSS for web UI design.

The back end:

1. Create a back-end server, implemented in the python language.
2. Create a Flask routing handler on the server side to receive requests sent by the front end.
3. In the route handler, get the expression sent by the front end, connect to the MySQL database and perform related operations.
4. The result is returned to the front end and the history is displayed on the database.

Front and back end interaction:

 

Code Explanation

Front-end:

There is not much difference between the front end and the first job, only the addition of other functions and page optimization of the calculator on the basis of the first time. It is important to implement the connection interaction with the back end in Javascript.

Request to send POST

function equal(){
    try{
        var exp = document.form.show.value
    if(exp){
        document.form.show.value = eval(exp)  
        if(eval(exp)=="Infinity")
        {
            document.form.show.value="error";
        }
        var result=eval(exp)  
        var xhr= new XMLHttpRequest
        xhr.open('POST','http://127.0.0.1:5000/get_history',true);
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText);
            }
        };
        const data = {
            calculation: exp,
            result: result
            };
            xhr.send(JSON.stringify(data));
    }    
    }
    catch{
        document.form.show.value = "error"
    }
}

Request to send GET 

function gethistory(){
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://127.0.0.1:5000/get_calculation', true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            Data = JSON.parse(xhr.responseText);
            array = Data['data'];
            let str="";
            for(let i=0;i<array.length;i++){
                str +=array[i][0]+" = "+array[i][1]+"\n";               
            }
            document.form.show.value=string         
        }
      }
    };
    xhr.send();
 }

Calculator various functional codes 

function clean(){
    document.form.show.value = ""
}
function back(){
    var text = document.form.show.value
    len = text.length
    document.form.show.value = text.substring(0,text.length-1)
}
function sin(){
    equal()
    var angle = document.form.show.value
    var view =  Math.sin(angle/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view           
}
function cos(){
    equal()
    var angle = document.form.show.value
    var view =  Math.cos(angle/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view
}
function tan(){
    equal()
    var angle = document.form.show.value
    var view =  Math.tan(angle/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view
}
function ln(){
    equal()
    document.form.show.value = Math.log10(document.form.show.value)
}
function sqrt(){
    equal()
    document.form.show.value = Math.sqrt(document.form.show.value)
}
function factorial(n) {  
    let result = 1
    for(let i = 1; i <= n; i++) {  
        result *= i
    }  
    return result
}
function jiecheng(){
    equal()
    document.form.show.value = factorial(document.form.show.value)
}  
function insert_num(num){
    document.form.show.value += num
    return document.form.show.value
}
function insert_op(op){
    var text = document.form.show.value
    var len = text.length
    if(text[len-1]<'0'||text[len]>'9'){
        
        document.form.show.value = text.substring(0,text.length-1)
    }
    document.form.show.value += op
}
function display(op){
    var text = document.form.show.value
    text+=op
    document.form.show.value=text
}

Back-end:

At the back end, pymysql+Flask is used to remotely connect the database, and the overall interaction between the front and back ends is realized.

Connecting front-end

#导入库
from flask import Flask, request, jsonify
import pymysql
from flask_cors import CORS
import datetime

#连接MySQL数据库
con = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123456',
    database='CalculatorData'
)

app = Flask(__name__)
CORS(app)
cursor = con.cursor()

Read the front-end records and store them in the database

@app.route('/get_history', methods=['POST'])
def get_history():
        data = request.get_json()
        expression = data.get('expression')
        result = data.get('result')

        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data = (time, expression, result)
        insert = "INSERT INTO web_calculate VALUES (%s, %s, %s)"
        cursor.execute(insert, data)
        con.commit()

        response_message = "ok"
        return jsonify({"message": response_message})

 Read the back-end database so that records can be returned when ans is pressed

@app.route('/get_calculation', methods=['GET'])
def get_calculation():
        cursor.execute("SELECT expression, result FROM web_calculate ORDER BY time DESC LIMIT 10")
        data = cursor.fetchall()
        return jsonify({"data": data})

Personal Journey and Learnings

In this assignment, I completed a front-to-back interactive calculator, which was much more difficult than the first assignment. The most important point of this job is the back-end part. In the study, I generally know the routing system of Flask, request processing, and learn how to connect to the mysql database and carry out related operations.

In the process of practice, I also found my shortcomings and weaknesses in software development, and I will work harder to learn relevant knowledge in the future.

...全文
560 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文围绕基于萤火虫算法(FA)的太阳能、风能与水力混合抽水蓄能系统的优化建模与仿真展开研究,提出了一种融合多源可再生能源与抽水蓄能技术的综合能源系统协调运行策略。通过Matlab平台实现了系统建模、智能优化算法设计与仿真验证全过程,重点解决了风光水多能源出力波动性强、系统供电可靠性低等问题。采用萤火虫算法对储能调度、能量管理与运行经济性进行优化,有效提升了系统对可再生能源的消纳能力和平滑输出性能,同时兼顾运行成本与稳定性。研究涵盖了从数学建模、目标函数构建、约束条件处理到多能互补协调机制的设计,提供了完整的代码实现方案,具有较强的科研复现价值与工程应用前景。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及从事新能源系统优化设计的工程技术人员。; 使用场景及目标:①用于高校或科研机构开展可再生能源集成与储能优化调度相关课题研究;②支撑高水平论文撰写与智能优化算法(如萤火虫算法)在综合能源系统中的应用复现;③为实际电力系统中多能互补项目、微电网能量管理系统的设计与仿真提供方法论与工具支持。; 阅读建议:建议读者结合文中提供的Matlab代码与可能的Simulink模型,逐步调试运行,深入理解算法实现细节与系统建模逻辑;同时关注优化目标函数的设定、约束条件处理及多能源协调机制,以提升自身在能源系统优化领域的建模与创新能力。
源码下载地址: https://pan.quark.cn/s/7f242081e14c 标题 "普中51-A2开发板资料.7z" 提供的信息表明,这是一个与普中51-A2开发板相关的资源包。 51单片机是微控制器领域中的一个经典系列,STC-89C52是51系列中的一个型号,常用于教学和入门级项目。 这个压缩包可能包含了一系列帮助用户理解和使用该开发板的材料。 描述中的"SHA256: B889D6FE71BF1CB25C67D57BE0854787F4D6902B20E2A1AF8FC9DEB66F4C7827"是文件的哈希值,用于验证文件的完整性和未被篡改,但具体知识点不在此范围内。 从标签来看,我们可以期待以下内容:1. **普中51-A2开发板**:这是一款基于51单片机的开发工具,可能包括硬件电路图、原理图、PCB设计文件等。 2. **STC-89C52**:这是51单片机的一个变种,具有增强的特性,如更多的I/O口、更大的内存等。 资料可能包含其数据手册、引脚定义、编程指南等。 3. **开发板**:可能包含开发板的使用手册、接线教程、初始化设置步骤等。 4. **51单片机**:基础理论、指令集、编程语言(如汇编或C语言)、中断系统、定时器/计数器的使用等。 5. **开发工具**:可能有Keil、Proteus、ISP编程软件等,这些工具用于编写、调试和烧录代码到单片机中。 从压缩包子文件的文件名称列表来看,我们可以深入学习以下内容:1. **普中51单片机开发攻略--A2.pdf**:这可能是开发板的用户指南或教程,涵盖基本操作、示例项目和常见问题解答。 2. **5--开发工具.rar**:可能包含开发环境的安装教程、配置指南和使用技巧。 3. **5--实验程序....
内容概要:本文详细介绍了一种基于Simulink的光伏储能单相逆变器并网仿真模型,系统涵盖了光伏阵列、储能单元、DC-AC单相逆变器及并网接口的完整结构,重点实现了储能环节的能量管理与逆变器并网控制策略的建模仿真。通过Simulink平台构建系统模型,验证了逆变器输出电能质量、并网稳定性以及控制系统的动态响应性能,采用SPWM调制、PI闭环控制等关键技术,确保并网电流与电网电压同频同相,满足并网电能质量要求。该模型不仅可用于分布式能源系统的仿真研究,还可作为新能源并网技术的教学与工程实践工具。; 适合人群:电气工程、自动化、新能源科学与工程等相关专业的高校本科生、研究生、科研人员,以及从事光伏发电系统设计、储能控制与并网技术研发的工程技术人员。; 使用场景及目标:①深入理解光伏储能系统中能量转换、存储与并网控制的整体工作原理;②支持课程设计、毕业设计或科研项目中对单相逆变器控制策略(如SPWM、PI调节、锁相技术等)的仿真验证与参数优化;③为后续研究更复杂的控制算法(如MPPT、低电压穿越、谐波抑制等)提供可扩展的仿真基础平台。; 阅读建议:建议结合MATLAB/Simulink环境动手搭建与调试模型,逐步理解各模块(如光伏建模、储能充放电控制、逆变器驱动、锁相环、PI调节器等)的功能与交互关系,重点关注控制系统的设计逻辑与参数整定过程,并可通过修改负载条件或电网参数测试系统鲁棒性,为进一步拓展至三相系统或多机并网场景奠定基础。

176

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧