前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[单机角色血量管理系统设计 ]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...爬取数据的持久化存储管理。 JPA(Java Persistence API) , JPA是Java平台上的一个规范,为Java开发者提供了对象关系映射(ORM)的功能,使开发者可以使用面向对象的方式来操作数据库。在文章的场景下,JPA被应用于SpringBoot项目中,用以简化数据库操作,将爬取的商品数据自动映射到实体类,并通过ORM方式方便地与数据库进行交互和数据持久化。 HttpClient , Apache HttpClient是一个强大的Java库,用于执行HTTP协议相关的客户端功能,如GET、POST等请求,获取HTTP响应结果。在本文的爬虫项目中,HttpClient被用来发起对京东页面的HTTP请求,获取商品列表页面的HTML源码。 Jsoup , Jsoup是一个基于Java的HTML解析器,它可以非常方便地提取和操作HTML文档中的数据,支持CSS选择器来查找元素。在该篇文章的爬虫实践中,Jsoup用于解析从京东页面获取的HTML内容,从中提取出商品SPU、SKU、价格、标题、图片链接等具体信息。
2023-03-13 10:48:12
104
转载
转载文章
...松分布,常出现在成像系统中,如光学或放射学领域,其特性是像素值的随机变化率与当前像素强度成正比。在图像去噪的背景下,AugmentNoise类根据用户指定的参数分别生成不同类型的高斯噪声或泊松噪声,以模拟真实情况下的噪声干扰,并通过训练后的UNet模型去除这些噪声,恢复图像原本清晰的内容。
2023-06-13 14:44:26
128
转载
JQuery
...及大量历史遗留代码的系统而言,逐步迁移至React或Vue的成本极高,而jQuery则提供了一种低成本、高效率的解决方案。通过合理规划,他们成功地将jQuery与Vue结合使用,既保留了原有系统的稳定性,又实现了新功能的快速迭代。 此外,有专家提醒,尽管jQuery在某些领域仍有价值,但开发者不应忽视其潜在的安全隐患。近年来,多起因jQuery版本过旧而导致的安全漏洞事件敲响了警钟。因此,定期更新jQuery版本、及时修补已知漏洞至关重要。同时,随着WebAssembly技术的兴起,未来可能会出现更多超越传统JavaScript框架的新工具,这或许会对jQuery的地位构成挑战。 综上所述,虽然jQuery正处于转型期,但它依然是前端开发领域的一块基石。无论是继续深耕还是寻找替代方案,都需要开发者根据具体业务需求做出理性判断。在这个快速变化的时代,保持开放的心态和持续学习的态度才是应对技术变革的最佳策略。
2025-05-08 16:16:22
58
蝶舞花间
转载文章
...新型动态变形验证码的设计方案,它不仅结合了随机旋转角度的方法,还引入了像素扰动、局部变形等手段,极大地增加了自动破解工具的识别难度。同时,研究人员强调了验证码设计时兼顾用户体验的重要性,提倡使用无障碍设计以方便视障人士及其他特殊群体进行验证。 此外,对于ClearType字体渲染优化问题,微软等公司也在不断探索改进方案,力求在保证验证码安全性的前提下提升显示效果,减少毛边现象,提供更为平滑清晰的文字显示。而在实际应用中,如银行、社交平台等高安全需求场景,则纷纷开始采用多模态验证码,结合图形、语音等多种方式,构建更为立体全面的安全防护体系。 总之,验证码技术的演进充分体现了AI与安全领域的交叉融合,未来将进一步发展为智能、高效且人性化的身份验证机制,持续抵御自动化攻击,保障用户的网络安全。
2023-05-27 09:38:56
249
转载
Beego
...能在实际运行中对整个系统做全面健康检查啦!创建一个controller_test.go文件并添加如下内容: go package controllers import ( "net/http" "testing" "github.com/astaxie/beego" "github.com/stretchr/testify/assert" ) type MockUserService struct{} func (m MockUserService) GetUser(id int64) (User, error) { return &User{ID: id, Name: fmt.Sprintf("User %d", id)}, nil } func TestUserController_GetByID(t testing.T) { userService := &MockUserService{} ctrl := NewUserController(userService) beego.SetController(&ctrl) request, _ := http.NewRequest("GET", "/users/1", nil) response := new(http.Response) defer response.Body.Close() _ctrl := beego.NewControllerWithRequest(request) _ctrl.ServeHTTP(response, nil) if response.StatusCode != http.StatusOK { t.Fatalf("Expected status code 200 but got %d", response.StatusCode) } userData, err := getUserFromResponse(response) assert.NoError(t, err) assert.NotNil(t, userData) assert.Equal(t, "User 1", userData.Name) } func getUserFromResponse(r http.Response) (User, error) { var user User err := json.Unmarshal(r.Body, &user) return &user, err } 五、结论 通过以上讲解,相信你已经掌握了如何在Beego项目中编写单元测试和集成测试,它们各自对代码质量保障和功能协作的有效性不容忽视。在实际做项目的时候,咱们得瞅准不同的应用场景,灵活选用最对口的测试方案。并且,持续打磨、改进测试覆盖面,这样一来,你的代码质量就能妥妥地更上一个台阶,杠杠的!祝你在Beego开发之旅中,既能写出高质量的代码,又能保证万无一失的功能交付!
2024-02-09 10:43:01
459
落叶归根-t
转载文章
...及,要求MP4容器在设计上不断创新和完善,为用户提供更为沉浸式的视听体验。 综上所述,在学习和掌握MP4文件格式的基础上,进一步关注和了解行业内的前沿技术和标准动态,对于音视频工程师和技术爱好者来说至关重要。通过持续跟进并探索如AV1、VVC编码技术与MP4容器格式的深度结合,以及新型媒体格式在MP4中的应用实践,将有助于推动音视频技术的不断发展与进步。
2024-01-21 17:43:21
437
转载
JSON
转载文章
...据是指随着用户交互或系统状态变化而实时更新的数据。例如,在采集百度下拉词数据时,当用户在搜索框中输入关键词时出现的下拉推荐词列表就是一种动态数据,它随用户的输入行为实时生成并消失。 JSON格式 , JavaScript Object Notation(JSON)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。在文中,百度返回的下拉词数据即采用JSON格式,包含键值对结构,通过抓取并解析JSON响应内容,可以提取出具体的下拉推荐词信息。 线程池 (concurrent.futures.ThreadPoolExecutor) , 在Python编程中,线程池是一种多线程编程的高效解决方案,通过预先创建一定数量的线程并进行复用,能够减少线程频繁创建销毁带来的开销。文中使用了concurrent.futures.ThreadPoolExecutor来并发处理多个关键词的下拉词数据获取任务,每个关键词的请求作为一个独立的任务提交给线程池,线程池中的空闲线程会自动执行这些任务,从而提高了数据采集效率。 抓包操作 , 在网络编程与数据分析领域中,抓包操作指的是利用网络封包分析软件(如Wireshark、Fiddler等,或浏览器开发者工具)捕获、记录网络传输过程中经过计算机网络接口的所有数据包的过程。在本文的具体情境下,作者通过浏览器开发者工具进行抓包操作,找到了包含百度下拉词数据的HTTP请求,进一步分析了该请求的相关参数和返回结果,以实现自动化数据采集的目标。
2023-06-21 12:59:26
490
转载
Superset
... 2.1 数据连接与管理 首先,Superset允许用户连接到多种不同的数据源,包括关系型数据库(如MySQL、PostgreSQL)、NoSQL数据库(如MongoDB)、甚至是云服务(如Amazon Redshift)。有了这些连接,你就可以超级方便地从各种地方抓取数据,然后在Superset里轻松搞定管理和操作啦! 2.2 可视化选项丰富多样 Superset内置了大量的可视化类型,从常见的柱状图、折线图到地图、热力图等,应有尽有。不仅如此,你还能自己调整图表的外观和排版,想怎么整就怎么整,做出专属于你的独特图表! 2.3 交互式仪表板 另一个亮点是Superset的交互式仪表板功能。你可以把好几个图表拼在一起,做成一个超级炫酷的仪表板。这样一来,用户就能随心所欲地调整和查看他们想看的数据了。就像是自己动手组装了一个数据游乐场一样!这种灵活性对于实时监控业务指标或呈现复杂的数据关系非常有用。 2.4 高级分析功能 除了基础的可视化之外,Superset还提供了一些高级分析功能,比如预测分析、聚类分析等。这些功能可以帮助你挖掘数据中的深层次信息,发现潜在的机会或问题。 三、如何安装和配置Superset? 3.1 安装Superset 安装Superset其实并不难,但需要一些基本的Python环境知识。首先,你需要确保你的机器上已经安装了Python和pip。接下来,你可以通过以下命令来安装Superset: bash pip install superset 然后,运行以下命令初始化数据库: bash superset db upgrade 最后,创建一个管理员账户以便登录: bash superset fab create-admin \ --username admin \ --firstname Superset \ --lastname Admin \ --email admin@fab.org \ --password admin 启动Superset服务器: bash superset runserver 3.2 配置数据源 一旦你成功安装了Superset,就可以开始配置数据源了。如果你想连上那个MySQL数据库,就得先在Superset里新建个数据库连接。具体步骤如下: 1. 登录到Superset的Web界面。 2. 导航到“Sources” -> “Databases”。 3. 点击“Add Database”按钮。 4. 填写数据库的相关信息,比如主机名、端口号、数据库名称等。 5. 保存配置后,你就可以在Superset中使用这个数据源了。 四、实战案例 使用Superset进行数据可视化 4.1 创建一个简单的柱状图 假设你已经成功配置了一个数据源,现在让我们来创建一个简单的柱状图吧。首先,导航到“Explore”页面,选择你想要使用的数据集。接着,在“Visualization Type”下拉菜单中选择“Bar Chart”。 在接下来的步骤中,你可以根据自己的需求调整图表的各种属性,比如X轴和Y轴的数据字段、颜色方案、标签显示方式等。完成后,点击“Save as Dashboard”按钮将其添加到仪表板中。 4.2 制作一个动态仪表板 为了展示Superset的强大之处,让我们尝试创建一个更加复杂的仪表板。假设我们要监控一家电商公司的销售情况,可以按照以下步骤来制作: 1. 添加销售总额图表 选择一个时间序列数据集,创建一个折线图来展示销售额的变化趋势。 2. 加入产品类别占比 使用饼图来显示不同类别产品的销售占比。 3. 实时监控库存 创建一个条形图来展示当前各仓库的库存量。 4. 用户行为分析 添加一个表格来列出最近几天内活跃用户的详细信息。 完成上述步骤后,你就得到了一个全面且直观的销售监控仪表板。有了这个仪表板,你就能随时了解公司的情况,做出快速的决定啦! 五、总结与展望 经过一番探索,我相信大家都已经被Superset的魅力所吸引了吧?作为一款开源的数据可视化工具,它不仅功能强大、易用性强,而且拥有广泛的社区支持。无论你是想快速生成报告,还是深入分析数据,Superset都能满足你的需求。 当然,随着技术的发展,Superset也在不断地更新和完善。未来的日子,我们会看到更多酷炫的新功能被加入进来,让数据可视化变得更简单好玩儿!所以,赶紧试试看吧!相信Superset会给你带来意想不到的惊喜! --- 这就是我今天分享的内容啦,希望大家喜欢。如果你有任何问题或想法,欢迎留言讨论哦!
2024-12-15 16:30:11
90
红尘漫步
转载文章
...化,尤其适用于响应式设计及跨平台测试场景。 另外值得注意的是,在Web应用安全测试方面,Selenium还可以与其他安全测试工具如ZAP (Zed Attack Proxy) 结合使用,通过对网站进行爬取和模拟用户交互,帮助发现潜在的安全漏洞。 综上所述,Selenium作为Web自动化测试的核心工具,在不断迭代升级中正逐步适应更多复杂且多样化的测试需求。随着DevOps理念的深入推广和实践,熟练掌握并灵活运用Selenium将成为软件质量保障工程师必备技能之一。与此同时,关注相关领域的最新发展动态和技术趋势,将有助于我们在实际项目中更好地利用Selenium以及其他配套工具,不断提升自动化测试的效果与价值。
2023-12-03 12:51:11
45
转载
转载文章
...线协作工具、实时交易系统、游戏开发、物联网设备数据同步等领域。 2021年,Mozilla发布了一篇关于WebSocket性能优化的文章,其中详细介绍了如何针对现代浏览器进行WebSocket连接的性能调优,包括握手过程、数据帧压缩以及多路复用等高级特性。同时,随着HTTP/3的推进,WebSocket在QUIC协议上的实验性支持也在逐步展开,未来有望实现更快速、更稳定的长连接通信。 另外,各大云服务商如AWS、阿里云等也纷纷推出了对WebSocket服务的支持,通过Serverless架构和WebSocket API,开发者可以更加便捷地构建基于WebSocket的应用程序,并能有效解决WebSocket服务器的运维与扩展问题。 此外,对于安全性方面,最新的WebSocket安全实践指南强调了加密传输、防篡改机制以及权限验证等方面的重要性,确保在提供实时通信能力的同时,保障用户数据的安全。 总之,在WebSocket技术不断发展的今天,掌握其原理并关注相关领域的前沿动态,将有助于开发者更好地应对实际项目中的挑战,提升用户体验和系统性能。
2023-03-19 12:00:21
52
转载
转载文章
...入一个字符串,我根据系统需要生成的随机数,汉字的话需要转码,如u'你好'.encode('gbk')) win32gui.SendMessage(hwnd_filename, win32con.WM_SETTEXT, None, fileName) 3.点击保存 点击保存按钮 hwnd_save = win32gui.FindWindowEx(hwnd,None,"Button",None) win32gui.PostMessage(hwnd_save, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) win32gui.PostMessage(hwnd_save, win32con.WM_KEYUP, win32con.VK_RETURN, 0) 以上在不需要修改保存路径的情况下可以直接保存文件 --------------------------------------------------------------------------------------------------------------------------- 以下是未解决的问题 1.修改路径的问题(已解决),我猜想是通过两种方式,一是通过左边的树视图(SysTreeView32)来操作选择路径,二是通过在地址栏直接输入路径地址。其中第一种方法在网上没有查找到操作的方法,然后尝试第二种方法,找到路径地址输入框然后输入路径: 未点击地址栏时路径的窗口句柄是上图这样的 点击地址栏之后路径窗口句柄变成下图这样 a1 = win32gui.FindWindowEx(hwnd,None,"WorkerW",None) a2 = win32gui.FindWindowEx(a1,None,"ReBarWindow32",None) a3 = win32gui.FindWindowEx(a2,None,"Address Band Root",None) a4 = win32gui.FindWindowEx(a3,None,"msctls_progress32",None) a5 = win32gui.FindWindowEx(a4,None,"Breadcrumb Parent",None) hwnd_filepath1 = win32gui.FindWindowEx(a5,None,"ToolbarWindow32",None) print "-----hwnd_filepath1------",hwnd_filepath1 先找到到上图路径栏句柄(查找成功),然后按回车,使地址栏变成可输入状态 win32gui.PostMessage(hwnd_filepath1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, 0) win32gui.PostMessage(hwnd_filepath1, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0) 在通过路径查找 a11 = win32gui.FindWindowEx(hwnd,None,"WorkerW",None) a21 = win32gui.FindWindowEx(a11,None,"ReBarWindow32",None) a31 = win32gui.FindWindowEx(a21,None,"Address Band Root",None) a41 = win32gui.FindWindowEx(a31,None,"msctls_progress32",None) a6 = win32gui.FindWindowEx(a41,None,"ComboBoxEx32",None) a7 = win32gui.FindWindowEx(a6,None,"ComboBox",None) hwnd_filepath = win32gui.FindWindowEx(a7,None,"Edit",None) print "-----hwnd_filepath------",hwnd_filepath 到这一步查找句柄返回值变成0,就是没查找到路径编辑框,没有找到原因,代码运行下来路径那里只是能看到的效果点击了一下,但是不会变成输入框状态,但是把鼠标移上去会变成输入的状态 这样是可输入的状态 然后win32gui.SendMessage(hwnd_filepath, win32con.WM_SETTEXT, None, 'C:\Users\Administrator\Desktop')这样地址就输入不进去,原因不明 视图数操作的方法没有找到 2.取消按钮的点击无效(已解决) 保存按钮 取消按钮 保存和取消的类名都是“Button”,所以通过保存按钮查找到下一个Button就是取消 hwnd_cancle = win32gui.FindWindowEx(hwnd,hwnd_save,"Button",None) print "------hwnd_cancle---",hwnd_cancle 取消句柄获取到了,通过下面的方法打印出来的父句柄和保存按钮是一样的都是另存为这个弹出框 print win32gui.GetParent(hwnd_cancle) 下面两行代码也获取到了取消的类名和标题打印出来的是‘Button’和‘取消’ print win32gui.GetClassName(hwnd_cancle) print win32gui.GetWindowText(hwnd_cancle).decode('gbk').encode('utf-8') 以下两行代码点击取消按钮的时候,弹出框不关闭,然后发现点击的是保存按钮,原因不明 win32gui.PostMessage(hwnd_cancle, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) win32gui.PostMessage(hwnd_cancle, win32con.WM_KEYUP, win32con.VK_RETURN, 0) 以上是完成的两点和处理失败的两点,做出来是个半成品,win32gui这方面的知识对我来说有点难,在python中安装的pywin32自带了一个API,里面的描述方法很简单,不够详细,很多看不太懂,以后还需要再花时间慢慢研究 -------------------------------------------------------------------------------------------- 问题1的解决方法: 修改成指定路径 win_1 = win32gui.FindWindowEx(hwnd, None,"WorkerW",None) win_2 = win32gui.FindWindowEx(win_1, None,"ReBarWindow32",None) win_3 = win32gui.FindWindowEx(win_2, None,"Address Band Root",None) win_4 = win32gui.FindWindowEx(win_3, None,"msctls_progress32",None) left, top, right, bottom = win32gui.GetWindowRect(win_4) win32api.SetCursorPos([left,top]) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) 将路径复制到剪切板 win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(filePath) win32clipboard.CloseClipboard() 按下ctrl+v win32api.keybd_event(0x11, 0, 0, 0) win32api.keybd_event(0x56, 0, 0, 0) win32api.keybd_event(0x56, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(0x11, 0, win32con.KEYEVENTF_KEYUP, 0) 按回车进入该路径 win32api.keybd_event(0x0D,0,0,0) 问题2取消按钮点击的问题已经解决: 点击取消按钮,用鼠标点击点击取消按钮,上面使用键盘按键不行,原因不明 hwnd_cancel = win32gui.FindWindowEx(hwnd,hwnd_save,"Button",None) left, top, right, bottom = win32gui.GetWindowRect(hwnd_cancel)该方法接收值必须为4个 win32api.SetCursorPos([left+35,top+13]) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32gui.GetWindowRect方法描述:Returns the rectangle for a window in screen coordinates。应该返回该句柄控件的四个顶点坐标吧 win32api.SetCursorPos方法描述:The SetCursorPos function moves the cursor to the specified screen coordinates.将光标移动到指定的屏幕坐标。 ----------------------------------------------------------------------------------------------- 查找另存为弹出框下的所有子句柄: hwndChildList = [] win32gui.EnumChildWindows(hwnd, lambda hwnd1, param: param.append(hwnd1), hwndChildList) for a in hwndChildList: print win32gui.GetParent(a) print win32gui.GetClassName(a) print win32gui.GetWindowText(a).decode('gbk').encode('utf-8') print "-----hwnd_save------",a 另外,经同事推荐ViewWizard工具比spy++更轻便快捷,查看父句柄也比之更方便 按键控制查询:http://www.mamicode.com/info-detail-1319197.html 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_39814378/article/details/110329291。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-17 22:46:11
253
转载
转载文章
...进图表元素的可访问性设计,确保视障用户通过辅助技术也能准确理解数据信息。 此外,amCharts团队正积极与各大开源社区合作,持续丰富地图库资源,并计划将更多开源地理空间数据项目纳入支持范围,让用户能更加便捷地创建符合特定业务需求的地图图表。通过这些升级,amCharts 5旨在巩固其作为行业领先的数据可视化工具的地位,赋能各行业用户高效、精准地洞察并传达复杂数据背后的价值。
2023-09-17 18:18:34
351
转载
HBase
...型电商公司的实时推荐系统中,HBase集群的响应速度直接影响了用户的购物体验。据报道,该公司最近对HBase集群进行了全面升级,不仅将RegionServer的堆内存从8GB提升至16GB,还引入了新的Compaction算法,大幅减少了数据碎片化问题。这一系列调整使得查询延迟降低了约30%,整体吞吐量提升了近50%。 与此同时,开源社区也在不断推进HBase的功能迭代。最新发布的HBase 2.5版本引入了多项性能增强特性,包括支持异步I/O操作以减少网络延迟,以及改进了Region分裂和合并逻辑,从而提高了数据分布的均匀性。此外,社区还特别强调了监控的重要性,建议用户充分利用Prometheus和Grafana等现代监控工具,实现对HBase集群的全方位观测。 值得注意的是,HBase的性能优化并非一蹴而就,而是需要结合实际业务场景进行细致调优。例如,在金融行业中,高频交易系统对数据一致性要求极高,因此需要特别关注GC时间对事务处理的影响;而在物联网领域,则可能更侧重于降低单点延迟,确保海量设备的数据上报能够及时响应。 回顾历史,HBase自2008年开源以来,一直致力于为企业级应用场景提供可靠的数据存储解决方案。正如Apache基金会主席比尔·霍普金斯所说:“HBase的成功离不开全球开发者社区的支持。”未来,随着5G、边缘计算等新技术的普及,HBase有望在更多新兴领域发挥重要作用,成为企业数字化转型不可或缺的一部分。
2025-04-14 16:00:01
63
落叶归根
转载文章
...运用。无论是组织架构设计,还是个人职业规划,都应充分认识到实践、交流和学习三者相辅相成的重要性,以适应不断变化的工作环境和挑战。
2023-06-04 23:38:21
105
转载
转载文章
...av元素专为导航链接设计,帮助构建页面内的导航菜单;而section元素用于划分不同的内容区块,增强了网页内容的模块化和组织性。 向后兼容 , 向后兼容是HTML5的一个重要特性,意味着新的HTML标准在设计时考虑到与旧版本浏览器的兼容问题,尽可能确保使用新特性的网页在不支持这些特性的老旧浏览器上也能以某种方式正确显示或至少不影响基本功能。比如,尽管HTML5引入了许多新的语义化元素,但在不支持这些元素的浏览器中,这些元素仍会被当作普通的块级元素处理,确保网页的基本结构和内容依然可以被用户看到和理解。
2023-07-16 11:42:34
252
转载
转载文章
... pids方法查看系统全部进程pids = psutil.pids()for pid in pids: Process方法查看单个进程p = psutil.Process(pid) print('pid-%s,pname-%s' % (pid, p.name())) 进程名if p.name() == 'ffmpeg-win64-v4.1.exe': 关闭任务 /f是强制执行,/im对应程序名cmd = 'taskkill /f /im ffmpeg-win64-v4.1.exe 2>nul 1>null' python调用Shell脚本执行cmd命令os.system(cmd)except:pass下载.ts文件def download_ts(m3u8_list,name):try:if not os.path.exists(config['FILE_PATH']):os.makedirs(config['FILE_PATH'])if not os.path.exists(config['TS_PATH']):os.makedirs(config['TS_PATH'])if os.path.exists(config['FILE_PATH']+name+'.mp4'):name = name+'_'+str(int(time.time()))print('开始下载:',name)L = []R = []for p in m3u8_list:ts_find = get_content_requests(p)file_ts = '{0}{1}.ts'.format(config['TS_PATH'],md5(ts_find.content).hexdigest())with open(file_ts,'wb') as f:f.write(ts_find.content)R.append(file_ts)hebing = VideoFileClip(file_ts)L.append(hebing)killProcess()print('下载完成:',file_ts)mp4file = '{0}{1}.mp4'.format(config['FILE_PATH'],name)final_clip = concatenate_videoclips(L)final_clip.to_videofile(mp4file, fps=24, remove_temp=True)killProcess()loop_del_file(R)print('\n下载完成:',name)print('')return Trueexcept:print('~~~~~合成.ts文件失败~~~~~')return None下载视频列表def list_get_kong(list_json):for item in list_json:y = Trueif config['CHECKID']:if check_to_mongo(item['vid']):print('~~~~~检测到重复项~~~~~')y = Falseif y:get_show_html = get_content_requests('https://vmobile.douyu.com/video/getInfo?vid=' + item['vid'])if get_show_html:m3u8_list = get_ts_list(get_show_html.text)if m3u8_list:download = download_ts(m3u8_list, item['title'])if download: save_to_mango(item['vid'])time.sleep(config['TIME_GE'])控制器def main(page):if config['TYPE']==1:print('~~~~~按用户ID采集~~~~~')listurl = 'https://v.douyu.com/video/author/getAuthorVideoListByNew?up_id={0}&cate2_id=0&limit=30&page={1}'.format(config['UID'],page)get_list_html = get_content_requests(listurl)if get_list_html:list_json = get_list(get_list_html.text,1)if list_json:list_get_kong(list_json)else:print('~~~~~按列表ID采集~~~~~')listurl = 'https://v.douyu.com/video/video/listData?page={1}&cate2Id={0}&action=new'.format(config['CID'],page)get_list_html = get_content_requests(listurl)if get_list_html:list_json = get_list(get_list_html.text,2)if list_json:list_get_kong(list_json)初始化if __name__=='__main__':if config['POOL']:groups = [x for x in range(config['PAGE_START'],config['PAGE_END']+1)]pool = Pool()pool.map(main, groups)else:for item in range(config['PAGE_START'],config['PAGE_END']+1):main(item)print('~~~~~已经完成【所有操作】~~~~~') 总结:众所周知,BiliBili是一个学习的网站! 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_35875470/article/details/89857445。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-18 11:34:00
119
转载
转载文章
...剩余磁盘空间,请联系管理员!"); } else { $('error-msg').text(""); } } }, error: function (xhr, err, obj) { $('error-msg').text("检测服务器剩余磁盘空间失败"); } }); }); uploader.bind('UploadProgress', function (uploader, file) { var percent = file.percent; progressBar.progress(percent); }); uploader.bind('FileUploaded', function (up, file, callBack) { var data = $.parseJSON(callBack.response); if (data.statusCode === "1") { $("<%=hfPackagePath.ClientID %>").val(data.filePath); var id = $("<%=hfCourseID.ClientID %>").val(); __doPostBack("save", id); } else { hideLoading(); $('error-msg').text(data.message); } }); uploader.bind('Error', function (up, err) { alert("文件上传失败,错误信息: " + err.message); }); /Plupload/ 后台 UploadCoursePackage.ashx 的代码也重要,主要是文件分片跟不分片的处理方式不一样 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace WebUI.Handlers { /// <summary> /// UploadCoursePackage 的摘要说明 /// </summary> public class UploadCoursePackage : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int statuscode = 1; string message = string.Empty; string filepath = string.Empty; if (context.Request.Files.Count > 0) { try { string resourceDirectoryName = System.Configuration.ConfigurationManager.AppSettings["resourceDirectory"]; string path = context.Server.MapPath("~/" + resourceDirectoryName); if (!Directory.Exists(path)) Directory.CreateDirectory(path); int chunk = context.Request.Params["chunk"] != null ? int.Parse(context.Request.Params["chunk"]) : 0; //获取当前的块ID,如果不是分块上传的。chunk则为0 string fileName = context.Request.Params["name"]; //这里写的比较潦草。判断文件名是否为空。 string type = context.Request.Params["type"]; //在前面JS中不是定义了自定义参数multipart_params的值么。其中有个值是type:"misoft",此处就可以获取到这个值了。获取到的type="misoft"; string ext = Path.GetExtension(fileName); //fileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), ext); filepath = resourceDirectoryName + "/" + fileName; fileName = Path.Combine(path, fileName); //对文件流进行存储 需要注意的是 files目录必须存在(此处可以做个判断) 根据上面的chunk来判断是块上传还是普通上传 上传方式不一样 ,导致的保存方式也会不一样 FileStream fs = new FileStream(fileName, chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append); //write our input stream to a buffer Byte[] buffer = null; if (context.Request.ContentType == "application/octet-stream" && context.Request.ContentLength > 0) { buffer = new Byte[context.Request.InputStream.Length]; context.Request.InputStream.Read(buffer, 0, buffer.Length); } else if (context.Request.ContentType.Contains("multipart/form-data") && context.Request.Files.Count > 0 && context.Request.Files[0].ContentLength > 0) { buffer = new Byte[context.Request.Files[0].InputStream.Length]; context.Request.Files[0].InputStream.Read(buffer, 0, buffer.Length); } //write the buffer to a file. if (buffer != null) fs.Write(buffer, 0, buffer.Length); fs.Close(); statuscode = 1; message = "上传成功"; } catch (Exception ex) { statuscode = -1001; message = "保存时发生错误,请确保文件有效且格式正确"; Util.LogHelper logger = new Util.LogHelper(); string path = context.Server.MapPath("~/Logs"); logger.WriteLog(ex.Message, path); } } else { statuscode = -404; message = "上传失败,未接收到资源文件"; } string msg = "{\"statusCode\":\"" + statuscode + "\",\"message\":\"" + message + "\",\"filePath\":\"" + filepath + "\"}"; context.Response.Write(msg); } public bool IsReusable { get { return false; } } } } 再附送一个检测服务器端硬盘剩余空间的功能吧 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; namespace WebUI { public partial class CheckHardDiskFreeSpace : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 获取磁盘剩余容量 /// </summary> /// <returns></returns> [WebMethod] public static string GetHardDiskFreeSpace() { const string strHardDiskName = @"F:\"; var freeSpace = string.Empty; var drives = DriveInfo.GetDrives(); var myDrive = (from drive in drives where drive.Name == strHardDiskName select drive).FirstOrDefault(); if (myDrive != null) { freeSpace = myDrive.TotalFreeSpace+""; } return freeSpace; } } } 效果展示: 详细配置信息可以参考这篇文章:http://blog.ncmem.com/wordpress/2019/08/12/plupload%e4%b8%8a%e4%bc%a0%e6%95%b4%e4%b8%aa%e6%96%87%e4%bb%b6%e5%a4%b9-2/ 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_45525177/article/details/100654639。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-19 09:43:46
127
转载
转载文章
...状态约束的双目vio系统 !!!注意imuCallback:接收IMU数据,将IMU数据存到imu_msg_buffer中,这里只会利用开头200帧IMU数据进行静止初始化,不做其他处理。featureCallback:接收双目特征,进行后端处理。利用IMU进行EKF Propagation,利用双目特征进行EKF Update。静止初始化(initializeGravityAndBias):将前200帧加速度和角速度求平均, 平均加速度的模值g作为重力加速度, 平均角速度作为陀螺仪的bias, 计算重力向量(0,0,-g)和平均加速度之间的夹角(旋转四元数), 标定初始时刻IMU系与world系之间的夹角. 因此MSCKF要求前200帧IMU是静止不动的 sudo apt-get install libsuitesparse-devcd ~/catkin_ws/srcgit clone KumarRobotics/msckf_viocd ..catkin_make --pkg msckf_vio --cmake-args -DCMAKE_BUILD_TYPE=Release激活环境变量很关键source /devel/setup.bashroslaunch msckf_vio msckf_vio_euroc.launch注意文件路径rosrun rviz rviz -d rviz/rviz_euroc_config.rviz (改成你自己的rviz文件)rosbag play ~/data/euroc/MH_04_difficult.bag(改成你自己的rosbag文件) 可以看到,s_msckf的输出是没有轨迹的,可以增加如下脚本,将/odom存为/path,在rviz订阅即可可视化轨迹 脚本来自其issue:https://github.com/KumarRobotics/msckf_vio/issues/13 !/usr/bin/env pythonimport rospyfrom nav_msgs.msg import Odometry, Pathfrom geometry_msgs.msg import PoseStampedclass OdomToPath:def __init__(self):self.path_pub = rospy.Publisher('/slz_path', Path, latch=True, queue_size=10)self.odom_sub = rospy.Subscriber('/firefly_sbx/vio/odom', Odometry, self.odom_cb, queue_size=10)self.path = Path()def odom_cb(self, msg):cur_pose = PoseStamped()cur_pose.header = msg.headercur_pose.pose = msg.pose.poseself.path.header = msg.headerself.path.poses.append(cur_pose)self.path_pub.publish(self.path)if __name__ == '__main__':rospy.init_node('odom_to_path')odom_to_path = OdomToPath()rospy.spin() 或者增加一个draw_path的功能包: cpp为: include <stdio.h>include <stdlib.h>include <unistd.h>include <ros/ros.h>include <ros/console.h>include <nav_msgs/Path.h>include <std_msgs/String.h>include <nav_msgs/Odometry.h>include <geometry_msgs/Quaternion.h>include <geometry_msgs/PoseStamped.h>nav_msgs::Path path;ros::Publisher path_pub;ros::Subscriber odomSub;ros::Subscriber odom_raw_Sub;void odomCallback(const nav_msgs::Odometry::ConstPtr& odom){geometry_msgs::PoseStamped this_pose_stamped;this_pose_stamped.header= odom->header;this_pose_stamped.pose = odom->pose.pose;//this_pose_stamped.pose.position.x = odom->pose.pose.position.x;//this_pose_stamped.pose.position.y = odom->pose.pose.position.y;//this_pose_stamped.pose.orientation = odom->pose.pose.orientation;//this_pose_stamped.header.stamp = ros::Time::now();//this_pose_stamped.header.frame_id = "world";//frame_id 是消息中与数据相关联的参考系id,例如在在激光数据中,frame_id对应激光数据采集的参考系 path.header= this_pose_stamped.header;path.poses.push_back(this_pose_stamped);//path.header.stamp = ros::Time::now();//path.header.frame_id= "world";path_pub.publish(path);//printf("path_pub ");//printf("odom %.3lf %.3lf\n",odom->pose.pose.position.x,odom->pose.pose.position.y);}int main (int argc, char argv){ros::init (argc, argv, "showpath");ros::NodeHandle ph;path_pub = ph.advertise<nav_msgs::Path>("/trajectory",10, true);odomSub = ph.subscribe<nav_msgs::Odometry>("/firefly_sbx/vio/odom", 10, odomCallback);//ros::Rate loop_rate(50);while (ros::ok()){ros::spinOnce(); // check for incoming messages//loop_rate.sleep();}return 0;} cmakelists.txt cmake_minimum_required(VERSION 2.8.3)project(draw) Compile as C++11, supported in ROS Kinetic and newer add_compile_options(-std=c++11) Find catkin macros and libraries if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) is used, also find other catkin packagesfind_package(catkin REQUIRED COMPONENTSgeometry_msgsroscpprospystd_msgsmessage_generation)catkin_package( INCLUDE_DIRS include LIBRARIES learning_communicationCATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs message_runtime DEPENDS system_lib) Build include_directories(include${catkin_INCLUDE_DIRS})add_executable(draw_path draw.cpp)target_link_libraries(draw_path ${catkin_LIBRARIES}) package.xml <?xml version="1.0"?><package><name>draw</name><version>0.0.0</version><description>The learning_communication package</description><!-- One maintainer tag required, multiple allowed, one person per tag --><!-- Example: --><!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> --><maintainer email="hcx@todo.todo">hcx</maintainer><!-- One license tag required, multiple allowed, one license per tag --><!-- Commonly used license strings: --><!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 --><license>TODO</license><!-- Url tags are optional, but multiple are allowed, one per tag --><!-- Optional attribute type can be: website, bugtracker, or repository --><!-- Example: --><!-- <url type="website">http://wiki.ros.org/learning_communication</url> --><!-- Author tags are optional, multiple are allowed, one per tag --><!-- Authors do not have to be maintainers, but could be --><!-- Example: --><!-- <author email="jane.doe@example.com">Jane Doe</author> --><!-- The _depend tags are used to specify dependencies --><!-- Dependencies can be catkin packages or system dependencies --><!-- Examples: --><!-- Use build_depend for packages you need at compile time: --><!-- <build_depend>message_generation</build_depend> --><!-- Use buildtool_depend for build tool packages: --><!-- <buildtool_depend>catkin</buildtool_depend> --><!-- Use run_depend for packages you need at runtime: --><!-- <run_depend>message_runtime</run_depend> --><!-- Use test_depend for packages you need only for testing: --><!-- <test_depend>gtest</test_depend> --><buildtool_depend>catkin</buildtool_depend><build_depend>geometry_msgs</build_depend><build_depend>roscpp</build_depend><build_depend>rospy</build_depend><build_depend>std_msgs</build_depend><run_depend>geometry_msgs</run_depend><run_depend>roscpp</run_depend><run_depend>rospy</run_depend><run_depend>std_msgs</run_depend><build_depend>message_generation</build_depend><run_depend>message_runtime</run_depend><!-- The export tag contains other, unspecified, tags --><export><!-- Other tools can request additional information be placed here --></export></package> vins_fusion: 双目vio等多系统 mkdir -p vins-catkin_ws/srccd vins-catkin_ws/srcgit clone https://github.com/HKUST-Aerial-Robotics/VINS-Fusion.gitcd ..catkin_makesource devel/setup.bash按照readme 3.1 Monocualr camera + IMUroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_mono_imu_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_mono_imu_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag 3.2 Stereo cameras + IMUroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_imu_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_imu_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag 3.3 Stereo camerasroslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_config.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/euroc/euroc_stereo_config.yaml rosbag play YOUR_DATASET_FOLDER/MH_01_easy.bag<img src="https://github.com/HKUST-Aerial-Robotics/VINS-Fusion/blob/master/support_files/image/euroc.gif" width = 430 height = 240 /> 4. KITTI Example 4.1 KITTI Odometry (Stereo)Download [KITTI Odometry dataset](http://www.cvlibs.net/datasets/kitti/eval_odometry.php) to YOUR_DATASET_FOLDER. Take sequences 00 for example,Open two terminals, run vins and rviz respectively. (We evaluated odometry on KITTI benchmark without loop closure funtion)roslaunch vins vins_rviz.launch(optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/kitti_odom/kitti_config00-02.yamlrosrun vins kitti_odom_test ~/catkin_ws/src/VINS-Fusion/config/kitti_odom/kitti_config00-02.yaml YOUR_DATASET_FOLDER/sequences/00/ 4.2 KITTI GPS Fusion (Stereo + GPS)Download [KITTI raw dataset](http://www.cvlibs.net/datasets/kitti/raw_data.php) to YOUR_DATASET_FOLDER. Take [2011_10_03_drive_0027_synced](https://s3.eu-central-1.amazonaws.com/avg-kitti/raw_data/2011_10_03_drive_0027/2011_10_03_drive_0027_sync.zip) for example.Open three terminals, run vins, global fusion and rviz respectively. Green path is VIO odometry; blue path is odometry under GPS global fusion.roslaunch vins vins_rviz.launchrosrun vins kitti_gps_test ~/catkin_ws/src/VINS-Fusion/config/kitti_raw/kitti_10_03_config.yaml YOUR_DATASET_FOLDER/2011_10_03_drive_0027_sync/ rosrun global_fusion global_fusion_node<img src="https://github.com/HKUST-Aerial-Robotics/VINS-Fusion/blob/master/support_files/image/kitti.gif" width = 430 height = 240 /> 5. VINS-Fusion on car demonstrationDownload [car bag](https://drive.google.com/open?id=10t9H1u8pMGDOI6Q2w2uezEq5Ib-Z8tLz) to YOUR_DATASET_FOLDER.Open four terminals, run vins odometry, visual loop closure(optional), rviz and play the bag file respectively. Green path is VIO odometry; red path is odometry under visual loop closure.roslaunch vins vins_rviz.launchrosrun vins vins_node ~/catkin_ws/src/VINS-Fusion/config/vi_car/vi_car.yaml (optional) rosrun loop_fusion loop_fusion_node ~/catkin_ws/src/VINS-Fusion/config/vi_car/vi_car.yaml rosbag play YOUR_DATASET_FOLDER/car.bag 本篇文章为转载内容。原文链接:https://blog.csdn.net/slzlincent/article/details/104364909。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-09-13 20:38:56
310
转载
转载文章
...开发工具、迁移与运维管理和专有云等方面,阿里云都做的很不错。 2.2 证件照生成背景 传统做法:通常是人工进行P图,不仅费时费力,而且效果也很难保障,容易有瑕疵。 机器学习做法:通常利用边缘检测算法进行人物轮廓提取。 深度学习做法:通常使用分割算法进行人物分割。例如U-Net网络。 2.3 图像分割算法 《BiHand: Recovering Hand Mesh with Multi-stage Bisected Hourglass Networks》里的SeedNet网络是很经典的网络,它把分割任务转变成多个任务。作者的思想是:尽可能的通过多任务学习收拢语义,这样或许会分割的更好或姿态估计的更好。其实这个模型就是多阶段学习网络的一部分,作者想通过中间监督来提高网络的性能。 我提取bihand网络中的SeedNet与训练权重,进行分割结果展示如下 我是用的模型不是全程的,是第一阶段的。为了可视化出最好的效果,我把第一阶段也就是SeedNet网络的输出分别采用不同的方式可视化。 从左边数第一张图为原图,第二张图为sigmoid后利用plt.imshow(colored_mask, cmap=‘jet’)进行彩色映射。第三张图为网络输出的张量经过sigmoid后,二色分割图,阀闸值0.5。第四张为网络的直接输出,利用直接产生的张量图进行颜色映射。第五张为使用sigmoid处理张量后进行的颜色映射。第六张为使用sigmoid处理张量后进行0,1分割掩码映射。使用原模型和网络需要添加很多代码。下面为修改后的的代码: 下面为修改后的net_seedd代码: Copyright (c) Lixin YANG. All Rights Reserved.r"""Networks for heatmap estimation from RGB images using Hourglass Network"Stacked Hourglass Networks for Human Pose Estimation", Alejandro Newell, Kaiyu Yang, Jia Deng, ECCV 2016"""import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom skimage import io,transform,utilfrom termcolor import colored, cprintfrom bihand.models.bases.bottleneck import BottleneckBlockfrom bihand.models.bases.hourglass import HourglassBisectedimport bihand.utils.func as funcimport matplotlib.pyplot as pltfrom bihand.utils import miscimport matplotlib.cm as cmdef color_mask(output_ok): 颜色映射cmap = plt.cm.get_cmap('jet') 将张量转换为numpy数组mask_array = output_ok.detach().numpy() 创建彩色图像cmap = cm.get_cmap('jet')colored_mask = cmap(mask_array)return colored_mask 可视化 plt.imshow(colored_mask, cmap='jet') plt.axis('off') plt.show()def two_color(mask_tensor): 将张量转换为numpy数组mask_array = mask_tensor.detach().numpy() 将0到1之间的值转换为二值化掩码threshold = 0.5 阈值,大于阈值的为白色,小于等于阈值的为黑色binary_mask = np.where(mask_array > threshold, 1, 0)return binary_mask 可视化 plt.imshow(binary_mask, cmap='gray') plt.axis('off') plt.show()class SeedNet(nn.Module):def __init__(self,nstacks=2,nblocks=1,njoints=21,block=BottleneckBlock,):super(SeedNet, self).__init__()self.njoints = njointsself.nstacks = nstacksself.in_planes = 64self.conv1 = nn.Conv2d(3, self.in_planes, kernel_size=7, stride=2, padding=3, bias=True)self.bn1 = nn.BatchNorm2d(self.in_planes)self.relu = nn.ReLU(inplace=True)self.maxpool = nn.MaxPool2d(2, stride=2)self.layer1 = self._make_residual(block, nblocks, self.in_planes, 2self.in_planes) current self.in_planes is 64 2 = 128self.layer2 = self._make_residual(block, nblocks, self.in_planes, 2self.in_planes) current self.in_planes is 128 2 = 256self.layer3 = self._make_residual(block, nblocks, self.in_planes, self.in_planes)ch = self.in_planes 256hg2b, res1, res2, fc1, _fc1, fc2, _fc2= [],[],[],[],[],[],[]hm, _hm, mask, _mask = [], [], [], []for i in range(nstacks): 2hg2b.append(HourglassBisected(block, nblocks, ch, depth=4))res1.append(self._make_residual(block, nblocks, ch, ch))res2.append(self._make_residual(block, nblocks, ch, ch))fc1.append(self._make_fc(ch, ch))fc2.append(self._make_fc(ch, ch))hm.append(nn.Conv2d(ch, njoints, kernel_size=1, bias=True))mask.append(nn.Conv2d(ch, 1, kernel_size=1, bias=True))if i < nstacks-1:_fc1.append(nn.Conv2d(ch, ch, kernel_size=1, bias=False))_fc2.append(nn.Conv2d(ch, ch, kernel_size=1, bias=False))_hm.append(nn.Conv2d(njoints, ch, kernel_size=1, bias=False))_mask.append(nn.Conv2d(1, ch, kernel_size=1, bias=False))self.hg2b = nn.ModuleList(hg2b) hgs: hourglass stackself.res1 = nn.ModuleList(res1)self.fc1 = nn.ModuleList(fc1)self._fc1 = nn.ModuleList(_fc1)self.res2 = nn.ModuleList(res2)self.fc2 = nn.ModuleList(fc2)self._fc2 = nn.ModuleList(_fc2)self.hm = nn.ModuleList(hm)self._hm = nn.ModuleList(_hm)self.mask = nn.ModuleList(mask)self._mask = nn.ModuleList(_mask)def _make_fc(self, in_planes, out_planes):bn = nn.BatchNorm2d(in_planes)conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False)return nn.Sequential(conv, bn, self.relu)def _make_residual(self, block, nblocks, in_planes, out_planes):layers = []layers.append( block( in_planes, out_planes) )self.in_planes = out_planesfor i in range(1, nblocks):layers.append(block( self.in_planes, out_planes))return nn.Sequential(layers)def forward(self, x):l_hm, l_mask, l_enc = [], [], []x = self.conv1(x) x: (N,64,128,128)x = self.bn1(x)x = self.relu(x)x = self.layer1(x)x = self.maxpool(x) x: (N,128,64,64)x = self.layer2(x)x = self.layer3(x)for i in range(self.nstacks): 2y_1, y_2, _ = self.hg2b[i](x)y_1 = self.res1[i](y_1)y_1 = self.fc1[i](y_1)est_hm = self.hm[i](y_1)l_hm.append(est_hm)y_2 = self.res2[i](y_2)y_2 = self.fc2[i](y_2)est_mask = self.mask[i](y_2)l_mask.append(est_mask)if i < self.nstacks-1:_fc1 = self._fc1[i](y_1)_hm = self._hm[i](est_hm)_fc2 = self._fc2[i](y_2)_mask = self._mask[i](est_mask)x = x + _fc1 + _fc2 + _hm + _maskl_enc.append(x)else:l_enc.append(x + y_1 + y_2)assert len(l_hm) == self.nstacksreturn l_hm, l_mask, l_encif __name__ == '__main__':a = torch.randn(10, 3, 256, 256) SeedNetmodel = SeedNet() output1,output2,output3 = SeedNetmodel(a) print(output1,output2,output3)total_params = sum(p.numel() for p in SeedNetmodel.parameters())/1000000print("Total parameters: ", total_params)pretrained_weights_path = 'E:/bihand/released_checkpoints/ckp_seednet_all.pth.tar'img_rgb_path=r"E:\FreiHAND\training\rgb\00000153.jpg"img=io.imread(img_rgb_path)resized_img = transform.resize(img, (256, 256), anti_aliasing=True)img256=util.img_as_ubyte(resized_img)plt.imshow(resized_img)plt.axis('off') 关闭坐标轴plt.show()''' implicit HWC -> CHW, 255 -> 1 '''img1 = func.to_tensor(img256).float() 转换为张量并且进行标准化处理''' 0-mean, 1 std, [0,1] -> [-0.5, 0.5] '''img2 = func.normalize(img1, [0.5, 0.5, 0.5], [1, 1, 1])img3 = torch.unsqueeze(img2, 0)ok=img3print(img.shape)SeedNetmodel = SeedNet()misc.load_checkpoint(SeedNetmodel, pretrained_weights_path)加载权重output1, output2, output3 = SeedNetmodel(img3)mask_tensor = torch.rand(1, 64, 64)output=output2[1] 1,1,64,64output_1=output[0] 1,64,64output_ok=torch.sigmoid(output_1[0])output_real=output_1[0].detach().numpy()直接产生的张量图color_mask=color_mask(output_ok) 显示彩色分割图two_color=two_color(output_ok)显示黑白分割图see=output_ok.detach().numpy() 使用Matplotlib库显示分割掩码 plt.imshow(see, cmap='gray') plt.axis('off') plt.show() print(output1, output2, output3)images = [resized_img, color_mask, two_color,output_real,see,see]rows = 1cols = 4 创建子图并展示图像fig, axes = plt.subplots(1, 6, figsize=(30, 5)) 遍历图像列表,并在每个子图中显示图像for i, image in enumerate(images):ax = axes[i] if cols > 1 else axes 如果只有一列,则直接使用axesif i ==5:ax.imshow(image, cmap='gray')else:ax.imshow(image)ax.imshowax.axis('off') 调整子图之间的间距plt.subplots_adjust(wspace=0.1, hspace=0.1) 展示图像plt.show() 上述的代码文件是在bihand/models/net_seed.py中,全部代码链接在https://github.com/lixiny/bihand。 把bihand/models/net_seed.p中的代码修改为我提供的代码即可使用作者训练好的模型和进行各种可视化。(预训练模型根据作者代码提示下载) 3.调用阿里云API进行证件照生成实例 3.1 准备工作 1.找到接口 进入下面链接即可快速访问 link 2.购买试用包 3.查看APPcode 4.下载代码 5.参数说明 3.2 实验代码 !/usr/bin/python encoding: utf-8"""===========================证件照制作接口==========================="""import requestsimport jsonimport base64import hashlibclass Idphoto:def __init__(self, appcode, timeout=7):self.appcode = appcodeself.timeout = timeoutself.make_idphoto_url = 'https://idp2.market.alicloudapi.com/idphoto/make'self.headers = {'Authorization': 'APPCODE ' + appcode,}def get_md5_data(self, body):"""md5加密:param body_json::return:"""md5lib = hashlib.md5()md5lib.update(body.encode("utf-8"))body_md5 = md5lib.digest()body_md5 = base64.b64encode(body_md5)return body_md5def get_photo_base64(self, file_path):with open(file_path, 'rb') as fp:photo_base64 = base64.b64encode(fp.read())photo_base64 = photo_base64.decode('utf8')return photo_base64def aiseg_request(self, url, data, headers):resp = requests.post(url=url, data=data, headers=headers, timeout=self.timeout)res = {"status_code": resp.status_code}try:res["data"] = json.loads(resp.text)return resexcept Exception as e:print(e)def make_idphoto(self, file_path, bk, spec="2"):"""证件照制作接口:param file_path::param bk::param spec::return:"""photo_base64 = self.get_photo_base64(file_path)body_json = {"photo": photo_base64,"bk": bk,"with_photo_key": 1,"spec": spec,"type": "jpg"}body = json.dumps(body_json)body_md5 = self.get_md5_data(body=body)self.headers.update({'Content-MD5': body_md5})data = self.aiseg_request(url=self.make_idphoto_url, data=body, headers=self.headers)return dataif __name__ == "__main__":file_path = "图片地址"idphoto = Idphoto(appcode="你的appcode")d = idphoto.make_idphoto(file_path, "red", "2")print(d) 3.3 实验结果与分析 原图片 背景为红色生成的证件照 背景为蓝色生成的证件照 另外尝试了使用柴犬照片做实验,也生成了证件照 原图 背景为红色生成的证件照 参考(可供参考的链接和引用文献) 1.参考:BiHand: Recovering Hand Mesh with Multi-stage Bisected Hourglass Networks(BMVC2020) 论文链接:https://arxiv.org/pdf/2008.05079.pdf 本篇文章为转载内容。原文链接:https://blog.csdn.net/m0_37758063/article/details/131128967。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-07-11 23:36:51
131
转载
转载文章
...节约大量的服务器端的系统资源,并且提供更好的用户体验。 创建正则表达式 创建正则表达式和创建字符串类似,创建正则表达式提供了两种方法,一种是采用 new 运算符,另一个是采用字面量方式。 两种创建方式 var box = new RegExp('box'); // 第一个参数字符串var box = new RegExp('box', 'ig'); // 第二个参数可选模式修饰符 模式修饰符的可选参数 参数 含义 i 忽略大小写 g 全局匹配 m 多行匹配 var box = /box/; // 直接用两个反斜杠var box = /box/ig; // 在第二个斜杠后面加上模式修饰符 测试正则表达式 RegExp 对象包含两个方法:test()和 exec(),功能基本相似,用于测试字符串匹配。test()方法在字符串中查找是否存在指定的正则表达式并返回布尔值,如果存在则返回 true,不存在则返回 false。exec()方法也用于在字符串中查找指定正则表达式,如果 exec()方法执行成功,则返回包含该查找字符串的相关信息数组。如果执行失败,则返回 null。 RegExp 对象的方法 方法 功能 test 在字符串中测试模式匹配,返回 true 或 false exec 在字符串中执行匹配搜索,返回结果数组 // 使用 new 运算符的 test 方法示例var pattern = new RegExp('box', 'i'); // 创建正则模式,不区分大小写var str = 'This is a Box!'; // 创建要比对的字符串alert(pattern.test(str)); // 通过 test()方法验证是否匹配// 使用字面量方式的 test 方法示例var pattern = /box/i; // 创建正则模式,不区分大小写var str = 'This is a Box!';alert(pattern.test(str));// 使用一条语句实现正则匹配alert(/box/i.test('This is a Box!')); // 模式和字符串替换掉了两个变量// 使用 exec 返回匹配数组var pattern = /box/i;var str = 'This is a Box!';alert(pattern.exec(str)); // 匹配了返回数组,否则返回 null 使用字符串的正则表达式方法 除了 test()和 exec()方法,String 对象也提供了 4 个使用正则表达式的方法。 String 对象中的正则表达式方法 方法 含义 match(pattern) 返回 pattern 中的子串或 null replace(pattern, replacement) 用 replacement 替换 pattern search(pattern) 返回字符串中 pattern 开始位置 split(pattern) 返回字符串按指定 pattern 拆分的数组 // 使用 match 方法获取获取匹配数组var pattern = /box/ig; // 全局搜索var str = 'This is a Box!,That is a Box too';alert(str.match(pattern)); // 匹配到两个 Box,Boxalert(str.match(pattern).length); // 获取数组的长度// 使用 search 来查找匹配数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.search(pattern)); // 查找到返回位置,否则返回-1 因为 search 方法查找到即返回,也就是说无需 g 全局。 // 使用 replace 替换匹配到的数据var pattern = /box/ig;var str = 'This is a Box!,That is a Box too';alert(str.replace(pattern, 'Tom')); // 将 Box 替换成了 Tom// 使用 split 拆分成字符串数组var pattern = / /ig;var str = 'This is a Box!,That is a Box too';alert(str.split(pattern)); // 将空格拆开分组成数组 RegExp 对象的静态属性 属性 短名 含义 input $_ 当前被匹配的字符串 lastMatch $& 最后一个匹配字符串 lastParen $+ 最后一对圆括号内的匹配子串 leftContext $ 最后一次匹配前的子串 multiline $ 用于指定是否所有的表达式都用于多行的布尔值 rightContext $’ 在上次匹配之后的子串 // 使用静态属性var pattern = /(g)oogle/;var str = 'This is google!';pattern.test(str); // 执行一下alert(RegExp.input); // This is google!alert(RegExp.leftContext); // This isalert(RegExp.rightContext); // !alert(RegExp.lastMatch); // googlealert(RegExp.lastParen); // galert(RegExp.multiline); // false Opera 不支持 input、lastMatch、lastParen 和 multiline 属性。IE 不支持 multiline 属性。所有的属性可以使用短名来操作。RegExp.input 可以改写成 RegExp['$_'],依次类推。但 RegExp.input 比较特殊,它还可以写成 RegExp.$_。 RegExp 对象的实例属性 属性 含义 global Boolean 值,表示 g 是否已设置 ignoreCase Boolean 值,表示 i 是否已设置 lastIndex 整数,代表下次匹配将从哪里字符位置开始 multiline Boolean 值,表示 m 是否已设置 Source 正则表达式的源字符串形式 // 使用实例属性var pattern = /google/ig;alert(pattern.global); // true,是否全局了alert(pattern.ignoreCase); // true,是否忽略大小写alert(pattern.multiline); // false,是否支持换行alert(pattern.lastIndex); // 0,下次的匹配位置alert(pattern.source); // google,正则表达式的源字符串var pattern = /google/g;var str = 'google google google';pattern.test(str); // google,匹配第一次alert(pattern.lastIndex); // 6,第二次匹配的位 以上基本没什么用。并且 lastIndex 在获取下次匹配位置上 IE 和其他浏览器有偏差 ,主要表现在非全局匹配上。lastIndex 还支持手动设置,直接赋值操作。 获取控制 正则表达式元字符是包含特殊含义的字符。它们有一些特殊功能,可以控制匹配模式的方式。反斜杠后的元字符将失去其特殊含义。 字符类:单个字符和数字 元字符/元符号 匹配情况 . 匹配除换行符外的任意字符 [a-z0-9] 匹配括号中的字符集中的任意字符 [^a-z0-9] 匹配任意不在括号中的字符集中的字符 \d 匹配数字 \D 匹配非数字,同[^0-9]相同 \w 匹配字母和数字及_ \W 匹配非字母和数字及_ 字符类:空白字符 元字符/元符号 匹配情况 \0 匹配 null 字符 \b 匹配空格字符 \f 匹配进纸字符 \n 匹配换行符 \r 匹配回车字符 \t 匹配制表符 \s 匹配空白字符、空格、制表符和换行符 \S 匹配非空白字符 字符类:锚字符 元字符/元符号 匹配情况 ^ 行首匹配 $ 行尾匹配 \A 只有匹配字符串开始处 \b 匹配单词边界,词在[]内时无效 \B 匹配非单词边界 \G 匹配当前搜索的开始位置 \Z 匹配字符串结束处或行尾 \z 只匹配字符串结束处 字符类:重复字符 元字符/元符号 匹配情况 x? 匹配 0 个或 1 个 x x 匹配 0 个或任意多个 x x+ 匹配至少一个 x (xyz)+ 匹配至少一个(xyz) x{m,n} 匹配最少 m 个、最多 n 个 x 字符类:替代字符 元字符/元符号 匹配情况 this where 字符类:记录字符 元字符/元符号 匹配情况 (string) 用于反向引用的分组 \1 或$1 匹配第一个分组中的内容 \2 或$2 匹配第二个分组中的内容 \3 或$3 匹配第三个分组中的内容 // 使用点元字符var pattern = /g..gle/; // .匹配一个任意字符var str = 'google';alert(pattern.test(str));// 重复匹配var pattern = /g.gle/; // .匹配 0 个一个或多个var str = 'google'; //,?,+,{n,m}alert(pattern.test(str));// 使用字符类匹配var pattern = /g[a-zA-Z_]gle/; // [a-z]表示任意个 a-z 中的字符var str = 'google';alert(pattern.test(str));var pattern = /g[^0-9]gle/; // [^0-9]表示任意个非 0-9 的字符var str = 'google';alert(pattern.test(str));var pattern = /[a-z][A-Z]+/; // [A-Z]+表示 A-Z 一次或多次var str = 'gOOGLE';alert(pattern.test(str));// 使用元符号匹配var pattern = /g\wgle/; // \w匹配任意多个所有字母数字_var str = 'google';alert(pattern.test(str));var pattern = /google\d/; // \d匹配任意多个数字var str = 'google444';alert(pattern.test(str));var pattern = /\D{7,}/; // \D{7,}匹配至少 7 个非数字var str = 'google8';alert(pattern.test(str));// 使用锚元字符匹配var pattern = /^google$/; // ^从开头匹配,$从结尾开始匹配var str = 'google';alert(pattern.test(str));var pattern = /goo\sgle/; // \s 可以匹配到空格var str = 'goo gle';alert(pattern.test(str));var pattern = /google\b/; // \b 可以匹配是否到了边界var str = 'google';alert(pattern.test(str));// 使用或模式匹配var pattern = /google|baidu|bing/; // 匹配三种其中一种字符串var str = 'google';alert(pattern.test(str));// 使用分组模式匹配var pattern = /(google){4,8}/; // 匹配分组里的字符串 4-8 次var str = 'googlegoogle';alert(pattern.test(str));var pattern = /8(.)8/; // 获取 8..8 之间的任意字符var str = 'This is 8google8';str.match(pattern);alert(RegExp.$1); // 得到第一个分组里的字符串内容var pattern = /8(.)8/;var str = 'This is 8google8';var result = str.replace(pattern,'<strong>$1</strong>'); // 得到替换的字符串输出document.write(result);var pattern = /(.)\s(.)/;var str = 'google baidu';var result = str.replace(pattern, '$2 $1'); // 将两个分组的值替换输出document.write(result); 贪婪 惰性 + +? ? ?? ? {n} {n}? {n,} {n,}? {n,m} {n,m}? // 关于贪婪和惰性var pattern = /[a-z]+?/; // ?号关闭了贪婪匹配,只替换了第一个var str = 'abcdefjhijklmnopqrstuvwxyz';var result = str.replace(pattern, 'xxx');alert(result);var pattern = /8(.+?)8/g; // 禁止了贪婪,开启的全局var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);var pattern = /8([^8])8/g; // 另一种禁止贪婪var str = 'This is 8google8, That is 8google8, There is 8google8';var result = str.replace(pattern,'<strong>$1</strong>');document.write(result);// 使用 exec 返回数组var pattern = /^[a-z]+\s[0-9]{4}$/i;var str = 'google 2012';alert(pattern.exec(str)); // 返回整个字符串var pattern = /^[a-z]+/i; // 只匹配字母var str = 'google 2012';alert(pattern.exec(str)); // 返回 googlevar pattern = /^([a-z]+)\s([0-9]{4})$/i; // 使用分组var str = 'google 2012';alert(pattern.exec(str)[0]); // google 2012alert(pattern.exec(str)[1]); // googlealert(pattern.exec(str)[2]); // 2012// 捕获性分组和非捕获性分组var pattern = /(\d+)([a-z])/; // 捕获性分组var str = '123abc';alert(pattern.exec(str));var pattern = /(\d+)(?:[a-z])/; // 非捕获性分组var str = '123abc';alert(pattern.exec(str));// 使用分组嵌套var pattern = /(A?(B?(C?)))/; // 从外往内获取var str = 'ABC';alert(pattern.exec(str));// 使用前瞻捕获var pattern = /(goo(?=gle))/; // goo 后面必须跟着 gle 才能捕获var str = 'google';alert(pattern.exec(str));// 使用特殊字符匹配var pattern = /\.\[\/b\]/; // 特殊字符,用\符号转义即可var str = '.[/b]';alert(pattern.test(str));// 使用换行模式var pattern = /^\d+/mg; // 启用了换行模式var str = '1.baidu\n2.google\n3.bing';var result = str.replace(pattern, '');alert(result); 常用的正则 检查邮政编码 var pattern = /[1-9][0-9]{5}/; // 共 6 位数字,第一位不能为 0var str = '224000';alert(pattern.test(str)); 检查文件压缩包 var pattern = /[\w]+\.zip|rar|gz/; // \w 表示所有数字和字母加下划线var str = '123.zip'; // \.表示匹配.,后面是一个选择alert(pattern.test(str)); 删除多余空格 var pattern = /\s/g; // g 必须全局,才能全部匹配var str = '111 222 333';var result = str.replace(pattern,''); // 把空格匹配成无空格alert(result); 删除首尾空格 var pattern = /^\s+/; // 强制首var str = ' goo gle ';var result = str.replace(pattern, '');pattern = /\s+$/; // 强制尾result = result.replace(pattern, '');alert('|' + result + '|');var pattern = /^\s(.+?)\s$/; // 使用了非贪婪捕获var str = ' google ';alert('|' + pattern.exec(str)[1] + '|');var pattern = /^\s(.+?)\s$/;var str = ' google ';alert('|' + str.replace(pattern, '$1') + '|'); // 使用了分组获取 简单的电子邮件验证 var pattern = /^([a-zA-Z0-9_\.\-]+)@([a-zA-Z0-9_\.\-]+)\.([a-zA-Z]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str));var pattern = /^([\w\.\-]+)@([\w\.\-]+)\.([\w]{2,4})$/;var str = 'yc60.com@gmail.com';alert(pattern.test(str)); 3、Function类型 在 ECMAScript 中,Function(函数)类型实际上是对象。每个函数都是 Function 类型的实例,而且都与其他引用类型一样具有属性和方法。由于函数是对象,因此函数名实际上也是一个指向函数对象的指针。 函数的声明方式 普通的函数声明 function box(num1, num2) {return num1+ num2;} 使用变量初始化函数 var box= function(num1, num2) {return num1 + num2;}; 使用 Function 构造函数 var box= new Function('num1', 'num2' ,'return num1 + num2'); 第三种方式我们不推荐,因为这种语法会导致解析两次代码(第一次解析常规 ECMAScript 代码,第二次是解析传入构造函数中的字符串),从而影响性能。但我们可以通过这种语法来理解"函数是对象,函数名是指针"的概念。 作为值的函数 ECMAScript 中的函数名本身就是变量,所以函数也可以作为值来使用。也就是说,不仅可以像传递参数一样把一个函数传递给另一个函数,而且可以将一个函数作为另一个函数的结果返回。 function box(sumFunction, num) {return sumFunction(num); // someFunction}function sum(num) {return num + 10;}var result = box(sum, 10); // 传递函数到另一个函数里 函数内部属性 在函数内部,有两个特殊的对象:arguments 和 this。arguments 是一个类数组对象,包含着传入函数中的所有参数,主要用途是保存函数参数。但这个对象还有一个名叫 callee 的属性,该属性是一个指针,指向拥有这个 arguments 对象的函数。 function box(num) {if (num <= 1) {return 1;} else {return num box(num-1); // 一个简单的的递归} } 对于阶乘函数一般要用到递归算法,所以函数内部一定会调用自身;如果函数名不改变是没有问题的,但一旦改变函数名,内部的自身调用需要逐一修改。为了解决这个问题,我们可以使用 arguments.callee 来代替。 function box(num) {if (num <= 1) {return 1;} else {return num arguments.callee(num-1); // 使用 callee 来执行自身} } 函数内部另一个特殊对象是 this,其行为与 Java 和 C中的 this 大致相似。换句话说 ,this 引用的是函数据以执行操作的对象,或者说函数调用语句所处的那个作用域。当在全局作用域中调用函数时,this 对象引用的就是 window。 // 便于理解的改写例子window.color = '红色的'; // 全局的,或者 var color = '红色的';也行alert(this.color); // 打印全局的 colorvar box = {color : '蓝色的', // 局部的 colorsayColor : function () {alert(this.color); // 此时的 this 只能 box 里的 color} };box.sayColor(); // 打印局部的 coloralert(this.color); // 还是全局的// 引用教材的原版例子window.color = '红色的'; // 或者 var color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color); // 这里第一次在外面,第二次在 box 里面}getColor();box.sayColor = sayColor; // 把函数复制到 box 对象里,成为了方法box.sayColor(); 函数属性和方法 ECMAScript 中的函数是对象,因此函数也有属性和方法。每个函数都包含两个属性 :length 和 prototype。其中,length 属性表示函数希望接收的命名参数的个数。 function box(name, age) {alert(name + age);}alert(box.length); // 2 对于 prototype 属性,它是保存所有实例方法的真正所在,也就是原型。这个属性 ,我们将在面向对象一章详细介绍。而 prototype 下有两个方法:apply()和 call(),每个函数都包含这两个非继承而来的方法。这两个方法的用途都在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。 function box(num1, num2) {return num1 + num2; // 原函数}function sayBox(num1, num2) {return box.apply(this, [num1, num2]); // this 表示作用域,这里是 window} // []表示 box 所需要的参数function sayBox2(num1, num2) {return box.apply(this, arguments); // arguments 对象表示 box 所需要的参数}alert(sayBox(10,10)); // 20alert(sayBox2(10,10)); // 20 call()方法于 apply()方法相同,他们的区别仅仅在于接收参数的方式不同。对于 call()方法而言,第一个参数是作用域,没有变化,变化只是其余的参数都是直接传递给函数的。 function box(num1, num2) {return num1 + num2;}function callBox(num1, num2) {return box.call(this, num1, num2); // 和 apply 区别在于后面的传参}alert(callBox(10,10)); 事实上,传递参数并不是 apply()和 call()方法真正的用武之地;它们经常使用的地方是能够扩展函数赖以运行的作用域。 var color = '红色的'; // 或者 window.color = '红色的';也行var box = {color : '蓝色的'};function sayColor() {alert(this.color);}sayColor(); // 作用域在 windowsayColor.call(this); // 作用域在 windowsayColor.call(window); // 作用域在 windowsayColor.call(box); // 作用域在 box,对象冒充 这个例子是之前作用域理解的例子修改而成,我们可以发现当我们使用 call(box)方法的时候,sayColor()方法的运行环境已经变成了 box 对象里了。 使用 call()或者 apply()来扩充作用域的最大好处,就是对象不需要与方法发生任何耦合关系(耦合,就是互相关联的意思,扩展和维护会发生连锁反应)。也就是说,box 对象和 sayColor()方法之间不会有多余的关联操作,比如 box.sayColor = sayColor;。 本篇文章为转载内容。原文链接:https://blog.csdn.net/gongxifacai_believe/article/details/108286196。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-24 13:01:25
529
转载
转载文章
...或是所有具备一定智能系统所共有的现象。该研究计划在未来几年内推出相关成果,或将为我们理解人工智能的发展边界提供新的理论依据。 此外,随着全球范围内对人工智能伦理问题的关注度日益提高,各国政府及国际组织正着手制定相关政策法规,探讨如何界定智能机器的行为责任以及保护人类免受潜在风险的影响。例如,欧盟近期已提出一套涵盖人工智能道德原则的框架,其中涉及到了对人工智能自主决策权的限制,以及确保其行为遵循人类价值观的要求。 综上所述,人工智能与人类智能边界的探索不断深入,而对灵魂、心流等概念的理解也在科技进步与哲学思辨的交融中得以丰富和完善。在追求更高水平的人工智能发展的同时,我们应始终关注并思考如何保持人类特性的核心地位,以及如何构建和谐共生的人机关系。
2023-01-02 11:30:59
620
转载
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
du -sh *
- 查看当前目录下所有文件及目录占用的空间大小(以人类可读格式)。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"