magic 发布的文章

Serverless实战驾校小程序【考题练习】三
介绍
上一节我们讲了,实现了分类、题目显示、进度条显示等功能,这节我们继续完善答题功能。由于开发时间比较紧,这里主要写实习思路,与核心代码。

这一节做顺序练习与模拟考试。都属于答题详细页面功能

这次进度条可以根据答题进度,显示进度。 这个也用了iview的一个插件, 目前样式没调整, 这个后面再说。

这一节主要实现了一些逻辑计算

逻辑一:记录学习题目进度
记录的核心代码,在提交保存的时候调用。当然,也可以在练习离开的时候触发,这里给了个按钮,点击保存即可保存学习记录

const AddLearning = ({ num, result, type = 1 }) => {
  let current = wx.Bmob.User.current()
  return new Promise((resolve, reject) => {
    const query = wx.Bmob.Query('learning');
    query.set('bSubjects', '1')
    query.set('bModels', '1')
    query.set('num', num)
    query.set('result', result)
    query.set('type', type)
    query.set('uid', current.objectId)
    query.save().then(res => {
      resolve(res)
    }).catch(err => {
      console.error(err)
      reject(err)
    })
  });
}

逻辑二:记录题目回答的对错
上面的变量result记录,格式请看上一节数据库格式说明,是题目的对错。这里点击一个选择就记录一次,我在页面data里面增加了一个items变量来保存。

选择答案执行以下代码,今天先实现单选,我们单选与多选,判断事件分开来做,这样便于逻辑管理

// 单选题
  handleFruitChange ({ detail = {}, target = {} }) {
    let questionInfo = this.data.questionInfo
    // 判断单选是否正确
    if (target.dataset.id) {
      console.log('ok')
      questionInfo.isOk = 1
    }

    this.setData({
      questionInfo: questionInfo,
      current: detail.value
    });

    // 单选自动跳到下一题
    this.statistical()

    // 显示第几道题
    this.setThisData(this.data.index)
    this.setData({
      index: this.data.index + 1,
      current: ''
    });
  },

逻辑三:答题相关统计
逻辑二讲了,记录对错,这里有一些统计需要拿出来计算,先做单选题,点击选择,判断是否正确, 如果正确,记录到结果对象 [{" id ":" XXX ', '0'}, {" id ":" XXX ", "1"}] ,0代表回答错误,1正确

例如错题个数、对题个数,页面提示,进度条进一步

statistical () {
    // 统计错题个数
    let questionErr = this.data.questionErr  //错题个数
    let questionOk = this.data.questionOk  //错题个数
    let questionInfo = this.data.questionInfo
    let items = this.data.items
    let arr = { "id": questionInfo.objectId, "o": 0 }

    let t = 'error', m = '回答错误'
    if (questionInfo.isOk === 1) {
      // o 0代表失败,1代表成功
      arr.o = 1
      questionOk = questionOk + 1
      t = 'success'
      m = '回答正确'
    } else {
      // 错误数+1
      questionErr = questionErr + 1

    }
    items.push(arr)

    // 提示
    $Message({
      content: m,
      type: t,
      duration: 2
    });


    //进度条
    let totalW = this.data.index / this.data.total
    totalW = (totalW * 100).toFixed(2);
    totalW = totalW < 1 ? 1 : totalW

    this.setData({
      items: items,
      questionErr: questionErr,
      questionOk: questionOk,
      totalW: totalW,
    });
  },

逻辑四:上一题下一题的实现
页面显示第几个题目,我们用数组的下面来记录,单电机下一题,我们记录回答对错,并且数组下标+1

// 翻页
  handlePageChange ({ detail }) {
    const type = detail.type;

    const current = this.data.current
    if (current == "") {
      console.log('空')
      $Toast({
        content: '请选择答案!',
        type: 'warning'
      });
      return;
    }


    this.statistical()

    if (type === 'next') {
      this.setThisData(this.data.index)
      this.setData({
        index: this.data.index + 1,
        current: ''
      });

    } else if (type === 'prev') {
      this.setData({
        index: this.data.index - 1,
        current: ''

      });
      this.setThisData(this.data.index)
    }
  },

逻辑五:引入模式概念
因为答题页面逻辑非常多,今天写这么多也没写完一般, 除了学习模式,后面还有模拟考试模式,这里不单独使用另外的页面来开发,统一在一个页面。 所以,我们在页面data里加入model变量,代表模式。

/**

​ * 这里有个模式, 练习模式,与模拟考试模式

​ * model 1.练习模式 2.模拟考试考试

​ * 练习模式查询出所有数据练习

​ * 模拟考试 随机100题 计算打分

​ */

总结
今天练习模式里面的单项选择逻辑基本已经做好,明天将实现模拟考试,计算考试成绩等等功能

大家想学习更多的云服务开发, 可以加入Bmob的交流群:群号:273080081

好久没更新自己博客了,今天正好给同事们写一篇sublime 如何配置php code sniffer,发现国内还没有一个比较完善的教程,所以把它放到网上。

一、windows PHPSTORM 配置php code sniffer插件。

二、MAC OS PHPSTORM 配置php code sniffer插件。

三、MAC OS Sublime 3 配置php code sniffer插件。

一、windows PHPSTORM 配置php code sniffer插件。


1. 点击菜单:File->Settings 或 按快捷键 Ctrl+Alt+S

2. 选择Project Settings下的:PHP->Code Sniffer

3. 设置PHP Code Sniffer(phpcs) path为:E:\wamp\bin\pear\phpcs.bat
(根据自己电脑情况设置)

4. 点击Validate按钮,可以看到如下提示,说明设置OK

为知笔记图片

5. 选择Project Settings下的Inspections,展开PHP,勾选PHP Code Sniffer validation

为知笔记图片

6. 第一次打开的时候,需要点击一下刷新的按钮可以获取已安装的代码规范,如果无法获取到代码规范的话,先执行 phpcs -i
命令查看PHP_CodeSniffer中已经安装的编码风格,确定有之后,尝试重启一下PhpStorm在刷新看看

7. 选择一个你习惯的编码风格,然后Apply配置

为知笔记图片

8. 打开一个PHP文件,就可以看到不符合规则的提示

为知笔记图片

二、MAC OS PHPSTORM 配置php code sniffer插件。


  1. 设置PHP Code Sniffer(phpcs) path为:/usr/local/bin/phpcs

2. 点击Validate按钮,可以看到如下提示,说明设置OK

为知笔记图片

3.启用代码风格


为知笔记图片

4.演示效果


为知笔记图片

三、MAC OS Sublime 3 配置php code sniffer插件。


1.系统安装PHP_CodeSniffer、phpmd、php-cs-fixer




pear install PHP_CodeSniffer


brew install phpmd


sudo curl  -o /usr/local/bin/php-cs-fixer
sudo chmod a+x /usr/local/bin/php-cs-fixer


2.sublime 2 安装 phpcs插件(安装方法(Ctrl+Shift+P->pi(package
install)->phpcs,安装成功后右键即可看到PHP Code Sniffer选项))


为知笔记图片

3.刚刚安装好的插件,sniff this file 显示的是灰色的,修改下配置文件(这是 Sublime 2的配置) Sublime3
的配置有所区别,请自行检查。






    
    
  1. 
        
        


            {
        



    


    
  2. 
        
        


                // *nix based systems, Mac OS X and Linux
        



    


    
  3. 
        
        


                // - All commands on and using PATHS
        



    


    
  4. 
        
        


            
        



    


    
  5. 
        
        


                // We want debugging on
        



    


    
  6. 
        
        


                "show_debug": true,
        



    


    
  7. 
        
        


            
        



    


    
  8. 
        
        


                // Only execute for .php files
        



    


    
  9. 
        
        


                "extensions_to_execute": ["php"],
        



    


    
  10. 
        
        


            
        



    


    
  11. 
        
        


                // Do not execute for twig files
        



    


    
  12. 
        
        


                "extensions_to_blacklist": ["twig.php"],
        



    


    
  13. 
        
        


            
        



    


    
  14. 
        
        


                // Execute the sniffer on file save
        



    


    
  15. 
        
        


                "phpcs_execute_on_save": false,
        



    


    
  16. 
        
        


            
        



    


    
  17. 
        
        


                // Show the error list after save.
        



    


    
  18. 
        
        


                "phpcs_show_errors_on_save": true,
        



    


    
  19. 
        
        


            
        



    


    
  20. 
        
        


                // Show the errors in the gutter
        



    


    
  21. 
        
        


                "phpcs_show_gutter_marks": true,
        



    


    
  22. 
        
        


            
        



    


    
  23. 
        
        


                // Show outline for errors
        



    


    
  24. 
        
        


                "phpcs_outline_for_errors": true,
        



    


    
  25. 
        
        


            
        



    


    
  26. 
        
        


                // Show the errors in the status bar
        



    


    
  27. 
        
        


                "phpcs_show_errors_in_status": true,
        



    


    
  28. 
        
        


            
        



    


    
  29. 
        
        


                // Show the errors in the quick panel so you can then goto line
        



    


    
  30. 
        
        


                "phpcs_show_quick_panel": true,
        



    


    
  31. 
        
        


            
        



    


    
  32. 
        
        


            
        



    


    
  33. 
        
        


                // PHP_CodeSniffer settings
        



    


    
  34. 
        
        


                // Run the PHP_CodeSniffer
        



    


    
  35. 
        
        


                "phpcs_sniffer_run": true,
        



    


    
  36. 
        
        


            
        



    


    
  37. 
        
        


                // Execute PHP_CodeSniffer on save
        



    


    
  38. 
        
        


                "phpcs_command_on_save": true,
        



    


    
  39. 
        
        


            
        



    


    
  40. 
        
        


                // Path to phpcs
        



    


    
  41. 
        
        


                "phpcs_executable_path": "/usr/local/bin/phpcs",
        



    


    
  42. 
        
        


            
        



    


    
  43. 
        
        


                // Run the PEAR standard without warnings
        



    


    
  44. 
        
        


                "phpcs_additional_args": {
        



    


    
  45. 
        
        


                    "--standard": "PEAR",
        



    


    
  46. 
        
        


                    "-n": ""
        



    


    
  47. 
        
        


                },
        



    


    
  48. 
        
        


            
        



    


    
  49. 
        
        


            
        



    


    
  50. 
        
        


                // PHP-CS-Fixer settings
        



    


    
  51. 
        
        


                // Do not automatically fix the errors
        



    


    
  52. 
        
        


                "php_cs_fixer_on_save": false,
        



    


    
  53. 
        
        


            
        



    


    
  54. 
        
        


                // Show the fixes in the quick panel
        



    


    
  55. 
        
        


                "php_cs_fixer_show_quick_panel": true,
        



    


    
  56. 
        
        


            
        



    


    
  57. 
        
        


                // Path to where php-cs-fixer.phar is
        



    


    
  58. 
        
        


                "php_cs_fixer_executable_path": "/usr/local/bin/php-cs-fixer",
        



    


    
  59. 
        
        


            
        



    


    
  60. 
        
        


                // Run all levels of fixing
        



    


    
  61. 
        
        


                "php_cs_fixer_additional_args": {
        



    


    
  62. 
        
        


                },
        



    


    
  63. 
        
        


            
        



    


    
  64. 
        
        


            
        



    


    
  65. 
        
        


                // PHP Linter settings
        



    


    
  66. 
        
        


                // Lint each file
        



    


    
  67. 
        
        


                "phpcs_linter_run": true,
        



    


    
  68. 
        
        


            
        



    


    
  69. 
        
        


                // Execute the linter on save
        



    


    
  70. 
        
        


                "phpcs_linter_command_on_save": true,
        



    


    
  71. 
        
        


            
        



    


    
  72. 
        
        


                // Use the $PATH version of php
        



    


    
  73. 
        
        


                "phpcs_php_path": "/usr/local/bin/phpcs",
        



    


    
  74. 
        
        


            
        



    


    
  75. 
        
        


                // Regex for the errors the linter produces
        



    


    
  76. 
        
        


                "phpcs_linter_regex": "(?P.*) on line (?P\d+)",
        



    


    
  77. 
        
        


            
        



    


    
  78. 
        
        


            
        



    


    
  79. 
        
        


                // PHP Mess Detector settings
        



    


    
  80. 
        
        


                // Execute phpmd
        



    


    
  81. 
        
        


                "phpmd_run": true,
        



    


    
  82. 
        
        


            
        



    


    
  83. 
        
        


                // Execute the phpmd on file save
        



    


    
  84. 
        
        


                "phpmd_command_on_save": true,
        



    


    
  85. 
        
        


            
        



    


    
  86. 
        
        


                // Path to where the phpmd application is
        



    


    
  87. 
        
        


                "phpmd_executable_path": "/usr/local/bin/phpmd",
        



    


    
  88. 
        
        


            
        



    


    
  89. 
        
        


                // What args I want to pass to phpmd
        



    


    
  90. 
        
        


                "phpmd_additional_args": {
        



    


    
  91. 
        
        


                    "codesize,unusedcode,naming": ""
        



    


    
  92. 
        
        


                },
        



    


    
  93. 
        
        


            
        



    


    
  94. 
        
        


                // PHP Scheck settings
        



    


    
  95. 
        
        


                // Execute scheck
        



    


    
  96. 
        
        


                "scheck_run": false,
        



    


    
  97. 
        
        


            
        



    


    
  98. 
        
        


                // Execute the scheck on file save
        



    


    
  99. 
        
        


                "scheck_command_on_save": false,
        



    


    
  100. 
        
        


            
        



    


    
  101. 
        
        


                // It seems python/sublime cannot always find the scheck application
        



    


    
  102. 
        
        


                // If empty, then use PATH version of scheck, else use the set value
        



    


    
  103. 
        
        


                "scheck_executable_path": "",
        



    


    
  104. 
        
        


            
        



    


    
  105. 
        
        


                // Additional arguments you can specify into the application
        



    


    
  106. 
        
        


                "scheck_additional_args": {
        



    


    
  107. 
        
        


                    "-strict" : ""
        



    


    
  108. 
        
        


                }
        



    


    
  109. 
        
        


            }
        



    







4.完成


为知笔记图片

PS:如submit 出现报错,可显示调试信息调试具体问题 Ctrl+~;如再有问题,可联系我。
为知笔记图片

Golang Gateway API 搭建教程

随着微服务的兴起,行业里出现了非常多优秀的微服务网关框架,今天教大家搭建一套国人,用Golang写的微服务网关框架。

这里啰嗦一句,可能到今天还有人不理解什么是微服务,为什么要用微服务。目前网上相对比较模糊,没有精确的定义,但大家的意思都差不多,这里个人通俗描述,就是小项目发展到大项目过程中,出于已维护,与稳定性等考虑,将一个整体项目分为多个微小服务。

微服务网关的作用是在用户第一个网关服务器,你按照业务服务相关需求,给网关分流,相比云主机厂商提供的负载均衡器,强大在于你可以根据自己业务去分流,同时还以可以实现鉴权、校验、聚合、缓存等自定义服务,而云主机的负载均衡器只是一个简单按照流量给你负载均衡请求,不具有自定义编程性质。

接下来教如何安装,以及注意事项。

地址:

https://github.com/fagongzi/gateway

功能:

  • 流量控制
  • 熔断
  • 负载均衡
  • 服务发现
  • 插件机制
  • 路由(分流,复制流量)
  • API 聚合
  • API 参数校验
  • API 访问控制(黑白名单)
  • API 默认返回值
  • API 定制返回值
  • API 结果Cache
  • JWT Authorization
  • API Metric导入Prometheus
  • API 失败重试
  • 后端server的健康检查
  • 开放管理API(GRPC、Restful)
  • 支持websocket
  • 支持在线迁移数据

1.下载

https://github.com/fagongzi/gateway

2.编译

cd $GOPATH/src/github.com/fagongzi/gateway/cmd/proxy
go build -o proxy ./...

cd $GOPATH/src/github.com/fagongzi/gateway/cmd/api
go build -o apiserver ./...

3.ECTD安装

Etcd是一个高可用的 Key/Value 存储系统,主要用于分享配置和服务发现。

etcd github地址:

https://github.com/etcd-io/etcd

当然,你也可以用命令行安装

1、安装

yum install etcd

2、修改配置文件,主要是地址,如果不是很懂,可以看下etcd官方文档

vim /etc/etcd/etcd.conf 
# [member] ETCD_NAME="k8s_master_ip_name" 
#范例:
etcd1 
ETCD_DATA_DIR="/work/etcd" 
ETCD_LISTEN_PEER_URLS="http://k8s_master_ip:2380" 
ETCD_LISTEN_CLIENT_URLS="http://127.0.0.1:2379,http://k8s_master_ip:2379"

3、启动

systemctl daemon-reload 
systemctl enable etcd.service 
systemctl start etcd.service

4、测试

IP与端口改为配置的ip地址,如果没有使用,建议不要随意变动端口

curl http://127.0.0.1:2379/version 

如果返回{"etcdserver":"3.3.2","etcdcluster":"3.3.0"} 就是安装成功了

基础软件都安装好了,我们就准备最低三台机器。

运行环境

我们以三台etcd、一台ApiServer,三台Proxy的环境为例

环境信息

组件环境说明
etcd集群环境192.168.1.12配置服务器
Proxy192.168.1.13代理服务器
ApiServer192.168.1.14路由配置接口服务器

1.启动 ApiServer服务

启动ApiServer服务,看到以下截图就对了。

image.png

2.启动代理服务

看到以下截图就对了

image.png

3.添加配置

服务都启动后,我们添加配置路由。

启动Proxy

./proxy --addr=192.168.1.200:80 --addr-rpc=192.168.1.200:9091 --addr-store=etcd://192.168.1.100:2379,192.168.1.101:2379,192.168.1.102:2379 --namespace=test
./proxy --addr=192.168.1.201:80 --addr-rpc=192.168.1.201:9091 --addr-store=etcd://192.168.1.100:2379,192.168.1.101:2379,192.168.1.102:2379 --namespace=test
./proxy --addr=192.168.1.202:80 --addr-rpc=192.168.1.202:9091 --addr-store=etcd://192.168.1.100:2379,192.168.1.101:2379,192.168.1.102:2379 --namespace=test

用户的API接入地址可以为:192.168.1.201:80、192.168.1.201:80、192.168.1.202:80其中任意一个

如果能访问下你后面代理的接口内容,表示成功。

如果觉得配置服务器API,命令行麻烦,可以下载WEB UI的管理控制台。

下载地址:

https://github.com/fagongzi/gateway-ui-vue

最后大家有任何疑问,可以在本文章留言。

本教程演示如何使用向量检索服务(DashVector),结合上的[Embedding
API](https://help.aliyun.com/zh/dashscope/developer-reference/api-
details-15),来从0到1构建基于文本索引的构建+向量检索基础上的语义搜索能力。具体来说,我们将基于QQ 浏览器搜索标题语料库(:QQ
Browser Query Title Corpus)进行实时的文本语义搜索,查询{BANNED}{BANNED}最佳佳相似的相关标题。

什么是 Embedding

简单来说,Embedding是一个多维向量的表示数组,通常由一系列数字组成。Embedding可以用来表示任何数据,例如文本、音频、图片、视频等等,通过Embedding我们可以编码各种类型的非结构化数据,转化为具有语义信息的多维向量,并在这些向量上进行各种操作,例如相似度计算、聚类、分类和推荐等。

整体流程概述

70038568_1716522503fm4s.png

  • Embedding:通过DashScope提供的通用文本向量模型,对语料库中所有标题生成对应的embedding向量。
  • 构建索引服务和查询:

    • 通过DashVector向量检索服务对生成embedding向量构建索引。
    • 将查询文本embedding向量作为输入,通过DashVector搜索相似的标题。

具体操作流程

前提条件

1、环境安装

说明

需要提前安装 Python3.7 及以上版本,请确保相应的 python 版本。



pip3 install dashvector dashscope





2、数据准备

(QBQTC, QQ Browser Query Title Corpus),是QQ浏览器搜索引擎目前针对大搜场景构建的一个融合了相关性、权威性、内容质量、
时效性等维度标注的学习排序(LTR)数据集,广泛应用在搜索引擎业务场景中。作为CLUE-beanchmark的一部分,QBQTC
数据集可以直接从github上下载(训练集路径为dataset/train.json)。



git clone https://github.com/CLUEbenchmark/QBQTC.git
wc-l QBQTC/dataset/train.json




数据集中的训练集(train.json)其格式为 json:



{
"id":0,
"query":"小孩咳嗽感冒",
"title":"小孩感冒过后久咳嗽该吃什么药育儿问答宝宝树",
"label":"1"
}

我们将从这个数据集中提取title,方便后续进行embedding并构建检索服务。



import json

def prepare_data(path,size):
with open(path,'r',encoding='utf-8')as f:
batch_docs=[]
forlineinf:
batch_docs.append(json.loads(line.strip()))
iflen(batch_docs)==size:
yield batch_docs[:]
batch_docs.clear()

ifbatch_docs:
yield batch_docs




3、通过 DashScope 生成 Embedding 向量

DashScope灵积模型服务通过标准的API提供了多种模型服务。其中支持文本Embedding的模型中文名为通用文本向量,英文名为text-
embedding-v1。我们可以方便的通过DashScope API调用来获得一段输入文本的embedding向量。

说明

需要使用您的api-key替换示例中的 your-dashscope-api-key ,代码才能正常运行。



import dashscope
from dashscope import TextEmbedding

dashscope.api_key='{your-dashscope-api-key}'


def generate_embeddings(text):
rsp=TextEmbedding.call(model=TextEmbedding.Models.text_embedding_v1,
input=text)

embeddings=[record['embedding']forrecordinrsp.output['embeddings']]
return embeddingsifisinstance(text,list)elseembeddings[0]


# 查看下embedding向量的维数,后面使用 DashVector 检索服务时会用到,目前是1536
print(len(generate_embeddings('hello')))


4、通过 DashVector 构建检索:向量入库

DashVector
向量检索服务上的数据以集合(Collection)为单位存储,写入向量之前,我们首先需要先创建一个集合来管理数据集。创建集合的时候,需要指定向量维度,这里的每一个输入文本经过DashScope上的text_embedding_v1模型产生的向量,维度统一均为1536。

DashVector 除了提供向量检索服务外,还提供倒排过滤功能 和 scheme free
功能。所以我们为了演示方便,可以写入数据时,可以将title内容写入 DashVector 以便召回。写入数据还需要指定 id,我们可以直接使用 QBQTC
中id。

说明

需要使用您的api-key替换示例中的 your-dashvector-api-key ,以及您的Cluster Endpoint替换示例中的
your-dashvector-cluster-endpoint ,代码才能正常运行。



from dashvector import Client,Doc


# 初始化 DashVector client
client=Client(
api_key='{your-dashvector-api-key}',
endpoint='{your-dashvector-cluster-endpoint}'
)

# 指定集合名称和向量维度
rsp=client.create('sample',1536)
assert rsp

collection=client.get('sample')
assert collection

batch_size=10
fordocsinlist(prepare_data('QBQTC/dataset/train.json',batch_size)):
# 批量 embedding
embeddings=generate_embeddings([doc['title']fordocindocs])

# 批量写入数据
rsp=collection.insert(
[
Doc(id=str(doc['id']),vector=embedding,fields={"title":doc['title']})
fordoc,embeddinginzip(docs,embeddings)
]
)
assert rsp


5、语义检索:向量查询

在把QBQTC训练数据集里的title内容都写到DashVector服务上的集合里后,就可以进行快速的向量检索,实现“语义搜索”的能力。继续上面代码的例子,假如我们要搜索有多少和'应届生
招聘'相关的title内容,可以通过在DashVector上去查询'应届生 招聘',即可迅速获取与该查询语义相近的内容,以及对应内容与输入之间的相似指数。



# 基于向量检索的语义搜索
rsp=collection.query(generate_embeddings('应届生 招聘'),output_fields=['title'])

fordocinrsp.output:
print(f"id: {doc.id}, title: {doc.fields['title']}, score: {doc.score}")





id:0,title:实习生招聘-应届生求职网,score:2523.1582
id:6848,title:应届生求职网校园招聘yingjieshengcom中国领先的大学生求职网站,score:3053.7095
id:8935,title:北京招聘求职-前程无忧,score:5100.5684
id:5575,title:百度招聘实习生北京实习招聘,score:5451.4155
id:6500,title:中公教育招聘信息网-招聘岗位-近期职位信息-中公教育网,score:5656.128
id:7491,title:张家口招聘求职-前程无忧,score:5834.459
id:7520,title:前程无忧网北京前程无忧网招聘,score:5874.412
id:3214,title:乡镇卫生院招聘招聘乡镇卫生院招聘信息+-58同城,score:6005.207
id:6507,title:赶集网招聘实习生北京实习招聘,score:6424.9927
id:5431,title:实习内容安排百度文库,score:6505.735