首页 文章 精选 留言 我的

精选列表

搜索[笔记],共9177篇文章
优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day60)——Core Foundation框架

Core Foundation框架是苹果公司提供一套概念来源于Foundation框架,编程接口面向C语言风格的API。虽然在Swift中调用这种C语言风格的API比较麻烦,但是在OS X和iOS开发过程中,有时候使用CoreFoundation框架的API是非常方便的,例如在与C语言混合编码的时候。 Core Foundation框架与Foundation框架紧密相关,他们具有与相同的接口,但是不同。Core Foundation框架是基于C语言风格的,而Foundation框架是基于Objective-C语言风格的。在OS X和iOS程序代码中经常会有多种语言风格的代码混合在一起的情况,这使得我们开发变得更加麻烦。 数据类型映射 Core Foundation框架提供了一些不透明的数据类型,这些数据类型封装了一些数据和操作,他们也可以称为“类”,他们都继承于CFType类,CFType是所用Core Foundation框架类型的根类。这些数据类型在Foundation框架中都有相应的数据类型与之对应,这些数据类型也有一些与Swift原生数据类型有对应关系。 看看Swift原生类型与Core Foundation类型之间的转换示例: 1 2 3 4 5 6 7 8 import CoreFoundation import Foundation varcfstr1:CFString= "Hello,World" //创建CFString字符串 varstr:String=cfstr1asString //将CFString字符串转换为Swift原生字符串String varcfstr2:CFString=str //将Swift原生字符串String转换为CFString字符串 这个转换过程中Core Foundation类型转换为Swift原生类型是需要强制类型转换的。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1748349,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 18)——有几个分支语句?

分支语句又称条件语句,Swift编程语言提供了if、switch和guard三种分支语句。 if语句 由if语句引导的选择结构有if结构、if-else结构和else-if结构3种。 if结构示例代码如下: 1 2 3 4 5 varscore= 95 if score>= 85 { print( "您真优秀!" ) } 程序运行结果如下: 您真优秀! if-else结构示例代码如下: 1 2 3 4 5 6 7 varscore= 95 if score< 60 { print( "不及格" ) } else { print( "及格" ) } 程序运行结果如下: 及格 else-if结构示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 lettestscore= 76 vargrade:Character if testscore>= 90 { grade= "A" } else if testscore>= 80 { grade= "B" } else if testscore>= 70 { grade= "C" } else if testscore>= 60 { grade= "D" } else { grade= "F" } print( "Grade=\(grade)" ) 输出结果如下: Grade = C switch语句 switch语句也称开关语句,它提供多分支程序结构。 switch语句基本形式示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 lettestscore= 86 vargrade:Character switchtestscore/ 10 { case 9 : grade= "优" case 8 : grade= "良" case 7 , 6 : grade= "中" default : grade= "差" } print( "Grade=\(grade)" ) 输出结果如下: Grade =良 guard语句 guard语句是Swift 2.0新添加的关键字,它与if语句非常类似,它设计的目的是提高程序的可读性。 guard语句必须带有else语句,它的语法如下: guard条件表达式else{ 跳转语句 } 语句组 当条件表达式为true时候跳过else语句中的内容,执行语句组内容。条件表达式为false时候执行else语句中的内容,跳转语句一般是return、break、continue和throw。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1746243,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 50)——扩展计算属性、方法

可以在原始类型上扩展计算属性,包括实例计算属性和静态计算属性。添加计算属性的定义,与普通的计算属性的定义是一样的。 实例计算属性示例:在网络编程时,为了减少流量,从服务器端返回的不是信息描述,而是编码,然后在本地再将编码转换为描述信息。为此定义了如下Int类型扩展: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 extensionInt{ //定义Int类型的扩展 varerrorMessage:String{ //只读计算属性 varerrorStr= "" switch (self){ case - 7 : errorStr= "没有数据。" case - 6 : errorStr= "日期没有输入。" case - 5 : errorStr= "内容没有输入。" case - 4 : errorStr= "ID没有输入。" case - 3 : errorStr= "据访问失败。" case - 2 : errorStr= "您的账号最多能插入10条数据。" case - 1 : errorStr= "用户不存在,请到http://51work6.com注册。" default : errorStr= "" } return errorStr } } letmessage=(- 7 ).errorMessage //获得-7编码对应的描述信息 print( "ErrorCode:-7,ErrorMessage:\(message)" ) 注意整个-7包括负号是一个完整的实例,因此调用它的属性时需要将-7作为一个整体用小括号括起来。然而,如果是7则不需要括号。 下面再看一个静态属性的示例: 1 2 3 4 5 6 7 8 9 10 11 12 structAccount{ //定义Account结构体 varamount:Double= 0.0 //账户金额 varowner:String= "" //账户名 } extensionAccount{ //定义Account结构体的扩展静态 static varinterestRate:Double{ //利率 return0. 0668 } } print(Account.interestRate) //打印输出interestRate属性 打印输出interestRate属性,访问方式与其他的静态计算属性一样,通过“类型名”加“.”来访问静态计算属性。 扩展方法 可以在原始类型上扩展方法,包括实例方法和静态方法。这些添加方法的定义与普通方法的定义是一样的。 下面先看一个示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 extensionDouble{ //定义Double类型的扩展 static varinterestRate:Double= 0.0668 //利率 funcinterestBy1()->Double{ return self*Double.interestRate //静态属性利率 } mutatingfuncinterestBy2(){ //定义实例方法interestBy2 self=self*Double.interestRate } static funcinterestBy3(amount:Double)->Double{ //定义静态方法interestBy3 return interestRate*amount //返回值是计算利息结果 } } letinterest1=(10_000. 00 ).interestBy1() //调用interestBy1方法计算利息 print( "利息1:\(interest1)" ) varinterest2=10_000. 00 //调用interestBy2方法计算利息 interest2.interestBy2() print( "利息2:\(interest2)" ) varinterest3=Double.interestBy3(10_000. 00 ) //调用interestBy3方法计算利息 print( "利息3:\(interest3)" ) 代码self = self *Double.interestRate,把计算结果直接赋值给当前实例self。在结构体和枚举类型中给self赋值会有编译错误,需要在方法前面加上mutating关键字,表明这是变异方法。 调用interestBy1方法计算利息,调用它的实例10_000.00,它的返回值被赋值给interest1常量,这是很常见的调用过程。 调用interestBy2方法计算利息,我们不能使用10_000.00实例调用,而是需要一个Double类型的变量interest2。interestBy2是变异方法,它会直接改变变量interest2的值,因此interest2.interestBy2()语句调用完成后,变量interest2的值就改变了。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1747538,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 24)——枚举(Day 24)——枚举

Swift中的枚举可以定义一组常量、提高程序的可读性;还具有面向对象特性。 使用enum关键词声明枚举类型,具体定义放在一对大括号内,枚举的语法格式如下: enum枚举名 { 枚举的定义 } “枚举名”是该枚举类型的名称。它首先应该是有效的标识符,其次应该遵守面向对象的命名规范,它由一组成员值和一组相关值组成。 成员值 枚举的成员值默认情况下不是整数类型,以下代码是声明枚举示例: 1 2 3 4 5 6 7 enum WeekDays{ case Monday case Tuesday case Wednesday case Thursday case Friday } 在这些成员值前面要加上case关键字,也可以将多个成员值放在同一行,用逗号隔开,如下所示: 1 2 3 enum WeekDays{ case Monday,Tuesday,Wednesday,Thursday,Friday } 下面我们看一个示例,代码如下: 1 2 3 varday=WeekDays.Friday day=WeekDays.Wednesday day=.Monday 使用枚举成员赋值时候,我们可以采用完整的“枚举类型名.成员值”的形式,也可以省略枚举类型采用“.成员值”的形式。这种省略形式能够访问的前提是,Swift编译器能够根据上下文环境推断类型。因为我们已经在第1行和第2行给day变量赋值,所以即使第3行代码采用缩写,Swift编译器能够推断出数据类型是WeekDays。 原始值 出于业务上的需要,要为每个成员提供某种基本数据类型,我们可以为枚举类型提供原始值(raw values)声明,这些原始值类型可以是:字符、字符串、整数和浮点数等。 原始值枚举的语法格式如下: 1 2 3 4 5 enum 枚举名:数据类型 { case 成员名=默认值 ... } 在“枚举名”后面跟“:”和“数据类型”就可以声明原始值枚举的类型,然后在定义case成员的时候需要提供原始值。 以下代码是声明枚举示例: 1 2 3 4 5 6 7 enum WeekDays:Int{ case Monday= 0 case Tuesday= 1 case Wednesday= 2 case Thursday= 3 case Friday= 4 } 我们声明的WeekDays枚举类型的原始值类型是Int,需要给每个成员赋值,只要是Int类型都可以,但是每个分支不能重复。 相关值 在Swift中除了可以定义一组成员值,还可以定义一组相关值(associated values),它有点类似于C中的联合类型。下面看一个枚举类型的声明: 1 2 3 4 enum Figure{ case Rectangle(Int,Int) case Circle(Int) } 枚举类型Figure(图形)有两个相关值:Rectangle(矩形)和Circle(圆形)。Rectangle和Circle是与Figure有关联的相关值,它们都是元组类型,对于一个特定的Figure实例,只能是其中一个相关值。从这一点来看,枚举类型的相关值类似于C中的联合类型。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1746420,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day54)——抛出错误

能放到try后面调用函数或方法都是有要求的,他们是有可能抛出错误,在这些函数或方法声明的参数后面要加上throws关键字,表示这个函数或方法可以抛出错误。 声明抛出错误方法示例代码如下: 1 2 3 4 5 6 7 8 //删除Note记录方法 funcremove(model:Note) throws { ... } //查询所有记录数据方法 funcfindAll() throws ->[Note]{ ... } 上述代码remove(_:)方法没有返回值,throws关键字放到参数后面。findAll()有返回值throws关键字放到参数和返回值类型之间。 在函数或方法中抛出错误 一个函数或方法能够声明抛出错误,是因为在函数或方法中产生并抛出了错误,这样函数或方法声明抛出错误才有实际的意义。 在产生并抛出错误方式: 在函数或方法中通过throw语句,人为地抛出错误。 在函数或方法中调用的其他可以抛出错误函数或方法,但是没有捕获处理,会导致错误被传播出来。 示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 //删除Note方法 funcremove(model:Note) throws { guardletdate=model.date else { //判断抛出时候是有了guard语句 //抛出"主键为空"错误 throw DAOError.PrimaryKeyNull } //比较日期主键是否相等 for (index,note)inlistData.enumerate()wherenote.date==date{ listData.removeAtIndex(index) } } //查询所有数据方法 funcfindAll() throws ->[Note]{ guardlistData.count> 0 else { //判断抛出时候是有了guard语句 //抛出"没有数据"错误。 throw DAOError.NoData } return listData } funcprintNotes() throws { //声明抛出错误 letdatas= try findAll() for noteindatas{ print( "date:\(note.date!)-content:\(note.content!)" ) } } try printNotes() guard语句最擅长处理这种早期判断,条件为false情况下抛出错误。 findAll()语句本身有可能产生错误,但是并没有使用catch语句捕获并处理,这样就导致了这个错误传播给该函数或方法的调用者,如果它的调用者也都不捕获处理,那么最后程序会出现运行期错误。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1748307,如需转载请自行联系原作者

优秀的个人博客,低调大师

阿里云云计算工程师ACP学习笔记--知识点总结

Elastic Compute Server 是一种处理能力可弹性伸缩的计算服务。 CPU内存需要停机,带宽不需要。 垂直:带宽 CPU 内存 水平:服务器 Region 地域 Zone 可用区 安全组, 允许包含跨可用区的实例 磁盘 只能挂在同一可用区 快照镜像 可以跨可用区,镜像可以复制到别的地域 发生故障时,实例只能在同一个可用区迁移 默认系统盘40GB-500GB ,系统盘设备名:/dev/xvda ECS创建时必须要选择镜像来确定其操作系统 更换系统盘不会更改实例的 IP 地址和 MAC 地址。 包年包月 最小一周 支持随时升级 带宽 不能提前释放 按量付费 不支持实例规格升级 带宽 可随时释放 高效云盘 20 -- 32768GB 3000* 80MBps 都是3个备份,不同交换机下的不同物理服务器上 SSD云盘 20 -- 32768GB 20000* 吞吐量 300MBps 普通云盘 2000GB 数百 30MBps 磁盘同一时间内,只能挂载在1个实例上。可设置是否随实例一起释放,只支持按量付费 一个ECS实例最多可以挂载16块数据盘 扩容需要重启服务器,手动去格式化,数据是保留的。 e2fsck -f /dev/vdb1 resize2fs /dev/vdb1 实例卸载 全部磁盘卸载 快照 磁盘数据在某个时间点的拷贝 增量快照 默认安装云盾 安全组 指定源IP地址段 CIDR Block 指定源安全组的ID(内网) 支持对入 出方向 每个用户最多100个安全组,每个安全组最多有1000个实例。 每个实例最多加入5个安全组,每个安全组最多100条规则。 安全组优先级1-100,1最大 4G内存以上不能选择32位操作系统 实例系列2 3 支持I/0优化,1的只有2C4G以上。 删除快照需要先删除相对应的镜像 每块磁盘提供 64 个快照额度 每个实例最多有10个标签 ECS API ecs.aliyuncs.com 签名机制 signature Access Key ID Accesss Key Secret 单个key 5000次/天 5个key Object Storage Server 云存储服务 可用性99.9% 可靠性 10个9 数据三备份 安全 防DDos 访问日志 无限扩展 Object put 5GB multipart 上传最大48.8TB 必须包含在Bucket Bucket 命名空间 1个用户最多10个 全局唯一 不能修改 容量最高2PB Server 虚拟存储空间 (用户) Access ID & Key 用户标示 API密钥 Bcuket 不可以修改所属可用区 三级域名 bucketname.endpoint 只有使用ECS实例用户 才能通过OSS内网地址访问,免流量 必须在同一区域 http://bucket名字.数据中心服务域名/object名字 私有 公共读 公共读写 不允许删除非空的bucket 没有任何碎片以及object 过期时间 自定义空间 批量删除最多1000个object 每个bucket可以绑定20个域名 当Object的Content-Type=application/octet-stream,采用OSS外网地址访问一个文件格式为jpg的Object ,默认直接下载 基于header中表头 referer 防盗链 白名单为空: -不会检查referer字段是否为空(不然所有的请求都会被拒绝) 白名单不为空: - 且设置了不允许referer字段为空的规则,则只有referer属于白名单的请求才允许,其他(包括referer为空)会被拒绝 - 设置了允许referer字段为空的故障,则referer为空的请求和符合白名单的请求会被允许;其他请求会被拒绝。 如果用浏览器浏览,需要设置允许 referer字段为空。 日志记录 用户自定义 源bucket 时间 OSS系统生成的字符串 图片服务 样式功能(将一系列的复杂的处理参数用简单的别名去代表) 规则 @ 样式@!别名(避免URL太长) 管道 | 多个处理动作一起操作 先关闭图片处理服务,再删除bucket Public-read-write Public-read 创建者可以写 Private 服务器端加密 防盗链 bucket权限控制 Acccess ID 和请求签名 OSS 本身不提供IP黑名单,但是可以通过CDN来间接使用IP黑白名单 弹性伸缩服务 免费 定时任务 20个 同一时间内的,会选取最近创建的定时任务执行 报警任务 名称唯一 必须指定ECS实例 支持RDS访问白名单 伸缩组 Scaling Group ECS实例的集合,最小值,最大值 权限最高 伸缩配置 Scaling Configuration ECS实例的规格 伸缩规则 Scaling Rule 扩展或收缩个数 伸缩活动 Scaling Activity 规则成功出发后,产生一个伸缩活动。(同一伸缩组内,同一时刻只能有一个伸缩活动在执行,无法终止互动) 伸缩触发任务 Scaling Trigger Task 用于触发伸缩规则的任务。 定时报警任务 冷却时间 Cooldown Period 伸缩活动完成后的 锁定时间 (只会拒绝云监控报警任务类型的伸缩活动请求,其他手工、定时可以绕过冷却时间)(最后一个成功后) 触发伸缩规则的任务独立于伸缩组存在,删除伸缩组不会删除任务 生效,失效,删除中 修改伸缩组属性时,地域 SLB RDS 不可以修改| 生效和失效 才可以修改 强制删除 1个伸缩桌10个伸缩规则,1个用户最多伸缩100个ECS 手工加入既有的ECS实例: 1,判断伸缩组的健康状态、边界条件和ECS实例的状态、类型。 2,分配ActivityId和执行伸缩活动。 3,加入ECS实例 4,修改Total Capacity。 5,添加RDS白名单 6,挂载SLB,将权重设为0。 7,等待60秒后,将权重设为50。 8,伸缩活动完成,启动cooldown。 虚拟专有网络 应用层 HTTP 传输层 TCP UDP 网络层 ICMP IP 路由选择 数据链路层 ARP RARP 不同VPC之间通过隧道ID进行隔离 VRouter VSwitch Route Table 1个 Route Entry 路由条目 Elastic IP Address 专线接入 每个专有网络最多容纳200个,可以工单申请。 CIDRBlock 创建成功后,不能修改网段 删除专有网络,需要先删除里面所有的东西 每个路由表最多只能创建48个自定义路由条目 一个专有网络最多只能创建24个交换机 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8 Server Load Balancer 负载均衡 高可用 低成本 安全 | 公网 私网免费 LoadBalancer 代表一个SLB实例 Listener 代表用户定制的负责均衡策略和转发规则 BackendServer是后端的一组云服务器 四层 TCP/UDP LVS 健康检查是 可以选择TCP HTTP 七层 HTTP/HTTPS Tengine 可以关闭健康检查 控制系统 用于配置和监控SLB 健康检查 会话保持 session 加权轮询WRR 加权最小连接数WLC 针对HTTPS,提供证书管理服务 使用流量 只收下行流量 (为公网出流量) 固定带宽 内网限流 1Gbps 1个SLB 最多支持50个服务监听配置 权重0-100, 0是不转发,设置后,长连接仍然存在。 实时生效 证书最多100个 每个用户最多30个SLB实例。1-65535 SLB 可以是不同Zone。 同一或不同地域,创建多个SLB, 通过DNS轮询的方式对外提供服务 不会限制SLB后面的ECS 可用性高达99.95% 安全结合云盾提供防 DDoS 攻击能力,包括 CC、SYN flood 等 DDoS 攻击方式。 负载均衡各监听连接超时时间如下: TCP 900秒 UDP 300秒 HTTP 60秒 HTTPS 60秒 Content Delivery Network 内容分发网络 将源站内容分发至全国所有的节点,缩短用户查看对象的延迟。 业务: 小文件加速 大文件加速 视频点播 视频直播 用户:快捷申请 个性化配置 报表 日志分析 OPEN API接口 防盗链支持 边缘节点 cache高速缓存 带宽峰值 流量 带宽利用率=实际使用流量GB/(带宽峰值Mbpsx10.54),1Mbps带宽每日100%利用率为10.54GB。 带宽计费:阶梯计费 智能DNS 根据客户的来源返回不同的IP地址 阿里云CDN:智能调度系统和Cacha软件 构成 | L1cache - BGP - L2cache - 源 IP 源站 OSS源站 缓存刷新 : URL刷新 目录刷新 URL预热 源站: 源站决定回源时,请求到哪个IP 回源host:回源host决定回源请求到该IP 上的哪个站点 WAF防护(WEB应用防护系统) CC防护(针对CC共计) 黑白名单 (IP) 同一时间内只能生效一种。 URL鉴权 3种方式 4层防御体系结构:网络层 主机层 应用层 数据层 安全体系: 云盾 云服务 云安全运维 安全管家:防DDOS服务、端口安全检查、异地登陆提醒、主机密码暴力破解防御、网站后门检测 安全体检:WEB漏洞检测 网页挂马检测 DDOS: DNS query Flooad 、 NTP reply Flood 清洗阈值: 自动 手动 云盾技术防护不支持防护CC攻击 安骑士: 主机密码防爆破 异地登陆报警 网站后门检测 高危漏洞修复 木马文件查杀 数据库防护: 白名单限制访问源IP 内网访问模式 防暴力破解 SQL注入防护 SQL审计 应用防火墙: 跨站攻击 CRLF攻击 SQL注入攻击 FastCGI攻击 WEBSHELL攻击 Cloud Monitor System 云监控 开放性 网络优势 开放平台支持 站点监控 云产品监控 自定义监控 报警及联系人管理 监控项目: HTTP: http.response Time & http.status 监控点:监控项的一个实例 维度: 定位监控项数据位置的维度, 目前维度用“字段信息表示” 规则: 条件 报警组 报警方式 状态码 响应时间 本文转自 295631788 51CTO博客,原文链接:http://blog.51cto.com/hequan/1974241,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day43)——构造函数继承

Swift中的子类构造函数的来源有两种:自己编写和从父类继承。并不是父类的所有的构造函数都能继承下来,能够从父类继承下来的构造函数是有条件的,如下所示。 条件1:如果子类没有定义任何指定构造函数,它将自动继承所有父类的指定构造函数。 条件2:如果子类提供了所有父类指定构造函数的实现,无论是通过条件1继承过来的,还是通过自己编写实现的,它都将自动继承所有父类的便利构造函数。 下面看示例代码: classPerson{ varname:String varage:Int funcdescription()->String{ return"\(name)年龄是:\(age)" } convenienceinit(){ self.init(name:"Tony") self.age=18 } convenienceinit(name:String){ self.init(name:name,age:18) } init(name:String,age:Int){ self.name=name self.age=age } } classStudent:Person{ varschool:String init(name:String,age:Int,school:String){ self.school=school super.init(name:name,age:age) } convenienceoverrideinit(name:String,age:Int){ self.init(name:name,age:age,school:"清华大学") } } classGraduate:Student{ varspecial:String="" } 来看看符合条件1的继承,Graduate继承Student,Graduate类没有定义任何指定构造函数,它将自动继承所有Student的指定构造函数。符合条件1后,Graduate从Student继承了如下指定构造函数: init(name : String,age : Int,school : String) 再看符合条件2的继承,由于Graduate实现了Student的所有指定构造函数,Graduate将自动继承所有Student的便利构造函数。符合条件2后,Graduate从Student继承了如下3个便利构造函数: init(name:String,age:Int) init(name:String) init() Student继承Person后有4个构造函数。 条件1对Student不满足,因为它有指定构造函数,Student类中的便利构造函数init (name: String, age: Int)满足了条件2,它实现了父类指定构造函数init (name: String, age: Int)。另外,由于子类构造函数与父类构造函数参数相同,需要使用override关键字,表示子类构造函数重写(overriding)了父类构造函数。 由于Student类实现了父类指定构造函数,因此也继承了父类的另外两个便利构造函数。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1747499,如需转载请自行联系原作者

优秀的个人博客,低调大师

[Android学习笔记十]Adapter如何进行视图与数据绑定资料

Android开发中视图和数据的绑定离不开Adapt系列的类,在呈现给用户的界面友好美观和内容丰富的应用中视图为骨,内容为肉,Adapter则是骨肉相连的筋。 下图是Android类库中的Adapter类层次图: 在android support库以及更多的第三方库中存在大量的Adapter类,Adapter在视图和数据绑定中起着至关重要的桥接作用。 本文转自 secondriver 51CTO博客,原文链接:http://blog.51cto.com/aiilive/1721188,如需转载请自行联系原作者

优秀的个人博客,低调大师

[BigData]关于Hadoop学习笔记第二天(PPT总结)(一)

Plan: 分布式文件系统与HDFS HDFS体系结构与基本概念 HDFS的shell操作 java接口及常用api HADOOP的RPC机制 HDFS源码分析 远程debug 自己设计一分布式文件系统? Distributed File System 1.数据量越来越多,在一个操作系统管辖的范围存不下了,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,因此迫切需要一种系统来管理多台机器上的文件,这就是分布式文件管理系统 。 2.是一种允许文件通过网络在多台主机上分享的文件系统,可让多机器上的多用户分享文件和存储空间。 3.通透性。让实际上是通过网络来访问文件的动作,由程序与用户看来,就像是访问本地的磁盘一般。 4.容错。即使系统中有某些节点脱机,整体来说系统仍然可以持续运作而不会有数据损失。 5.分布式文件管理系统很多,hdfs只是其中一种。适用于一次写入多次查询的情况,不支持并发写情况,小文件不合适。 HDFS的Shell 1.调用文件系统(FS)Shell命令应使用 bin/hadoop fs 的形式。 2.所有的FS shell命令使用URI路径作为参数。 URI格式是scheme://authority/path。HDFS的scheme是hdfs,对本地文件系统,scheme是file。其中scheme和authority参数都是可选的,如果未加指定,就会使用配置中指定的默认scheme。 例如:/parent/child可以表示成hdfs://namenode:namenodePort/parent/child,或者更简单的/parent/child(假设配置文件是namenode:namenodePort) 3.大多数FS Shell命令的行为和对应的Unix Shell命令类似。 HDFS fs命令 -help [cmd] //显示命令的帮助信息 -ls(r) <path> //显示当前目录下所有文件 -du(s) <path> //显示目录中所有文件大小 -count[-q] <path> //显示目录中文件数量 -mv <src> <dst> //移动多个文件到目标目录 -cp <src> <dst> //复制多个文件到目标目录 -rm(r) //删除文件(夹) -put <localsrc> <dst> //本地文件复制到hdfs -copyFromLocal //同put -moveFromLocal //从本地文件移动到hdfs -get [-ignoreCrc] <src> <localdst> //复制文件到本地,可以忽略crc校验 -getmerge <src> <localdst> //将源目录中的所有文件排序合并到一个文件中 -cat <src> //在终端显示文件内容 -text <src> //在终端显示文件内容 -copyToLocal [-ignoreCrc] <src> <localdst> //复制到本地 -moveToLocal <src> <localdst> -mkdir <path> //创建文件夹 -touchz <path> //创建一个空文件 HDFS的Shell命令练习 #hadoop fs -ls / 查看HDFS根目录 #hadoop fs -mkdir /test 在根目录创建一个目录test #hadoop fs -mkdir /test1 在根目录创建一个目录test1 #hadoop fs -put ./test.txt /test 或#hadoop fs -copyFromLocal ./test.txt /test #hadoop fs -get /test/test.txt . 或#hadoop fs -getToLocal /test/test.txt . #hadoop fs -cp /test/test.txt /test1 #hadoop fs -rm /test1/test.txt #hadoop fs -mv /test/test.txt /test1 #hadoop fs -rmr /test1 HDFS架构 NameNode DataNode Secondary NameNode HDFS Architecture 元数据存储细节 NameNode 1.是整个文件系统的管理节点。它维护着整个文件系统的文件目录树,文件/目录的元信息和每个文件对应的数据块列表。接收用户的操作请求。 2.文件包括: ①fsimage:元数据镜像文件。存储某一时段NameNode内存元数据信息。(hdfs-site.xml的dfs.name.dir属性 ) ②edits:操作日志文件。 ③fstime:保存最近一次checkpoint的时间 3.以上这些文件是保存在linux的文件系统中。 NameNode的工作特点 1.Namenode始终在内存中保存metedata,用于处理“读请求” 2.到有“写请求”到来时,namenode会首先写editlog到磁盘,即向edits文件中写日志,成功返回后,才会修改内存,并且向客户端返回 3.Hadoop会维护一个fsimage文件,也就是namenode中metedata的镜像,但是fsimage不会随时与namenode内存中的metedata保持一致,而是每隔一段时间通过合并edits文件来更新内容。Secondary namenode就是用来合并fsimage和edits文件来更新NameNode的metedata的。 SecondaryNameNode 1.HA的一个解决方案。但不支持热备。配置即可。 2.执行过程:从NameNode上下载元数据信息(fsimage,edits),然后把二者合并,生成新的fsimage,在本地保存,并将其推送到NameNode,替换旧的fsimage. 3.默认在安装在NameNode节点上,但这样...不安全! secondary namenode的工作流程 1.secondary通知namenode切换edits文件 2.secondary从namenode获得fsimage和edits(通过http) 3.secondary将fsimage载入内存,然后开始合并edits 4.secondary将新的fsimage发回给namenode 5.namenode用新的fsimage替换旧的fsimage 什么时候checkpiont 1.fs.checkpoint.period 指定两次checkpoint的最大时间间隔,默认3600秒。 2.fs.checkpoint.size 规定edits文件的最大值,一旦超过这个值则强制checkpoint,不管是否到达最大时间间隔。默认大小是64M。 Datanode 1.提供真实文件数据的存储服务。 2.文件块(block):最基本的存储单位。对于文件内容而言,一个文件的长度大小是size,那么从文件的0偏移开始,按照固定的大小,顺序对文件进行划分并编号,划分好的每一个块称一个Block。HDFS默认Block大小是128MB,以一个256MB文件,共有256/128=2个Block. dfs.block.size 3.不同于普通文件系统的是,HDFS中,如果一个文件小于一个数据块的大小,并不占用整个数据块存储空间 4.Replication。多复本。默认是三个。 hdfs-site.xml的dfs.replication属性 Shell命令练习:验证块大小 1.方法:上传大于128MB的文件,观察块大小 2.验证:使用 http://hadoop0:50070 观察 HDFS的java访问接口——FileSystem •写文件 create •读取文件 open •删除文件delete • • •创建目录 mkdirs •删除文件或目录 delete •列出目录的内容 listStatus •显示文件系统的目录和文件的元数据信息 getFileStatus HDFS的FileSystem读取文件 private static FileSystem getFileSystem() throws URISyntaxException, IOException { Configuration conf = new Configuration(); URI uri = new URI("hdfs://hadoop240:9000"); final FileSystem fileSystem = FileSystem.get(uri , conf); return fileSystem; } /** * 读取文件,调用fileSystem的open(path) * @throws Exception */ private static void readFile() throws Exception { FileSystem fileSystem = getFileSystem(); FSDataInputStream openStream = fileSystem.open(new Path("hdfs://itcast0106:9000/aaa")); IOUtils.copyBytes(openStream, System.out, 1024, false); IOUtils.closeStream(openStream); } HDFS的FileSystem目录 /** * 创建目录,调用fileSystem的mkdirs(path) * @throws Exception */ private static void mkdir() throws Exception { FileSystem fileSystem = getFileSystem(); fileSystem.mkdirs(new Path("hdfs://itcast0106:9000/bbb")); } /** * 删除目录,调用fileSystem的deleteOnExit(path) * @throws Exception */ private static void rmdir() throws Exception { FileSystem fileSystem = getFileSystem(); fileSystem.delete(new Path("hdfs://itcast0106:9000/bbb")); } HDFS的FileSystem遍历目录 /** * 遍历目录,使用FileSystem的listStatus(path) * 如果要查看file状态,使用FileStatus对象 * @throws Exception */ private static void list() throws Exception{ FileSystem fileSystem = getFileSystem(); FileStatus[] listStatus = fileSystem.listStatus(new Path("hdfs://itcast0106:9000/")); for (FileStatus fileStatus : listStatus) { String isDir = fileStatus.isDir()?"目录":"文件"; String name = fileStatus.getPath().toString(); System.out.println(isDir+" "+name); } } FileSystem 用户代码操作HDFS时,是直接调用FileSystem的子类完成的。 Remote Procedure Call 1.RPC——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。RPC协议假定某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。 2.RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服务器。首先,客户机调用进程发送一个有进程参数的调用信息到服务进程,然后等待应答信息。在服务器端,进程保持睡眠状态直到调用信息的到达为止。当一个调用信息到达,服务器获得进程参数,计算结果,发送答复信息,然后等待下一个调用信息,最后,客户端调用进程接收答复信息,获得进程结果,然后调用执行继续进行。 3.hadoop的整个体系结构就是构建在RPC之上的(见org.apache.hadoop.ipc)。 RPC示例 public interface Bizable extends VersionedProtocol{ public abstract String hello(String name); } class Biz implements Bizable{ @Override public String hello(String name){ System.out.println("被调用了"); return "hello "+name; } @Override public long getProtocolVersion(String protocol, long clientVersion) throws IOException { System.out.println("Biz.getProtocalVersion()="+MyServer.VERSION); return MyServer.VERSION; } } public class MyServer { public static int PORT = 3242; public static long VERSION = 23234l; public static void main(String[] args) throws IOException { final Server server = RPC.getServer(new Biz(), "127.0.0.1", PORT, new Configuration()); server.start(); } } public class MyClient { public static void main(String[] args) throws IOException { final InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", MyServer.PORT); final Bizable proxy = (Bizable) RPC.getProxy(Bizable.class, MyServer.VERSION, inetSocketAddress, new Configuration()); final String ret = proxy.hello("吴超"); System.out.println(ret); RPC.stopProxy(proxy); } } RPC调用流程 ClientProtocol l是客户端(FileSystem)与NameNode通信的接口。 DatanodeProtocol l是DataNode与NameNode通信的接口 NamenodeProtocol l是SecondaryNameNode与NameNode通信的接口。 HDFS读过程 1.初始化FileSystem,然后客户端(client)用FileSystem的open()函数打开文件 2.FileSystem用RPC调用元数据节点,得到文件的数据块信息,对于每一个数据块,元数据节点返回保存数据块的数据节点的地址。 3.FileSystem返回FSDataInputStream给客户端,用来读取数据,客户端调用stream的read()函数开始读取数据。 4.DFSInputStream连接保存此文件第一个数据块的最近的数据节点,data从数据节点读到客户端(client) 5.当此数据块读取完毕时,DFSInputStream关闭和此数据节点的连接,然后连接此文件下一个数据块的最近的数据节点。 6.当客户端读取完毕数据的时候,调用FSDataInputStream的close函数。 7.在读取数据的过程中,如果客户端在与数据节点通信出现错误,则尝试连接包含此数据块的下一个数据节点。 8.失败的数据节点将被记录,以后不再连接。 HDFS写过程 1.初始化FileSystem,客户端调用create()来创建文件 2.FileSystem用RPC调用元数据节点,在文件系统的命名空间中创建一个新的文件,元数据节点首先确定文件原来不存在,并且客户端有创建文件的权限,然后创建新文件。 3.FileSystem返回DFSOutputStream,客户端用于写数据,客户端开始写入数据。 4.DFSOutputStream将数据分成块,写入data queue。data queue由Data Streamer读取,并通知元数据节点分配数据节点,用来存储数据块(每块默认复制3块)。分配的数据节点放在一个pipeline里。Data Streamer将数据块写入pipeline中的第一个数据节点。第一个数据节点将数据块发送给第二个数据节点。第二个数据节点将数据发送给第三个数据节点。 5.DFSOutputStream为发出去的数据块保存了ack queue,等待pipeline中的数据节点告知数据已经写入成功。 6.当客户端结束写入数据,则调用stream的close函数。此操作将所有的数据块写入pipeline中的数据节点,并等待ack queue返回成功。最后通知元数据节点写入完毕。 7.如果数据节点在写入的过程中失败,关闭pipeline,将ack queue中的数据块放入data queue的开始,当前的数据块在已经写入的数据节点中被元数据节点赋予新的标示,则错误节点重启后能够察觉其数据块是过时的,会被删除。失败的数据节点从pipeline中移除,另外的数据块则写入pipeline中的另外两个数据节点。元数据节点则被通知此数据块是复制块数不足,将来会再创建第三份备份。 练习题 1.练习shell命令 2.在HDFS创建一个文本文件hadoop.test。内容自定;然后,用Java程序在本地终端打印hadoop.test文件内容 3.用Java程序实现copyFromLocal 思考题 1.hdfs的组成部分有哪些,分别解释一下 2.hdfs的高可靠如何实现 3.hdfs的常用shell命令有哪些 4.hdfs的常用java api有哪些 5.请用shell命令实现目录、文件的增删改查 6.请用java api实现目录、文件的增删改查 本文转自SummerChill博客园博客,原文链接:http://www.cnblogs.com/DreamDrive/p/4566838.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:代码规范(新浪微博sdk示例工程附带的说明)

规范: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 /* *文件名(可选),如CodingRuler.java * *版本信息(可选),如:@version1.0.0 * *版权申明(开源代码一般都需要添加),如:Copyright(C)2010-2013SINACorporation. */ packagecom.sina.weibo.sdk.codestyle; /** *类的大体描述放在这里。 * *<p> *<b>NOTE:以下部分为一个简要的编码规范,更多规范请参考ORACLE官方文档。</b><br> *地址:http://www.oracle.com/technetwork/java/codeconventions-150003.pdf<br> *另外,请使用UTF-8格式来查看代码,避免出现中文乱码。<br> *<b>至于注释应该使用中文还是英文,请自己行决定,根据公司或项目的要求而定,推荐使用英文。</b><br> *</p> *<h3>1.整理代码</h3> *<ul> *<li>1.1.Java代码中不允许出现在警告,无法消除的警告要用@SuppressWarnings。 *<li>1.2.去掉无用的包、方法、变量等,减少僵尸代码。 *<li>1.3.使用Lint工具来查看并消除警告和错误。 *<li>1.4.使用Ctrl+Shift+F来格式化代码,然后再进行调整。 *<li>1.5.使用Ctrl+Shift+O来格式化Import包。 *</ul> * *<h3>2.命名规则</h3> *<h3>2.1.基本原则</h3> *<ul> *<li>2.1.1.变量,方法,类命名要表义,严格禁止使用name1,name2等命名。 *<li>2.1.2.命名不能太长,适当使用简写或缩写。(最好不要超过25个字母) *<li>2.1.3.方法名以小写字母开始,以后每个单词首字母大写。 *<li>2.1.4.避免使用相似或者仅在大小写上有区别的名字。 *<li>2.1.5.避免使用数字,但可用2代替to,用4代替for等,如go2Clean。 *</ul> * *<h3>2.2.类、接口</h3> *<ul> *<li>2.2.1.所有单词首字母都大写。使用能确切反应该类、接口含义、功能等的词。一般采用名词。 *<li>2.2.2.接口带I前缀,或able,ible,er等后缀。如ISeriable。 *</ul> * *<h3>2.3.字段、常量</h3> *<ul> *<li>2.3.1.成员变量以m开头,静态变量以s开头,如mUserName,sInstance。 *<li>2.3.2.常量全部大写,在词与词之前用下划线连接,如MAX_NUMBER。 *<li>2.3.3.代码中禁止使用硬编码,把一些数字或字符串定义成常用量。 *<li>2.3.4.对于废弃不用的函数,为了保持兼容性,通常添加@Deprecated,如{@link#doSomething()} *</ul> * *<h3>3.注释</h3> *请参考{@link#SampleCode}类的注释。 *<ul> *<li>3.1.常量注释,参见{@link#ACTION_MAIN} *<li>3.2.变量注释,参见{@link#mObject0} *<li>3.3.函数注释,参见{@link#doSomething(int,float,String)} *</ul> * *<h3>4.Class内部顺序和逻辑</h3> *<ul> *<li>4.1.每个class都应该按照一定的逻辑结构来排列基成员变量、方法、内部类等, *从而达到良好的可读性。 *<li>4.2.总体上来说,要按照先public,后protected,最后private,函数的排布 *也应该有一个逻辑的先后顺序,由重到轻。 *<li>4.3.以下顺序可供参考:<br> *定义TAG,一般为private(可选)<br> *定义public常量<br> *定义protected常量、内部类<br> *定义private变量<br> *定义public方法<br> *定义protected方法<br> *定义private方法<br> *</ul> * *<h3>5.表达式与语句</h3> *<h3>5.1.基本原则:采用紧凑型风格来编写代码</h3> *<h3>5.2.细则</h3> *<ul> *<li>5.2.1.条件表示式,参见{@link#conditionFun(boolean)} *<li>5.2.2.switch语句,参见{@link#switchFun(int)} *<li>5.2.3.循环语句,参见{@link#circulationFun(boolean)} *<li>5.2.4.错误与异常,参见{@link#exceptionFun()} *<li>5.2.5.杂项,参见{@link#otherFun()} *<li>5.2.6.批注,参见{@link#doSomething(int,float,String)} *</ul> * *@author作者名 *@since2013-XX-XX */ @SuppressWarnings("unused") publicclassCodingRuler{ /**公有的常量注释*/ publicstaticfinalStringACTION_MAIN="android.intent.action.MAIN"; /**私有的常量注释(同类型的常量可以分块并紧凑定义)*/ privatestaticfinalintMSG_AUTH_NONE=0; privatestaticfinalintMSG_AUTH_SUCCESS=1; privatestaticfinalintMSG_AUTH_FAILED=2; /**保护的成员变量注释*/ protectedObjectmObject0; /**私有的成员变量mObject1注释(同类型的成员变量可以分块并紧凑定义)*/ privateObjectmObject1; /**私有的成员变量mObject2注释*/ privateObjectmObject2; /**私有的成员变量mObject3注释*/ privateObjectmObject3; /** *对于注释多于一行的,采用这种方式来 *定义该变量 */ privateObjectmObject4; /** *公有方法描述... * *@paramparam1参数1描述... *@paramparam2参数2描述... *@paramparamXX参数XX描述...(注意:请将参数、描述都对齐) */ publicvoiddoSomething(intparam1,floatparam2,StringparamXX){ //以***释标签可以通过Eclipse内置的Task插件看到 //TODO使用TODO来标记代码,说明标识处有功能代码待编写 //FIXME使用FIXME来标记代码,说明标识处代码需要修正,甚至代码是 //错误的,不能工作,需要修复 //XXX使用XXX来标记代码,说明标识处代码虽然实现了功能,但是实现 //的方法有待商榷,希望将来能改进 } /** *保护方法描述... */ @Deprecated protectedvoiddoSomething(){ //...implementation } /** *私有方法描述... * *@paramparam1参数1描述... *@paramparam2参数2描述... */ privatevoiddoSomethingInternal(intparam1,floatparam2){ //...implementation } /** *条件表达式原则。 */ privatevoidconditionFun(){ booleancondition1=true; booleancondition2=false; booleancondition3=false; booleancondition4=false; booleancondition5=false; booleancondition6=false; //原则:1.所有if语句必须用{}包括起来,即便只有一句,禁止使用不带{}的语句 //2.在含有多种运算符的表达式中,使用圆括号来避免运算符优先级问题 //3.判断条件很多时,请将其它条件换行 if(condition1){ //...implementation } if(condition1){ //...implementation }else{ //...implementation } if(condition1)/*禁止使用不带{}的语句*/ condition3=true; if((condition1==condition2) ||(condition3==condition4) ||(condition5==condition6)){ } } /** *Switch语句原则。 */ privatevoidswitchFun(){ //原则:1.switch语句中,break与下一条case之间,空一行 //2.对于不需要break语句的,请使用/*Fallsthrough*/来标注 //3.请默认写上default语句,保持完整性 intcode=MSG_AUTH_SUCCESS; switch(code){ caseMSG_AUTH_SUCCESS: break; caseMSG_AUTH_FAILED: break; caseMSG_AUTH_NONE: /*Fallsthrough*/ default: break; } } /** *循环表达式。 */ privatevoidcirculationFun(){ //原则:1.尽量使用foreach语句代替原始的for语句 //2.循环中必须有终止循环的条件或语句,避免死循环 //3.循环要尽可能的短,把长循环的内容抽取到方法中去 //4.嵌套层数不应超过3层,要让循环清晰可读 intarray[]={1,2,3,4,5}; for(intdata:array){ //...implementation } intlength=array.length; for(intix=0;ix<length;ix++){ //...implementation } booleancondition=true; while(condition){ //...implementation } do{ //...implementation }while(condition); } /** *异常捕获原则。 */ privatevoidexceptionFun(){ //原则:1.捕捉异常是为了处理它,通常在异常catch块中输出异常信息。 //2.资源释放的工作,可以放到finally块部分去做。如关闭Cursor等。 try{ //...implementation }catch(Exceptione){ e.printStackTrace(); }finally{ } } /** *其它原则(整理中...)。 */ private void otherFun(){ //TODO } } 简单说明: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 /* *Copyright(C)2010-2013TheSINAWEIBOOpenSourceProject * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packagecom.sina.weibo.sdk.codestyle; /** *类的大体描述放在这里。 * *@author作者名 *@since2013-XX-XX */ @SuppressWarnings("unused") publicclassSampleCode{ /**公有的常量注释*/ publicstaticfinalStringACTION_MAIN="android.intent.action.MAIN"; /**私有的常量注释(同类型的常量可以分块并紧凑定义)*/ privatestaticfinalintMSG_AUTH_NONE=0; privatestaticfinalintMSG_AUTH_SUCCESS=1; privatestaticfinalintMSG_AUTH_FAILED=2; /**保护的成员变量注释*/ protectedObjectmObject0; /**私有的成员变量mObject1注释(同类型的成员变量可以分块并紧凑定义)*/ privateObjectmObject1; /**私有的成员变量mObject2注释*/ privateObjectmObject2; /**私有的成员变量mObject3注释*/ privateObjectmObject3; /** *对于注释多于一行的,采用这种方式来 *定义该变量 */ privateObjectmObject4; /** *公有方法描述... * *@paramparam1参数1描述... *@paramparam2参数2描述... *@paramparamXX参数XX描述...(注意:请将参数、描述都对齐) */ publicvoiddoSomething(intparam1,floatparam2,StringparamXX){ //...implementation } /** *保护方法描述... */ protectedvoiddoSomething(){ //...implementation } /** *私有方法描述... * *@paramparam1参数1描述... *@paramparam2参数2描述... */ private void doSomethingInternal( int param1, float param2){ //...implementation } } 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1677101,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 35)——会使用下标吗?

看下面的示例代码是不是使用过: 1 <span style= "font-size:14px;" >var studentList:String[] = [ "张三" , "李四" , "王五" ]<br>studentList[ 0 ] = "诸葛亮" <br><br>var studentDictionary =[ 102 : "张三" , 105 : "李四" , 109 : "王五" ]<br>studentDictionary[ 110 ] = "董六" </span> 在访问数组和字典的时候,可以采用下标访问。其中数组的下标是整数类型索引,字典的下标是它的“键”。 下标 Swift中的下标相当于Java中的索引属性和C#中的索引器。 下标访问的语法格式如下: 1 <span style= "font-size:14px;" >面向对象类型类型名 { <br> 其他属性<br> ...<br> subscript(参数: 参数数据类型) -> 返回值数据类型 { <br> get{ <br> return 返回值<br> } <br><br> set(新属性值) {<br> ...<br> } <br> } <br>}</span> 下标也有类似于计算属性的getter和setter访问器。 getter访问器是一个方法,在最后使用return语句将计算结果返回。 setter访问器“新属性值”是要赋值给属性值。参数的声明可以省略,系统会分配一个默认的参数newValue。 示例:二维数组 在Swift中没有提供二维数组,只有一维数组Array。可以自定义一个二维数组类型,然后通过两个下标参数访问它的元素,形式上类似于C语言的二维数组。 采用下标的二维数组示例代码如下: 1 <span style= "font-size:14px;" >structDoubleDimensionalArray { //定义了二维数组结构体<br> <br> let rows: Int, columns: Int //存储属性rows和columns<br> var grid: [Int]<br> <br> init(rows: Int, columns: Int) { //构造函数<br> self.rows = rows<br> self.columns = columns<br> grid = Array(count: rows * columns,repeatedValue: 0) //初始化存储属性grid<br> }<br> <br> subscript(row: Int, col: Int) -> Int { //定义下标<br> <br> get {<br> return grid[(row * columns) + col] <br> }<br> <br> set (newValue1){<br> grid[(row * columns) + col] =newValue1 <br> }<br> }<br> <br>}<br><br>var ary2 =DoubleDimensionalArray(rows: 10, columns: 10)//创建并初始化10×10大小的二维数组<br><br>//初始化二维数组<br>for var i = 0; i < 10;i++ {<br> for var j = 0; j < 10; j++ {<br> ary2[i,j] = i * j <br><br> }<br>}<br><br>//打印输出二维数组<br>for var i = 0; i < 10;i++ {<br> for var j = 0; j < 10; j++ {<br> print("\t \(ary2[i,j])")<br> }<br> print("\n")<br>}<br></span> 输出结果如下: 0 000000000 0123456789 024681012141618 0369121518212427 04812162024283236 051015202530354045 061218243036424854 071421283542495663 081624324048566472 091827364554637281 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1746615,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 33)——属性观察者

为了监听属性的变化,Swift提供了属性观察者。属性观察者能够监听存储属性的变化,即便变化前后的值相同,它们也能监听到。 属性观察者主要有以下两个: willSet:观察者在修改之前调用。 didSet:观察者在修改之后立刻调用。 属性观察者的语法格式如下: 面向对象类型类型名{ 1 2 3 4 5 6 7 8 9 10 ... var存储属性:属性数据类型=初始化值{ willSet(新值){ //定义willSet观察者。“新值”是传递给willSet观察者的参数,它保存了将要替换原来属性的新值 ... } didSet(旧值){ //定义didSet观察者。“旧值”是传递给didSet观察者的参数,它保存了被新属性替换的旧值。 ... } } } 属性观察者的语法格式比计算属性要混乱。 属性观察者可以在类和结构体中使用,不能在枚举中使用。 示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Employee{ varno:Int= 0 varname:String= "Tony" { willSet(newNameValue){ //定义name属性的willSet观察者,newNameValue是由我们分配的传递新值的参数名 print( "员工name新值:\(newNameValue)" ) } didSet(oldNameValue){ //定义name属性的didSet观察者,oldNameValue是由我们分配的传递旧值的参数名 print( "员工name旧值:\(oldNameValue)" ) } } varjob:String? varsalary:Double= 0 vardept:Department? } structDepartment{ varno:Int= 10 { willSet{ //定义no属性的willSet观察者,注意这里没有声明参数,但是我们可以在观察者内部使用newValue print( "部门编号新值:\(newValue)" ) } didSet{ //定义no属性的didSet观察者,注意这里也没有声明参数,但是我们可以在观察者内部使用oldValue print( "部门编号旧值:\(oldValue)" ) } } varname:String= "RESEARCH" } varemp=Employee() emp.no= 100 emp.name= "Smith" vardept=Department() dept.no= 30 上述代码运行结果如下: 员工name新值:Smith 员工name旧值:Tony 部门编号新值:30 部门编号旧值:10 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1746600,如需转载请自行联系原作者

优秀的个人博客,低调大师

《从零开始学Swift》学习笔记(Day 42)——构造函数调用规则

在构造函数中可以使用构造函数代理帮助完成部分构造工作。类构造函数代理分为横向代理和向上代理,横向代理只能在发生在同一类内部,这种构造函数称为便利构造函数。向上代理发生在继承的情况下,在子类构造过程中,要先调用父类构造函数初始化父类的存储属性,这种构造函数称为指定构造函数。 构造函数调用规则 Person和Student类示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Person{ varname:String varage:Int funcdescription()->String{ return "\(name)年龄是:\(age)" } convenienceinit(){ //便利构造函数 self.init(name: "Tony" ) self.age= 18 } convenienceinit(name:String){ //便利构造函数 self.init(name:name,age: 18 ) } init(name:String,age:Int){ //指定构造函数 self.name=name self.age=age } } class Student:Person{ varschool:String init(name:String,age:Int,school:String){ //指定构造函数 self.school=school super .init(name:name,age:age) } convenienceoverrideinit(name:String,age:Int){ //便利构造函数 self.init(name:name,age:age,school: "清华大学" ) } } letstudent=Student() print( "学生:\(student.description())" ) 构造函数之间的调用形成了构造函数链,如图所示。 Swift限制构造函数之间的代理调用的规则有3条,如下所示。 指定构造函数必须调用其直接父类的的指定构造函数。从图可见,Student中的④号指定构造函数调用Person中的③号指定构造函数。 便利构造函数必须调用同一类中定义的其他构造函数。从图可见,Student中的⑤号便利构造函数调用同一类中的④号便利构造函数,Person中的①号便利构造函数调用同一类中的②号便利构造函数。 便利构造函数必须最终以调用一个指定构造函数结束。从图可见,Student中的⑤号便利构造函数调用同一类中的④号指定构造函数,Person中的②号便利构造函数调用同一类中的③号指定构造函数。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1747498,如需转载请自行联系原作者

优秀的个人博客,低调大师

学习笔记TF066:TensorFlow移动端应用,iOS、Android系统实践

TensorFlow对Android、iOS、树莓派都提供移动端支持。 移动端应用原理。移动端、嵌入式设备应用深度学习方式,一模型运行在云端服务器,向服务器发送请求,接收服务器响应;二在本地运行模型,PC训练模型,放到移动端预测。向服务端请求数据可行性差,移动端资源稀缺。本地运行实时性更好。加速计算,内存空间和速度优化。精简模型,节省内存空间,加快计算速度。加快框架执行速度,优化模型复杂度和每步计算速度。精简模型,用更低权得精度,量化(quantization)、权重剪枝(weight pruning,剪小权重连接,把所有权值连接低于阈值的从网络移除)。加速框架执行,优化矩阵通用乘法(GEMM)运算,影响卷积层(先数据im2col运行,再GEMM运算)和全连接层。im2col,索引图像块重排列为矩阵列。先将大矩阵重叠划分多个子矩阵,每个子矩阵序列化成向量,得到另一个矩阵。 量化(quantitative)。《How to Quantize Neural Networks with TensorFlow》https://www.tensorflow.org/performance/quantization 。离散化。用比32位浮点数更少空间存储、运行模型,TensorFlow量化实现屏蔽存储、运行细节。神经网络预测,浮点影响速度,量化加快速度,保持较高精度。减小模型文件大小。存储模型用8位整数,加载模型运算转换回32位浮点数。降低预测过程计算资源。神经网络噪声健壮笥强,量化精度损失不会危害整体准确度。训练,反向传播需要计算梯度,不能用低精度格式直接训练。PC训练浮点数模型,转8位,移动端用8位模型预测。量化示例。GoogleNet模型转8位模型例子。下载训练好GoogleNet模型,http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz 。 bazel build tensorflow/tools/quantization:quantization_graph bazel-bin/tensorflow/tools/quantization/quantization_graph \ --input=/tmp/classify_image_graph_def.pb \ --output_node_names="softmax" --output=/tmp/quantized_graph.pb \ --mode=eightbit 生成量化后模型大小只有原来的1/4。执行: bazel build tensorflow/examples/label_image:label_image bazel-bin/tensorflow/examples/label_image/label_image \ --image=/tmp/cropped_panda.jpg \ --graph=/tmp/quantized_graph.pb \ --labels=/tmp/imagenet_synset_to_human_label_map.txt \ --input_width=299 \ --input_height=299 \ --input_mean=128 \ --input_std=128 \ --input_layer="Mul:0" \ --output_layer="softmax:0" 量化过程实现。预测操作转换成等价8位版本操作实现。原始Relu操作,输入、输出浮点数。量化Relu操作,根据输入浮点数计算最大值、最小值,进入量化(Quantize)操作输入数据转换8位。保证输出层输入数据准确性,需要反量化(Dequantize)操作,权重转回32位精度,保证预测准确性。整个模型前向传播用8位整数支行,最后一层加反量化层,8位转回32位输出层输入。每个量化操作后执行反量化操作。 量化数据表示。浮点数转8位表示,是压缩问题。权重、经过激活函数处理上层输出,是分布在一个范围内的值。量化过程,找出最大值、最小值,将浮点数线性分布,做线性扩展。 优化矩阵乘法运算。谷歌开源小型独立低精度通用矩阵乘法(General Matrix to Matrix Multiplication,GEMM)库 gemmlowp。https://github.com/google/gemmlowp 。 iOS系统实践。 环境准备。操作系统Mac OS X,集成开发工具Xcode 7.3以上版本。编译TensorFlow核心静态库。tensorflow/contrib/makefiles/download_depencies.sh 。依赖库下载到tensorflow/contrib/makefile/downloads目录。eigen #C++开源矩阵计算工具。gemmlowp #小型独立低精度通用矩阵乘法(GEMM)库。googletest #谷歌开源C++测试框架。protobuf #谷歌开源数据交换格式协议。re2 #谷歌开源正则表达式库。 编译演示程度,运行。tensorflow/contrib/makefile/build_all_iso.sh。编译生成静态库,tensorflow/contrib/makefile/gen/lib:ios_ARM64、ios_ARMV7、ios_ARMV7S、ios_I386、ios_X86_64、libtensorflow-core.a。Xcode模拟器或iOS设备运行APP预测示例。TensorFlow iOS示例。https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/ios/ 。3个目录。benchmark目录是预测基准示例。simple目录是图片预测示例。camera目录是视频流实时预测示例。下载Inception V1模型,能识别1000类图片,https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip 。解压模型,复制到benchmark、simple、camera的data目录。运行目录下xcodeproj文件。选择iPhone 7 Plus模拟器,点击运行标志,编译完成点击Run Model按钮。预测结果见Xcode 控制台。 自定义模型编译、运行。https://github.com/tensorflow/tensorflow/blob/15b1cf025da5c6ac2bcf4d4878ee222fca3aec4a/tensorflow/docs_src/tutorials/image_retraining.md 。下载花卉数据 http://download.tensorflow.org/example_images/flower_photos.tgz 。郁金香(tulips)、玫瑰(roses)、浦公英(dandelion)、向日葵(sunflowers)、雏菊(daisy)5种花卉文件目录,各800张图片。训练原始模型。下载预训练Inception V3模型 http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz 。 python tensorflow/examples/image_retraining/retrain.py \ --bottlenectk_dir=/tmp/bottlenecks/ \ --how_many_training_steps 10 \ --model_dir=/tmp/inception \ --output_graph=/tmp/retrained_graph.pb \ --output_labels=/tmp/retrained_labels.txt \ --image_dir /tmp/flower_photos 训练完成,/tmp目录有模型文件retrained_graph.pb、标签文件上retrained_labels.txt。“瓶颈”(bottlenecks)文件,描述实际分类最终输出层前一层(倒数第二层)。倒数第二层训练很好,瓶颈值是有意义紧凑图像摘要,包含足够信息使分类选择。第一次训练,retrain.py文件代码先分析所有图片,计算每张图片瓶颈值存储下来。每张图片被使用多次,不必重复计算。 编译iOS支持模型。https://petewarden.com/2016/09/27/tensorflow-for-mobile-poets/ 。原始模型到iOS模型,先去掉iOS系统不支持操作,优化模型,再将模型量化,权重变8位常数,缩小模型,最后模型内存映射。去掉iOS系统不支持操作,优化模型。iOS版本TensorFlow仅支持预测阶段常见没有大外部依赖关系操作。支持操作列表:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/makefile/tf_op_files.txt 。DecodeJpeg不支持,JPEG格式图片解码,依赖libjpeg。从摄像头实时识别花卉种类,直接处理相机图像缓冲区,不存JPEG文件再解码。预训练模型Inception V3 从图片数据集训练,包含DecodeJpeg操作。输入数据直接提供(feed)Decode后Mul操作,绕过Decode操作。优化加速预测,显式批处理规范化(explicit batch normalization)操作合并到卷积权重,减少计算次数。 bazel build tensorflow/python/tools:optimize_for_inference bazel-bin/tensorflow/python/tools/optimize_for_inference \ --input=/tmp/retrained_graph.pb \ --output=/tmp/optimized_graph.pb \ --input_names=Mul \ --output_names=final_result \ label_image命令预测: bazel-bin/tensorflow/examples/label_image/label_image \ --output_layer=final_result \ --labels=/tmp/output_labels.txt \ --image=/tmp/flower_photos/daisy/5547758_eea9edfd54_n.jpg --graph=/tmp/output_graph.pb \ --input_layer=Mul \ --input_mean=128 \ --input_std=128 \ 量化模型。苹果系统在.ipa包分发应用程度,所有应用程度资源都用zip压缩。模型权重从浮点数转整数(范围0~255),损失准确度,小于1%。 bazel build tensorflow/tools/quantization:quantization_graph bazel-bin/tensorflow/tools/quantization/quantization_graph \ --input=/tmp/optimized_graph.pb \ --output=/tmp/rounded_graph.pb \ --output_node_names=final_result \ --mode=weights_rounded 内存映射 memory mapping。物理内存映射到进程地址空间内,应用程序直接用输入/输出地址空间,提高读写效率。模型全部一次性加载到内存缓冲区,会对iOS RAM施加过大压力,操作系统会杀死内存占用过多程序。模型权值缓冲区只读,可映射到内存。重新排列模型,权重分部分逐块从主GraphDef加载到内存。 bazel build tensorflow/contrib/util:convert_graphdef_memmapped_format bazel-bin/tensorflow/contrib/util/convert_graphdef_memmapped_format \ --in_graph=/tmp/rounded_graph.pb \ --out_graph=/tmp/mmapped_graph.pb 生成iOS工程文件运行。视频流实进预测演示程序例子。https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/ios/camera 。模型文件、标记文件复制到data目录。修改CameraExampleViewController.mm,更改加载模型文件名称、输入图片尺寸、操作节点名字、缩放像素大小。 #import <AssertMacros.h> #import <AssetsLibrary/AssetsLibrary.h> #import <CoreImage/CoreImage.h> #import <ImageIO/ImageIO.h> #import "CameraExampleViewController.h" #include <sys/time.h> #include "tensorflow_utils.h" // If you have your own model, modify this to the file name, and make sure // you've added the file to your app resources too. static NSString* model_file_name = @"tensorflow_inception_graph"; static NSString* model_file_type = @"pb"; // This controls whether we'll be loading a plain GraphDef proto, or a // file created by the convert_graphdef_memmapped_format utility that wraps a // GraphDef and parameter file that can be mapped into memory from file to // reduce overall memory usage. const bool model_uses_memory_mapping = false; // If you have your own model, point this to the labels file. static NSString* labels_file_name = @"imagenet_comp_graph_label_strings"; static NSString* labels_file_type = @"txt"; // These dimensions need to match those the model was trained with. // 以下尺寸需要和模型训练时相匹配 const int wanted_input_width =299;// 224; const int wanted_input_height = 299;//224; const int wanted_input_channels = 3; const float input_mean = 128.0f;//117.0f; const float input_std = 128.0f;//1.0f; const std::string input_layer_name = "Mul";//"input"; const std::string output_layer_name = "final_result";//"softmax1"; static void *AVCaptureStillImageIsCapturingStillImageContext = &AVCaptureStillImageIsCapturingStillImageContext; @interface CameraExampleViewController (InternalMethods) - (void)setupAVCapture; - (void)teardownAVCapture; @end @implementation CameraExampleViewController - (void)setupAVCapture { NSError *error = nil; session = [AVCaptureSession new]; if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) [session setSessionPreset:AVCaptureSessionPreset640x480]; else [session setSessionPreset:AVCaptureSessionPresetPhoto]; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; assert(error == nil); isUsingFrontFacingCamera = NO; if ([session canAddInput:deviceInput]) [session addInput:deviceInput]; stillImageOutput = [AVCaptureStillImageOutput new]; [stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:(void *)(AVCaptureStillImageIsCapturingStillImageContext)]; if ([session canAddOutput:stillImageOutput]) [session addOutput:stillImageOutput]; videoDataOutput = [AVCaptureVideoDataOutput new]; NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; [videoDataOutput setVideoSettings:rgbOutputSettings]; [videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL); [videoDataOutput setSampleBufferDelegate:self queue:videoDataOutputQueue]; if ([session canAddOutput:videoDataOutput]) [session addOutput:videoDataOutput]; [[videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:YES]; previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session]; [previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]]; [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect]; CALayer *rootLayer = [previewView layer]; [rootLayer setMasksToBounds:YES]; [previewLayer setFrame:[rootLayer bounds]]; [rootLayer addSublayer:previewLayer]; [session startRunning]; if (error) { NSString *title = [NSString stringWithFormat:@"Failed with error %d", (int)[error code]]; UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *dismiss = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleDefault handler:nil]; [alertController addAction:dismiss]; [self presentViewController:alertController animated:YES completion:nil]; [self teardownAVCapture]; } } - (void)teardownAVCapture { [stillImageOutput removeObserver:self forKeyPath:@"isCapturingStillImage"]; [previewLayer removeFromSuperlayer]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == AVCaptureStillImageIsCapturingStillImageContext) { BOOL isCapturingStillImage = [[change objectForKey:NSKeyValueChangeNewKey] boolValue]; if (isCapturingStillImage) { // do flash bulb like animation flashView = [[UIView alloc] initWithFrame:[previewView frame]]; [flashView setBackgroundColor:[UIColor whiteColor]]; [flashView setAlpha:0.f]; [[[self view] window] addSubview:flashView]; [UIView animateWithDuration:.4f animations:^{ [flashView setAlpha:1.f]; }]; } else { [UIView animateWithDuration:.4f animations:^{ [flashView setAlpha:0.f]; } completion:^(BOOL finished) { [flashView removeFromSuperview]; flashView = nil; }]; } } } - (AVCaptureVideoOrientation)avOrientationForDeviceOrientation: (UIDeviceOrientation)deviceOrientation { AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)(deviceOrientation); if (deviceOrientation == UIDeviceOrientationLandscapeLeft) result = AVCaptureVideoOrientationLandscapeRight; else if (deviceOrientation == UIDeviceOrientationLandscapeRight) result = AVCaptureVideoOrientationLandscapeLeft; return result; } - (IBAction)takePicture:(id)sender { if ([session isRunning]) { [session stopRunning]; [sender setTitle:@"Continue" forState:UIControlStateNormal]; flashView = [[UIView alloc] initWithFrame:[previewView frame]]; [flashView setBackgroundColor:[UIColor whiteColor]]; [flashView setAlpha:0.f]; [[[self view] window] addSubview:flashView]; [UIView animateWithDuration:.2f animations:^{ [flashView setAlpha:1.f]; } completion:^(BOOL finished) { [UIView animateWithDuration:.2f animations:^{ [flashView setAlpha:0.f]; } completion:^(BOOL finished) { [flashView removeFromSuperview]; flashView = nil; }]; }]; } else { [session startRunning]; [sender setTitle:@"Freeze Frame" forState:UIControlStateNormal]; } } + (CGRect)videoPreviewBoxForGravity:(NSString *)gravity frameSize:(CGSize)frameSize apertureSize:(CGSize)apertureSize { CGFloat apertureRatio = apertureSize.height / apertureSize.width; CGFloat viewRatio = frameSize.width / frameSize.height; CGSize size = CGSizeZero; if ([gravity isEqualToString:AVLayerVideoGravityResizeAspectFill]) { if (viewRatio > apertureRatio) { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } else { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } } else if ([gravity isEqualToString:AVLayerVideoGravityResizeAspect]) { if (viewRatio > apertureRatio) { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } else { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } } else if ([gravity isEqualToString:AVLayerVideoGravityResize]) { size.width = frameSize.width; size.height = frameSize.height; } CGRect videoBox; videoBox.size = size; if (size.width < frameSize.width) videoBox.origin.x = (frameSize.width - size.width) / 2; else videoBox.origin.x = (size.width - frameSize.width) / 2; if (size.height < frameSize.height) videoBox.origin.y = (frameSize.height - size.height) / 2; else videoBox.origin.y = (size.height - frameSize.height) / 2; return videoBox; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CFRetain(pixelBuffer); [self runCNNOnFrame:pixelBuffer]; CFRelease(pixelBuffer); } - (void)runCNNOnFrame:(CVPixelBufferRef)pixelBuffer { assert(pixelBuffer != NULL); OSType sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer); int doReverseChannels; if (kCVPixelFormatType_32ARGB == sourcePixelFormat) { doReverseChannels = 1; } else if (kCVPixelFormatType_32BGRA == sourcePixelFormat) { doReverseChannels = 0; } else { assert(false); // Unknown source format } const int sourceRowBytes = (int)CVPixelBufferGetBytesPerRow(pixelBuffer); const int image_width = (int)CVPixelBufferGetWidth(pixelBuffer); const int fullHeight = (int)CVPixelBufferGetHeight(pixelBuffer); CVPixelBufferLockFlags unlockFlags = kNilOptions; CVPixelBufferLockBaseAddress(pixelBuffer, unlockFlags); unsigned char *sourceBaseAddr = (unsigned char *)(CVPixelBufferGetBaseAddress(pixelBuffer)); int image_height; unsigned char *sourceStartAddr; if (fullHeight <= image_width) { image_height = fullHeight; sourceStartAddr = sourceBaseAddr; } else { image_height = image_width; const int marginY = ((fullHeight - image_width) / 2); sourceStartAddr = (sourceBaseAddr + (marginY * sourceRowBytes)); } const int image_channels = 4; assert(image_channels >= wanted_input_channels); tensorflow::Tensor image_tensor( tensorflow::DT_FLOAT, tensorflow::TensorShape( {1, wanted_input_height, wanted_input_width, wanted_input_channels})); auto image_tensor_mapped = image_tensor.tensor<float, 4>(); tensorflow::uint8 *in = sourceStartAddr; float *out = image_tensor_mapped.data(); for (int y = 0; y < wanted_input_height; ++y) { float *out_row = out + (y * wanted_input_width * wanted_input_channels); for (int x = 0; x < wanted_input_width; ++x) { const int in_x = (y * image_width) / wanted_input_width; const int in_y = (x * image_height) / wanted_input_height; tensorflow::uint8 *in_pixel = in + (in_y * image_width * image_channels) + (in_x * image_channels); float *out_pixel = out_row + (x * wanted_input_channels); for (int c = 0; c < wanted_input_channels; ++c) { out_pixel[c] = (in_pixel[c] - input_mean) / input_std; } } } CVPixelBufferUnlockBaseAddress(pixelBuffer, unlockFlags); if (tf_session.get()) { std::vector<tensorflow::Tensor> outputs; tensorflow::Status run_status = tf_session->Run( {{input_layer_name, image_tensor}}, {output_layer_name}, {}, &outputs); if (!run_status.ok()) { LOG(ERROR) << "Running model failed:" << run_status; } else { tensorflow::Tensor *output = &outputs[0]; auto predictions = output->flat<float>(); NSMutableDictionary *newValues = [NSMutableDictionary dictionary]; for (int index = 0; index < predictions.size(); index += 1) { const float predictionValue = predictions(index); if (predictionValue > 0.05f) { std::string label = labels[index % predictions.size()]; NSString *labelObject = [NSString stringWithUTF8String:label.c_str()]; NSNumber *valueObject = [NSNumber numberWithFloat:predictionValue]; [newValues setObject:valueObject forKey:labelObject]; } } dispatch_async(dispatch_get_main_queue(), ^(void) { [self setPredictionValues:newValues]; }); } } CVPixelBufferUnlockBaseAddress(pixelBuffer, 0); } - (void)dealloc { [self teardownAVCapture]; } // use front/back camera - (IBAction)switchCameras:(id)sender { AVCaptureDevicePosition desiredPosition; if (isUsingFrontFacingCamera) desiredPosition = AVCaptureDevicePositionBack; else desiredPosition = AVCaptureDevicePositionFront; for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([d position] == desiredPosition) { [[previewLayer session] beginConfiguration]; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil]; for (AVCaptureInput *oldInput in [[previewLayer session] inputs]) { [[previewLayer session] removeInput:oldInput]; } [[previewLayer session] addInput:input]; [[previewLayer session] commitConfiguration]; break; } } isUsingFrontFacingCamera = !isUsingFrontFacingCamera; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)viewDidLoad { [super viewDidLoad]; square = [UIImage imageNamed:@"squarePNG"]; synth = [[AVSpeechSynthesizer alloc] init]; labelLayers = [[NSMutableArray alloc] init]; oldPredictionValues = [[NSMutableDictionary alloc] init]; tensorflow::Status load_status; if (model_uses_memory_mapping) { load_status = LoadMemoryMappedModel( model_file_name, model_file_type, &tf_session, &tf_memmapped_env); } else { load_status = LoadModel(model_file_name, model_file_type, &tf_session); } if (!load_status.ok()) { LOG(FATAL) << "Couldn't load model: " << load_status; } tensorflow::Status labels_status = LoadLabels(labels_file_name, labels_file_type, &labels); if (!labels_status.ok()) { LOG(FATAL) << "Couldn't load labels: " << labels_status; } [self setupAVCapture]; } - (void)viewDidUnload { [super viewDidUnload]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (BOOL)prefersStatusBarHidden { return YES; } - (void)setPredictionValues:(NSDictionary *)newValues { const float decayValue = 0.75f; const float updateValue = 0.25f; const float minimumThreshold = 0.01f; NSMutableDictionary *decayedPredictionValues = [[NSMutableDictionary alloc] init]; for (NSString *label in oldPredictionValues) { NSNumber *oldPredictionValueObject = [oldPredictionValues objectForKey:label]; const float oldPredictionValue = [oldPredictionValueObject floatValue]; const float decayedPredictionValue = (oldPredictionValue * decayValue); if (decayedPredictionValue > minimumThreshold) { NSNumber *decayedPredictionValueObject = [NSNumber numberWithFloat:decayedPredictionValue]; [decayedPredictionValues setObject:decayedPredictionValueObject forKey:label]; } } oldPredictionValues = decayedPredictionValues; for (NSString *label in newValues) { NSNumber *newPredictionValueObject = [newValues objectForKey:label]; NSNumber *oldPredictionValueObject = [oldPredictionValues objectForKey:label]; if (!oldPredictionValueObject) { oldPredictionValueObject = [NSNumber numberWithFloat:0.0f]; } const float newPredictionValue = [newPredictionValueObject floatValue]; const float oldPredictionValue = [oldPredictionValueObject floatValue]; const float updatedPredictionValue = (oldPredictionValue + (newPredictionValue * updateValue)); NSNumber *updatedPredictionValueObject = [NSNumber numberWithFloat:updatedPredictionValue]; [oldPredictionValues setObject:updatedPredictionValueObject forKey:label]; } NSArray *candidateLabels = [NSMutableArray array]; for (NSString *label in oldPredictionValues) { NSNumber *oldPredictionValueObject = [oldPredictionValues objectForKey:label]; const float oldPredictionValue = [oldPredictionValueObject floatValue]; if (oldPredictionValue > 0.05f) { NSDictionary *entry = @{ @"label" : label, @"value" : oldPredictionValueObject }; candidateLabels = [candidateLabels arrayByAddingObject:entry]; } } NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"value" ascending:NO]; NSArray *sortedLabels = [candidateLabels sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]; const float leftMargin = 10.0f; const float topMargin = 10.0f; const float valueWidth = 48.0f; const float valueHeight = 26.0f; const float labelWidth = 246.0f; const float labelHeight = 26.0f; const float labelMarginX = 5.0f; const float labelMarginY = 5.0f; [self removeAllLabelLayers]; int labelCount = 0; for (NSDictionary *entry in sortedLabels) { NSString *label = [entry objectForKey:@"label"]; NSNumber *valueObject = [entry objectForKey:@"value"]; const float value = [valueObject floatValue]; const float originY = (topMargin + ((labelHeight + labelMarginY) * labelCount)); const int valuePercentage = (int)roundf(value * 100.0f); const float valueOriginX = leftMargin; NSString *valueText = [NSString stringWithFormat:@"%d%%", valuePercentage]; [self addLabelLayerWithText:valueText originX:valueOriginX originY:originY width:valueWidth height:valueHeight alignment:kCAAlignmentRight]; const float labelOriginX = (leftMargin + valueWidth + labelMarginX); [self addLabelLayerWithText:[label capitalizedString] originX:labelOriginX originY:originY width:labelWidth height:labelHeight alignment:kCAAlignmentLeft]; if ((labelCount == 0) && (value > 0.5f)) { [self speak:[label capitalizedString]]; } labelCount += 1; if (labelCount > 4) { break; } } } - (void)removeAllLabelLayers { for (CATextLayer *layer in labelLayers) { [layer removeFromSuperlayer]; } [labelLayers removeAllObjects]; } - (void)addLabelLayerWithText:(NSString *)text originX:(float)originX originY:(float)originY width:(float)width height:(float)height alignment:(NSString *)alignment { CFTypeRef font = (CFTypeRef) @"Menlo-Regular"; const float fontSize = 20.0f; const float marginSizeX = 5.0f; const float marginSizeY = 2.0f; const CGRect backgroundBounds = CGRectMake(originX, originY, width, height); const CGRect textBounds = CGRectMake((originX + marginSizeX), (originY + marginSizeY), (width - (marginSizeX * 2)), (height - (marginSizeY * 2))); CATextLayer *background = [CATextLayer layer]; [background setBackgroundColor:[UIColor blackColor].CGColor]; [background setOpacity:0.5f]; [background setFrame:backgroundBounds]; background.cornerRadius = 5.0f; [[self.view layer] addSublayer:background]; [labelLayers addObject:background]; CATextLayer *layer = [CATextLayer layer]; [layer setForegroundColor:[UIColor whiteColor].CGColor]; [layer setFrame:textBounds]; [layer setAlignmentMode:alignment]; [layer setWrapped:YES]; [layer setFont:font]; [layer setFontSize:fontSize]; layer.contentsScale = [[UIScreen mainScreen] scale]; [layer setString:text]; [[self.view layer] addSublayer:layer]; [labelLayers addObject:layer]; } - (void)setPredictionText:(NSString *)text withDuration:(float)duration { if (duration > 0.0) { CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"foregroundColor"]; colorAnimation.duration = duration; colorAnimation.fillMode = kCAFillModeForwards; colorAnimation.removedOnCompletion = NO; colorAnimation.fromValue = (id)[UIColor darkGrayColor].CGColor; colorAnimation.toValue = (id)[UIColor whiteColor].CGColor; colorAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [self.predictionTextLayer addAnimation:colorAnimation forKey:@"colorAnimation"]; } else { self.predictionTextLayer.foregroundColor = [UIColor whiteColor].CGColor; } [self.predictionTextLayer removeFromSuperlayer]; [[self.view layer] addSublayer:self.predictionTextLayer]; [self.predictionTextLayer setString:text]; } - (void)speak:(NSString *)words { if ([synth isSpeaking]) { return; } AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:words]; utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"]; utterance.rate = 0.75 * AVSpeechUtteranceDefaultSpeechRate; [synth speakUtterance:utterance]; } @end 连上iPhone手机,双击tensorflow/contrib/ios_examples/camera/camera_example.xcodeproj编译运行。手机安装好APP,打开APP,找到玫瑰花识别。训练迭代次数10000次后,识别率99%以上。模拟器打包,生成打包工程文件位于/Users/libinggen/Library/Developer/Xcode/DeriveData/camera_example-dhfdsdfesfmrwtfb1fpfkfjsdfhdskf/Build/Products/Debug-iphoneos。打开CameraExample.app,有可执行文件CameraExample、资源文件模型文件mmapped_graph.pb、标记文件retrained_labels.txt。 Android系统实践。 环境准备。MacBook Pro。Oracle官网下载JDK1.8版本。http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 。jdk-8u111-macosx-x64.dmg。双击安装。设置Java环境变量: JAVA_HOME='/usr/libexec/java_home' export JAVA_HOME 搭建Android SDK环境。Android官网下载Android SDK,https://developer.android.com 。25.0.2版本。android-sdk_r25.0.2-macosx.zip。解压到~/Library/Android/sdk目录。build-tools、extras、patcher、platform-tools #各版本SDK 根据API Level划分SDK版本、platforms、sources、system-images、temp #临时文件夹 在SDK更新安装时用到、tools #各版本通用SDK工具 有adb、aapt、aidl、dx文件。搭建Android NDK环境。Android官网下载Android NDK Mac OS X版本,https://developer.android.com/ndk/downloads/index.html 。android-ndk-r13b-darwin-x86_64.zip文件。解压,CHANGELOG.md、build、ndk-build、ndk-depends、ndk-gdb、ndk-stack、ndk-which、platforms、prebuilt、python-packages、shader-tools、simpleperf、source.properties、sources、toolchains。搭建Bazel。brew安装bazel: brew install bazel 更新bazel: brew upgrade bazel 编译演示程序运行。修改tensorflow-1.1.0根目录WORKSPACE文件。android_sdk_repository、android_ndk_repository配置改为用户自己安装目录、版本。 android_sdk_repository( name = "androidsdk", api_level = 25, build_tools_version = "25.0.2", # Replace with path to Android SDK on your system path = "~/Library/Android/sdk" ) android_ndk_repository( name = "androidndk", api_level = 23, path = "~/Downloads/android-ndk-r13b" ) 在根目录用bazel构建: bazel build // tensorflow/examples/android:tensorflow_demo 编译成功,默认在tensorflow-1.1.0/bazel-bin/tensorflow/examples/android目录生成TensorFlow演示程序。运行。生成apk文件传输到手机,手机摄像头看效果。Android 6.0.1。开启“开发者模式”。手机用数据线与计算机相连,进入SDK所在目录,进入platform-tools文件夹,找到adb命令,执行: ./adb install tensorflow-0.12/bazel-bin/tensorflow/examples/android/tensorflow_demo.apk tensorflow_demo.apk自动安装到手机。打开TF Detec App。App 调起手机摄像头,摄像头返回数据流实时监测。 自定义模型编译运行。训练原始模型、编译Android系统支持模型、生成Android apk文件运行。训练原始模型、编译Android系统支持模型。用项目根目录tensorflow/python/tools/optimize_for_inference.py、tensorflow/tools/quantization/quantize_graph.py、tensorflow/contrib/util/convert_graphdef_memmapped_format.cc对模型优化。将第一步生成原始模型文件retrained_graph.pb、标记文件retrained_labels.txt放在tensorflow/examples/android/assets目录。修改tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowImageClassifier.java要加载模型文件名称,输入图片尺寸、操作节点名字、缩放像素大小。 package org.tensorflow.demo; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.os.Trace; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Vector; import org.tensorflow.Operation; import org.tensorflow.contrib.android.TensorFlowInferenceInterface; /** A classifier specialized to label images using TensorFlow. */ public class TensorFlowImageClassifier implements Classifier { private static final String TAG = "TensorFlowImageClassifier"; // Only return this many results with at least this confidence. private static final int MAX_RESULTS = 3; private static final float THRESHOLD = 0.1f; // Config values. private String inputName; private String outputName; private int inputSize; private int imageMean; private float imageStd; // Pre-allocated buffers. private Vector<String> labels = new Vector<String>(); private int[] intValues; private float[] floatValues; private float[] outputs; private String[] outputNames; private boolean logStats = false; private TensorFlowInferenceInterface inferenceInterface; private TensorFlowImageClassifier() {} /** * Initializes a native TensorFlow session for classifying images. * * @param assetManager The asset manager to be used to load assets. * @param modelFilename The filepath of the model GraphDef protocol buffer. * @param labelFilename The filepath of label file for classes. * @param inputSize The input size. A square image of inputSize x inputSize is assumed. * @param imageMean The assumed mean of the image values. * @param imageStd The assumed std of the image values. * @param inputName The label of the image input node. * @param outputName The label of the output node. * @throws IOException */ public static Classifier create( AssetManager assetManager, String modelFilename, String labelFilename, int inputSize, int imageMean, float imageStd, String inputName, String outputName) { TensorFlowImageClassifier c = new TensorFlowImageClassifier(); c.inputName = inputName; c.outputName = outputName; // Read the label names into memory. // TODO(andrewharp): make this handle non-assets. String actualFilename = labelFilename.split("file:///android_asset/")[1]; Log.i(TAG, "Reading labels from: " + actualFilename); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(assetManager.open(actualFilename))); String line; while ((line = br.readLine()) != null) { c.labels.add(line); } br.close(); } catch (IOException e) { throw new RuntimeException("Problem reading label file!" , e); } c.inferenceInterface = new TensorFlowInferenceInterface(assetManager, modelFilename); // The shape of the output is [N, NUM_CLASSES], where N is the batch size. final Operation operation = c.inferenceInterface.graphOperation(outputName); final int numClasses = (int) operation.output(0).shape().size(1); Log.i(TAG, "Read " + c.labels.size() + " labels, output layer size is " + numClasses); // Ideally, inputSize could have been retrieved from the shape of the input operation. Alas, // the placeholder node for input in the graphdef typically used does not specify a shape, so it // must be passed in as a parameter. c.inputSize = inputSize; c.imageMean = imageMean; c.imageStd = imageStd; // Pre-allocate buffers. c.outputNames = new String[] {outputName}; c.intValues = new int[inputSize * inputSize]; c.floatValues = new float[inputSize * inputSize * 3]; c.outputs = new float[numClasses]; return c; } @Override public List<Recognition> recognizeImage(final Bitmap bitmap) { // Log this method so that it can be analyzed with systrace. Trace.beginSection("recognizeImage"); Trace.beginSection("preprocessBitmap"); // Preprocess the image data from 0-255 int to normalized float based // on the provided parameters. bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); for (int i = 0; i < intValues.length; ++i) { final int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd; floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd; } Trace.endSection(); // Copy the input data into TensorFlow. Trace.beginSection("feed"); inferenceInterface.feed(inputName, floatValues, 1, inputSize, inputSize, 3); Trace.endSection(); // Run the inference call. Trace.beginSection("run"); inferenceInterface.run(outputNames, logStats); Trace.endSection(); // Copy the output Tensor back into the output array. Trace.beginSection("fetch"); inferenceInterface.fetch(outputName, outputs); Trace.endSection(); // Find the best classifications. PriorityQueue<Recognition> pq = new PriorityQueue<Recognition>( 3, new Comparator<Recognition>() { @Override public int compare(Recognition lhs, Recognition rhs) { // Intentionally reversed to put high confidence at the head of the queue. return Float.compare(rhs.getConfidence(), lhs.getConfidence()); } }); for (int i = 0; i < outputs.length; ++i) { if (outputs[i] > THRESHOLD) { pq.add( new Recognition( "" + i, labels.size() > i ? labels.get(i) : "unknown", outputs[i], null)); } } final ArrayList<Recognition> recognitions = new ArrayList<Recognition>(); int recognitionsSize = Math.min(pq.size(), MAX_RESULTS); for (int i = 0; i < recognitionsSize; ++i) { recognitions.add(pq.poll()); } Trace.endSection(); // "recognizeImage" return recognitions; } @Override public void enableStatLogging(boolean logStats) { this.logStats = logStats; } @Override public String getStatString() { return inferenceInterface.getStatString(); } @Override public void close() { inferenceInterface.close(); } } 重新编译apk,连接Android手机,安装apk: bazel buld //tensorflow/examples/android:tensorflow_demo adb install -r -g bazel-bin/tensorflow/examples/android/tensorflow_demo.apk 树莓派实践。 Tensorflow可以在树莓派(Raspberry Pi)运行。树莓派,只有信用卡大小微型电脑,系统基于Linux,有音频、视频功能。应用,输入1万张自己的面部图片,在树莓派训练人脸识别模型,教会它认识你,你进入家门后,帮你开灯、播放音乐各种功能。树莓派编译方法和直接在Linux环境上用相似。 参考资料:《TensorFlow技术解析与实战》 欢迎推荐上海机器学习工作机会,我的微信:qingxingfengzi

优秀的个人博客,低调大师

libgdx游戏引擎开发笔记(二)主要类的详解(图像绘制)

下面我们来看看libgdx游戏引擎中一些常用的类 1.Gdx类 Gdx是Libgdx类库运行的核心所在,不单运行Graphics、Input、Files、Audio、AndroidApplication等Libgdx关键部分,所必需的实例会在Libgdx初始化时注入Gdx中对应的graphics、input、files、audio、app等静态变量里面,就连Libgdx对OpenGL接口(或OpenGLES,视Libgdx运行平台而定,以下统称OpenGL)的GL10、GL11、GL20、GLCommon等封装类也会在Graphics实例化时分别注入到gl10、gl11、gl20、gl这四个同样位于Gdx的静态变量当中(在Graphics中也会继续保留它们的引用,因此无论你执行Gdx.graphics.getGL10还是Gdx.gl10,其实都在调用同一个静态变量),总之一句话,要想运行Libgdx必须的使用Gdx! 2.图形绘制 2.1.Texture类: 定义:图片从原始格式解码并上传到GPU就被称为纹理,其实质可理解为保存在显存中的Image。 Libgdx的纹理可以直接从指定文件路径加载,也可以通过它提供的Pixmap类凭空创建(它的Texture(int width, int height, Format format)构造内部直接调用了Pixmap,不是必须在外部生成Pixmap后注入)。这里说一下前者: 1 Gdx.files. internal ( "button.jpg" ) Gdx.files,它是libgdx的文件模块,主要提供以下5大功能:读取文件,写入文件、复制文件、移动文件、列出文件和目录。其中获取文件有许多种办法: 1.Classpath: 路径相对于classpath,文件通常为只读。 2.Internal: 内部文件路径相对于程序根目录或者android 的assets文件夹。 3.External: 外部文件路径是相对于SD卡根目录 4.Absolute:assets文件夹本身就是存储资源的文件夹,而且相比resource文件夹,它其中的资源不会生成R中的ID,用来放图片很是合适。 2.2.SpriteBatch类: 定义:SpriteBatch用于绘制二维矩形参考纹理(区域)。SpriteBatch类可用于批量绘图命令和优化处理的GPU。 Libgdx所提供的纹理渲染器,本质上是OpenGL的简易封装体,每次调用SpriteBatch类都必须以begin函数开头,以end函数结尾,中间调用draw()进行绘制。SpriteBatch可以把许多相同纹理一起描述并一起送入GPU,同时赋予纹理和坐标以便每个图形的绘制。 2.3TextureRegion类 定义:定义了一个矩形区域的纹理。使用的坐标系统与x轴指向右,Y轴向下在左上角的起源。 将多个图片资源集合在一个图片文件夹中,而要显示图片的一部分就要使用该类,TextureRegion一般都是截取texture,然后定义截取起点(x,y)随后再定义宽高(width,height),如果宽高是正数,那么就是沿x,y正方向截取,如果是负就是沿x,y负方向截取,方向只和宽高的正负有关。 1 textureRegion = new TextureRegion(texture, 0 , 0 , 48 , 48 ); 1 textureRegion = new TextureRegion(texture, 48 , 48 ,- 48 ,- 48 ); 2.4.Sprite类 定义:持有的几何形状,颜色,和纹理信息使用加载绘制2D精灵。一个精灵有定位和给定的宽度和高度尺寸。的位置是相对于通过加载指定的坐标系的原点。begin()和各自的矩阵。一个精灵总是矩形和它的位置(x,y)是位于左下角的矩形。一个精灵也有一个起点,旋转和缩放的执行(即,产地不通过旋转和缩放修改),起点是相对于左下角的精灵,它的位置。 它是TextureRegion的加强版,还能指定位置,颜色,旋转等等。 鉴于以上的总结,我们来看一个显示图片的例子(部分裁剪) 1 2 3 4 5 6 7 8 9 10 11 12 package com.zhf.android_libgdx; import com.badlogic.gdx.backends.android.AndroidApplication; import android.os.Bundle; public class MainActivity extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); //在此启动游戏,FirstGame实现了ApplicationListener的类 initialize( new FirstGame(), false ); //specifying the configuration for the GLSurfaceView. //第二个参数如果设为true,则在opengl 2.0可用的情况下会使用opengl 2.0。 } } FirstGame类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package com.zhf.android_libgdx; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class FirstGame implements ApplicationListener { //绘图用的SpriteBatch private SpriteBatch batch; //纹理 private Texture texture; //区域 private TextureRegion region; @Override public void create() { batch = new SpriteBatch(); //实例化 texture= new Texture(Gdx.files. internal ( "image1.jpg" )); region= new TextureRegion(texture, 30 , 80 , 200 , 200 ); } @Override public void dispose() { batch.dispose(); texture.dispose(); region.dispose(); } @Override public void pause() { // TODO Auto-generated method stub } @Override public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); //清屏 batch.begin(); batch.draw(region, 0 , 0 ); batch.end(); } @Override public void resize( int width, int height) { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } } 效果图: 使用Sprite类: 声明 1 2 //Sprite不光包含TextureRegion的功能,还可以指定位置和颜色 privateSprite sprite; 实例化 1 2 3 4 5 //精灵类 sprite=newSprite(texture, 80 , 80 , 400 , 300 ); sprite.setPosition( 10 , 10 ); //位置 sprite.setRotation( 20 ); //旋转 sprite.setColor( 0 .5f, 0 .0f, 0 .0f, 0 .5f); //为图形着色死奥用 调用 1 sprite.draw(batch); //精灵类绘画 效果图: 对了,这里还有很重要的一点哦! Android上画图可以使用OpenGL ES,分两个不兼容的版本:OpenGL ES 1.x,和 OpenGL ES 2.0。它们之间的一个重要区别就是:OpenGL ES 1.x的图片大小必须是2的整数次幂,而OpenGL ES 2.0则无此要求。 而libgdx在早期使用OpenGL es1.x 的版本所以只支持2的整数次幂的图像,并一直沿用至今,新版本(0.9.8)中允许开发者使用OpenGL ES 2.0,这样使用OpenGL ES 2.0就可以不用管图片分辨率的问题了。android系统对opengl es的支持情况:OpenGLES 1.0------------>andoid 1.0-2.1(api 7) OpenGL ES 2.0------------>android 2.2(api 8)以上 恩,暂时就这么多,下次继续总结吧! 参考博客:http://www.apkbus.com/Android-159-1.html 本文转自zhf651555765 51CTO博客,原文链接:http://blog.51cto.com/smallwoniu/1255140,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android笔记:TextView和编辑框中添加图片,ImageSpan,SpannableStringBuilder用法

在TextView或者编辑框EditText中添加图片的方法,代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import java.util.regex.Matcher; import java.util.regex.Pattern; import android.os.Bundle; import android.app.Activity; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ImageSpan; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(BundlesavedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextViewtv=(TextView)findViewById(R.id.tv); Stringstr= "sdfasdfasljeojgfadfalsdkjfasjdkfalsdjfoawpjfsajfadsjfladjfals" ; SpannableStringBuilderbuilder= new SpannableStringBuilder(str); Stringflag= "" ; Patternpattern=Pattern.compile(flag); Matchermatcher=pattern.matcher(str); while (matcher.find()) { builder.setSpan( new ImageSpan( this ,R.drawable.ic_launcher),matcher.start(),matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } tv.setText(builder); EditTexted=(EditText)findViewById(R.id.editText1); ed.setText(builder); } } 布局文件代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <RelativeLayoutxmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:paddingBottom= "@dimen/activity_vertical_margin" android:paddingLeft= "@dimen/activity_horizontal_margin" android:paddingRight= "@dimen/activity_horizontal_margin" android:paddingTop= "@dimen/activity_vertical_margin" tools:context= ".MainActivity" > <TextView android:id= "@+id/tv" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "@string/hello_world" /> <EditText android:id= "@+id/editText1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_alignParentLeft= "true" android:layout_below= "@+id/tv" android:layout_marginTop= "63dp" android:ems= "10" > <requestFocus/> </EditText> </RelativeLayout> 效果图: 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1548221,如需转载请自行联系原作者

优秀的个人博客,低调大师

android -&gt;在界面上使用URI编程 ----开发笔记1

导言 做android 开发有一段时间了,很多时候就是做些重复性的数据绑定,还有就是不够操作不够灵活,例如,我在某个界面要新增一个按钮,就需要发布一个新版本,就这么一个按钮的话其实,可以完全由服务器控制,例如UC,凡客他们要更新首页,不可能为了更新一个首页特地开发一个新版本,那多傻啊,所以,观察了一下,想出了一个可能解决的方案… 1.控制显示 如何做到有服务器控制客户端的显示呢? 我们可以在客户端预留一些可能会用的例如UC的首页: 箭头标志的区域,是会根据不同情况而更新,而我现在就是要做出这样的效果. 如何控制显示? 我们知道,android 找view是通过一系列ID 值找到相关的UI 那样,我们可以通过,在服务端,发送我们要修改的id. 1,是直接发送ID值还是发送一个具体路径? 这点,我毫无犹豫的选择了发送一个ui的路径,通过在客户端把这个URI进行转义,然后获得,相关的ID值.代码 /** * 资源ID 的几种形式 * res = package:type/entry * 1,res://com.achai@drawable/test_icon * 2,res://drawable/test_icon *(1) 不带具体包名 *entry = layout/main *(2) 指定包名和类型实体 *com.achai@drawable/icon * @param url * @return */public static int getResIdFromURL( Stringurl){ URI uri = URI.create(url); Stringscheme = uri.getScheme(); Stringtype = uri.getHost(); Stringentry = uri.getPath(); entry = entry.replaceFirst(" /", " "); StringpackageName = uri.getUserInfo(); if(ress == null) initRes(); if(ress == null) return-1; //判断是否android资源URLif(!scheme.equals(" res")) return-1; //1,判断是否是带包名的uri,并执行转换,获得资源IDif(packageName != null){ returnress.getIdentifier(entry, type, packageName); }else{ returnress.getIdentifier(entry, type, defPackage); } } 思路就如同代码那样,这样,我们的客户端就能够解析服务端发送过来要改哪个UI的了!接着就是修改值的事情了,这部分,以后继续! 2,控制监听 还是用uc作为例子: 在 UC的应用中心中,有个添加应用,这里就有个问题,我们如何监听我们新增的应用呢? x 我翻阅android api的时候发现这么一行话 Tags Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. 看到这里,我觉得就可以在这里做点文章了. 我们可以做一个tag 命令系统,然后,在这些新增应用的tag上打上一个标签命令,例如,UC就可能在这些应用上的tag 打上一个url 我们点击的时候,就会跳转到相关的应用. 根据这个思路敲下如下代码 public voiddoViewClicked(View v){ String url = v.getTag().toString().trim(); if(v != null&& url != null){ //对view 中tag 进行解析doExecUrl(v, url); } } protected voiddoExecUrl(View view, String url) { try{ if(url.indexOf('\n') &gt; 0){ String[] urls = url.split(" \n"); for(String u : urls){ execUrl(view, u); } } else{ execUrl(view, url); } } catch(RuntimeException ex){ UserApp.curApp().showMessage(" url 解析错误"); } } private voidexecUrl(View view, String u) { URI execUri = URI.create(u); if(execUri == null) return; String prefix = execUri.getScheme(); //执行相关的的命令 if(prefix.equals(" cmd")){ execCmd(execUri); } else if(prefix.equals(" act")){ execAct(execUri); } } /** * 执行命令操作 * @param u */ private voidexecCmd(URI u){ String type = u.getHost(); //监控 watch if(type.equals(" watch")){ //用于观察view 中的变量改变情况,晚些在实现 return; } //结束当前view if(type.equals(" finish")){ theAct.finish(); return; } //弹出提示 if(type.equals(" hint")){ String msg = u.getFragment(); if(msg != null){ UserApp.showMessage(theAct, msg); } return; } //重新读取 if(type.equals(" reload")){ return; } //设置指定id view 的值 if(type.equals(" setview")){ return; } //设置显示某个view if(type.equals(" showview")){ return; } } 这样,我们可以在初始化view的时候,遍历所有view的元素,有tag命令就设置监听器! public voidcheckView(){ ViewGroup vg = (ViewGroup) findViewById(R.id.line); intcount = vg.getChildCount(); for( inti=0; i &lt; count; i ++){ View child = vg.getChildAt(i); String tag = (String) child.getTag(); if(tag != null){ initTagCmd.setViewTagListenr(child); } } } 这样我们就可以很灵活的操作我们的UI 事件了! k 可能有人会说效率问题? 效率的影响那是肯定会有的,但是,你想一下,一个view 官方推荐不要超过80个,一般而言也就10来个,遍历消耗的时间估计就算是htc g1(第一台android手机)那样的配置的手机都没问题,更何况是现在4核的android手机…. 试一下效果: 这是一个开源的玩意… 这个项目放在了github上,如果有朋友,想试一下可以到以下链接下载或者关注,提供一些建议,完善的话会慢慢来… android_URI4Resource 本文转自 liam2199 博客,原文链接: http://blog.51cto.com/youxilua/854675 如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码