配置各种环境

NodeJS

Windows

下载地址:官方网站

1
2
3
npm install cnpm -g --registry=https://registry.npm.taobao.org
# 如果计算机禁止脚本运行,执行下面步骤,选 A
set-ExecutionPolicy RemoteSigned

Python

PyTorch

下载torch和torchvision

1
https://download.pytorch.org/whl/torch_stable.html

安装

1
2
pip install /path_to_file/torch...
pip install /path_to_file/torchvision...

WSL

基本操作

可以到应用商店安装基于WSL的Ubuntu。下载安装完成后,可以通过命令切换到WSL 2。

1
2
wsl -l -v  # 查看安装的子系统
wsl --set-version Ubuntu-20.04 2 # 切换到WSL 2

查看所有安装的WSL:

1
cd \\wsl$

WSL2 Docker

更新系统到Windows 10 2004版本,打开WSL功能,下载安装WSL2补丁。升级成功后,安装Docker安装包即可。

可以去CUDA官网下载WSL CUDA驱动

迁移 WSL

1
2
3
4
wsl --shutdown  # 关闭WSL
wsl --export docker-desktop-data E:\docker-desktop-data.tar # 导出数据
wsl --unregister docker-desktop-data # 注销子系统
wsl --import docker-desktop-data D:\wsl\docker-desktop-data\ E:\docker-desktop-data.tar --version 2 # 重新挂载子系统到其他位置

开启 关闭 HyperV

1
2
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
Disable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform

VS Code

开发 C++

配置编译环境 MinGW-64

点击进入MinGW-64下载页面,下载完毕后,解压到一个固定的目录下,并将该目录的../bin目录添加至环境变量中。

打开CMD(或Power Shell)输入gcc测试环境是否配置成功。如果成功,则显示:

1
2
gcc: fatal error: no input files
compilation terminated.

下载 Visual Studio Code

点击下载Visual Studio Code,下载完毕后安装打开。进入程序后,在插件栏中安装Code RunC/C++两款插件。安装完毕后重启编辑器。

Tips: 可以安装一个Chinese插件可以进行汉化。

创建第一个项目

打开一个空文件夹,在其下面创建.vscode文件夹(注意有个点),依次点击菜单栏的调试->添加配置选项,添加一个C++(GDB/LLDB)配置,第二步选择g++.exe build and debug active file,之后会启动调试,并显示调试失败。这里点击取消,编辑器将自动创建launch.json文件和tasks.json文件,这个文件中可以配置启动程序和调试程序所需的相关内容。这两个文件默认情况下是不需要修改的。如果调试失败,可以参考如下两个配置文件进行修改。文件内容如下:

launch.json

1
{      "version": "0.2.0",      "configurations": [          {              "name": "(gdb) Launch", // 配置名称            "type": "cppdbg",       // 这里只能为cppdbg              "request": "launch",    // 请求配置类型,可以为launch(启动)或attach(附加)              "program": "${fileDirname}/${fileBasenameNoExtension}.exe",// 将要进行调试的程序的路径              "args": [],             // 程序调试时传递给程序的命令行参数,一般设为空即可              "stopAtEntry": false,   // 设为true时程序将暂停在程序入口处,一般设置为false              "cwd": "${workspaceFolder}", // 调试程序时的工作目录,一般为${workspaceFolder}即代码所在目录              "environment": [],              "externalConsole": true, // 调试时是否显示控制台窗口,一般设置为true显示控制台              "MIMode": "gdb",              "miDebuggerPath": "gdb.exe", // miDebugger的路径,注意这里要与MinGw的路径对应              "preLaunchTask": "g++", // 调试会话开始前执行的任务,一般为编译程序,c++为g++, c为gcc              "setupCommands": [                  {   		    "description": "Enable pretty-printing for gdb",                      "text": "-enable-pretty-printing",                      "ignoreFailures": true                  }              ]          }      ]  }

tasks.json

1
{    // See https://go.microsoft.com/fwlink/?LinkId=733558     // for the documentation about the tasks.json format    "version": "2.0.0",    "tasks": [        {            "type": "shell",            "label": "g++",            "command": "g++.exe",            "args": [                   "-g",                "${file}",                "-o",                "${fileDirname}\\${fileBasenameNoExtension}.exe"            ],            "options": {                "cwd": ""            },            "problemMatcher": [                "$gcc"            ]        }    ]}

配置完成后,添加一个简单的CPP文件,分别调试、直接运行一次测试功能是否正确。如果发现不能调试程序,可尝试重启编辑器。

main.cpp

1
#include <iostream>int main(void){    std::cout<<"Hello World..."<<std::endl;    return 0;}

安装插件Code Runner,配置参数为Run in Terminal

Web 版 VS Code

首先确保安装yarn

1
npm config set registry https://registry.npm.taobao.org/npm i -g yarnyarn config set registry https://registry.npm.taobao.org/

下载安装运行代码(Windows 下):

1
git clone --depth 1 https://github.com/microsoft/vscode.gitcd vscodeyarnyarn watchyarn gulp watch-web  yarn web

(Linux下,Code Server):

1
git clone --depth 1 https://github.com/cdr/code-server.gitcd code-serversudo ./install.shsudo code-server --bind-addr 0.0.0.0:8080 --auth none

VS Code + Docker

在Docker服务器上,修改文件/lib/systemd/system/docker.service

1
ExecStart=/usr/bin/dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375

再重启Docker

1
systemctl daemon-reloadsystemctl restart docker

在VS Code上安装Docker插件,打开设置,搜索docker:host,配置远程服务器。

1
tcp://192.168.1.101:2375

打开Remote Container,使用Try a Sample开启远程Docker。

VS Code 远程开发

开启OpenSSH服务,并在VS Code中安装插件:

1
Remote - SSHRemote - WSLRemote - Container

完成后,在左侧远程资源管理器中添加远程主机。

1
ssh user@host

并提示保存config文件。如果需要密钥,可以用ssh-add添加密钥。

OpenCV

OpenCV CMake 编译

使用CMake进行MingW编译。需要安装CMakeMingW-w64(QT自带)或MSVC(Visual Studio 20xx)。

选择源程序目录Source和输出目录Build,点击Configure,选择MinGW Makefiles,选择Finish,等待完成。

完成后,添加或修改如下选项:

1
BUILD_opencv_world             ONCMAKE_PREFIX_PATH              D:\Qt\5.14.2\mingw73_64\lib\cmake\Qt5   # 如果是MSVC则不需要CMAKE_BUILD_TYPE               Debug                                   # 如果是MSVC则不需要OPENCV_ENABLE_ALLOCATOR_STATS  OFFWITH_OPENGL                    ONWITH_QT                        ON                                      # 如果使用 QT 就打开

点击Generate

待生成后,如果是Mingw,则使用命令行进入Build目录,输入指令:

1
D:\Qt\Tools\mingw730_64\bin\mingw32-make.exe -j 4D:\Qt\Tools\mingw730_64\bin\mingw32-make.exe install

注意,为了防止混淆,这里尽量使用完整的make程序的路径,因为还存在mingw730_32的32位编译器。

如果是MSVC,则打开OpenCV.sln,在上方选择Debug或是Release,再右键解决方案,点击生成。生成后,右键Install,生成即可安装。

如果出现File Too Big错误,可以修改相应的文件,如D:\OpenCV4\opencv\build-mingw\modules\core\CMakeFiles\opencv_perf_core.dir\flags.make

1
CXX_FLAGS = -Wa,-mbig-obj ...

或直接修改OpenCV源代码中的CMakeFiles.txt

1
# ========================== C/C++ options ==========================if(CMAKE_COMPILER_IS_GNUCXX)    add_compile_options(-Wa,-mbig-obj)endif(CMAKE_COMPILER_IS_GNUCXX)

OpenCV + Visual Stuido

打开项目属性,编辑如下选项:

配置:Debug;平台:x64

调试 -> 环境:PATH=D:\OpenCV4\opencv\build\x64\vc15\bin;%PATH%,即配置OpenCV的环境变量。

VC++目录:

  • 包含目录:
1
D:\OpenCV4\opencv\build\includeD:\OpenCV4\opencv\build\include\opencv2
  • 库目录:
1
D:\OpenCV4\opencv\build\x64\vc15\lib

连接器 -> 输入 -> 附加依赖项:opencv_world430d.lib
如果配置的是Release,则输入opencv_world430.lib

OpenCV + QT + MingW

打开QT,新建工程,在.PRO文件中加入

1
INCLUDEPATH += D:\OpenCV4\opencv\build-mingw\install\include\INCLUDEPATH += D:\OpenCV4\opencv\build-mingw\install\include\opencv2LIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_core430.dllLIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_highgui430.dllLIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_imgcodecs430.dllLIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_imgproc430.dllLIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_features2d430.dllLIBS += D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\libopencv_calib3d430.dll

之后构建程序并执行。如果出现程序无法打开,则可以做如下两种方案解决问题。
方案 1:将D:\OpenCV4\opencv\build-mingw\install\x64\mingw\bin\目录添加到环境变量下(可以在QT中设置项目独立环境变量:项目->构建环境)。
方案 2:将用到的DLL文件复制到\build-xxxx-Desktop_Qt_5_14_2_MinGW_64_bit-Debug\debug目录下。

Vagrant

开机脚本

1
# Version Ubuntu 16.04sudo mv /etc/apt/sources.list /etc/apt/sources.list.backsudo cat>>/etc/apt/sources.list<<EOF# deb cdrom:[Ubuntu 16.04 LTS _Xenial Xerus_ - Release amd64 (20160420.1)]/ xenial main restricteddeb-src http://archive.ubuntu.com/ubuntu xenial main restricted #Added by software-propertiesdeb http://mirrors.aliyun.com/ubuntu/ xenial main restricteddeb-src http://mirrors.aliyun.com/ubuntu/ xenial main restricted multiverse universe #Added by software-propertiesdeb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricteddeb-src http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted multiverse universe #Added by software-propertiesdeb http://mirrors.aliyun.com/ubuntu/ xenial universedeb http://mirrors.aliyun.com/ubuntu/ xenial-updates universedeb http://mirrors.aliyun.com/ubuntu/ xenial multiversedeb http://mirrors.aliyun.com/ubuntu/ xenial-updates multiversedeb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiversedeb-src http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse #Added by software-propertiesdeb http://archive.canonical.com/ubuntu xenial partnerdeb-src http://archive.canonical.com/ubuntu xenial partnerdeb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricteddeb-src http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted multiverse universe #Added by software-propertiesdeb http://mirrors.aliyun.com/ubuntu/ xenial-security universedeb http://mirrors.aliyun.com/ubuntu/ xenial-security multiverseEOFsudo apt-get updatecurl -sSL https://get.docker.com | shsudo cat>>/etc/docker/daemon.json<<EOF{  "registry-mirrors": ["https://sfpj1t4c.mirror.aliyuncs.com"]}EOFsudo systemctl daemon-reloadsudo systemctl restart dockersudo apt-get install -y docker-compose

Boost

下载Boost,解压到某一路径。

为VS 2019编译,使用x86_x64 Cross Tools Command Prompt for VS 2019工具,打开解压目录,运行bootstrap.bat,创建编译文件。
创建完成后执行指令:

1
b2.exe --toolset=msvc-14.1 architecture=x86 address-model=64 link=static --build-type=complete --with-system --with-thread --with-date_time --with-filesystem --with-serialization

如果为QT编译,则直接用命令行打开,输入:

1
bootstrap.bat gcc# 等待完成后输入b2.exe --toolset=gcc architecture=x86 address-model=64 link=static --build-type=complete --with-system --with-thread --with-date_time --with-filesystem --with-serialization

编译完成即可。

之后将Boost加入到环境变量(%BOOST_DIR%)。

Visual Studio 中:
VC++包含目录中添加: %BOOST_DIR%;
VC++库目录中添加: %BOOST_DIR%\stage\lib;

QT 中:
INCLUDEPATH += %BOOST_DIR%/bin/include
LIBS += %BOOST_DIR%/bin/lib/libboost_regex-mgw49-mt-1_56.a

MSYS2

下载MSYS2,并安装。
配置环境变量到Path:

1
C:\msys64C:\msys64\usr\bin

修改如下文件:
C:\msys64\etc\pacman.d\mirrorlist.mingw32
C:\msys64\etc\pacman.d\mirrorlist.mingw64
C:\msys64\etc\pacman.d\mirrorlist.msys

1
## mirrorlist.mingw32#### 32-bit Mingw-w64 repository mirrorlist#### 清华大学软件镜像Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/i686/## 中科大镜像Server = http://mirrors.ustc.edu.cn/msys2/mingw/i686/## msys2.orgServer = http://repo.msys2.org/mingw/i686/## Sourceforge 镜像Server = https://sourceforge.net/projects/msys2/files/REPOS/MINGW/i686/## The UK Mirror Service Sourceforge mirrorServer = http://sourceforge.mirrorservice.org/m/ms/msys2/REPOS/MINGW/i686/## Sourceforge.netServer = http://downloads.sourceforge.net/project/msys2/REPOS/MINGW/i686## FutureAt 镜像Server = http://www2.futureware.at/~nickoe/msys2-mirror/msys/i686/## mirrorlist.mingw64#### 64-bit Mingw-w64 repository mirrorlist#### 清华大学软件镜像Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64/## 中科大镜像Server = http://mirrors.ustc.edu.cn/msys2/mingw/x86_64/## msys2.orgServer = http://repo.msys2.org/mingw/x86_64/## Sourceforge 镜像Server = https://sourceforge.net/projects/msys2/files/REPOS/MINGW/x86_64/## The UK Mirror Service Sourceforge mirrorServer = http://sourceforge.mirrorservice.org/m/ms/msys2/REPOS/MINGW/x86_64/## Sourceforge.netServer = http://downloads.sourceforge.net/project/msys2/REPOS/MINGW/x86_64## FutureAt 镜像Server = http://www2.futureware.at/~nickoe/msys2-mirror/msys/x86_64/## mirrorlist.msys#### MSYS2 repository mirrorlist#### 清华大学软件镜像Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/msys/$arch## 中科大镜像Server = http://mirrors.ustc.edu.cn/msys2/msys/$arch## msys2.orgServer = http://repo.msys2.org/msys/$arch## Sourceforge 镜像Server = https://sourceforge.net/projects/msys2/files/REPOS/msys/$arch## The UK Mirror Service Sourceforge mirrorServer = http://sourceforge.mirrorservice.org/m/ms/msys2/REPOS/msys/$arch## Sourceforge.netServer = http://downloads.sourceforge.net/project/msys2/REPOS/msys/$arch## FutureAt 镜像Server = http://www2.futureware.at/~nickoe/msys2-mirror/msys/$arch

更新软件包:

1
pacman -Sypacman -Su

搜索软件包

1
pacman -Sl | grep git

安装Git:

1
pacman -S git

Windows Clang

  1. 下载Clang-LLVM for Windows,安装后添加到环境变量Path中。
  2. 安装MinGW-w64,添加bin目录到环境变量Path中。
  3. 或使用MSVC。
  4. 使用Clang编译程序。
1
clang++ -target x86_64-pc-windows-mingw 

前后端分离开发

整体架构

Docker

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
# Use root/example as user/password credentials
version: '2'

services:

django:
image: python:3.8
restart: always
ports:
- 8000:8000
working_dir: /usr/src/app
environment:
DJANGO_DATABASE: backend
DJANGO_DATABASE_HOST: db
DJANGO_DATABASE_PORT: 3306
DJANGO_DATABASE_PSWD: root
volumes:
- ./django:/usr/src/app
command: bash -c "pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
links:
- db

db:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: backend
ports:
- 3306:3306
volumes:
- ~/sql_django:/var/lib/mysql

nginx:
image: nginx
restart: always
ports:
- 80:80
volumes:
- ./vue:/usr/share/nginx/html
- ./vue_conf/nginx.conf:/etc/nginx/nginx.conf

adminer:
image: adminer
restart: always
ports:
- 9080:8080

Django

配置开发环境中的环境变量

在PyCharm中的Edit Configurations中,修改Environment Variables,添加环境变量。这样在Docker中就可以使用environment选项配置环境了。

在Python文件中,使用如下方式载入环境变量。

1
2
3
4
5
6
7
import os

DJANGO_API = os.getenv('DJANGO_API')
DJANGO_DATABASE = os.getenv('DJANGO_DATABASE')
DJANGO_DATABASE_HOST = os.getenv('DJANGO_DATABASE_HOST')
DJANGO_DATABASE_PORT = os.getenv('DJANGO_DATABASE_PORT')
DJANGO_DATABASE_PSWD = os.getenv('DJANGO_DATABASE_PSWD')

Vue

配置Vue Cli开发环境与生产环境文件

创建.env.production.env.development,用于存放两种环境下的配置参数。

.env.production

1
2
3
NODE_ENV = 'development'
VUE_APP_MODE = 'development'
VUE_APP_API_URL = 'http://127.0.0.1:8000/'

.env.development

1
2
3
NODE_ENV = 'production'
VUE_APP_MODE = 'production'
VUE_APP_API_URL = ''

在Js文件中,通过下面的方式可以区分两种运行环境。

1
let mode = process.env.VUE_APP_MODE

虚拟后端

1
2
npm i axios 
npm i mockjs

通过配置Mock可以实现模拟后端反馈数据。
首先配置axios模块,实现请求和响应拦截。

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
import axios from 'axios'
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = ''

if (process.env.VUE_APP_MODE == 'development') {
// 请求拦截器
axios.interceptors.request.use(config => {
const token = localStorage.getItem('userToken');
if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.accessToken = token;
}
return config;
},
error => {
return Promise.reject(error);
})
// 响应拦截器
axios.interceptors.response.use(response => {
return response;
},
error => {
return Promise.reject(error);
})
}
export default axios

创建mock.js文件,编写模拟后端接口。

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
/* eslint-disable no-unused-vars */
import Mock from 'mockjs';
// 配置拦截 ajax 的请求时的行为,支持的配置项目有 timeout。
Mock.setup({
timeout: '200 - 300'
})

// const vCode = '123456';
// function getVerificatCode(prarms) {
// const prarmsObj = JSON.parse(prarms.body);
// return Object.assign(prarmsObj, { vCode: vCode });
// }
// function loginFun(prarms) {
// const prarmsObj = JSON.parse(prarms.body);
// if (prarmsObj.code === vCode) {
// return { code: 1, text: '登录成功' }
// } else {
// return { code: 2, text: '验证码有误,登录失败' }
// }
// }

let raw_device_list = {
device_list: [
{ "id": "1001", "ip": '192.168.3.101', "status": true, "auto": true, 'comment': '院子里那个' },
{ "id": "1002", "ip": '192.168.3.102', "status": false, "auto": true, 'comment': '屋子里那个' },
{ "id": "2004", "ip": '192.168.3.123', "status": true, "auto": null },
{ "id": "3002", "ip": '192.168.3.132', "status": true, "auto": true },
]
}

let raw_device_data = {
'1001': [
{ time: '2020-06-09T11:11:03.841', value: 10 },
{ time: '2020-06-09T11:12:03.841', value: 20 },
{ time: '2020-06-09T12:13:03.841', value: 30 },
],
'1002': [
{ time: '2020-06-09T13:11:03.841', value: 10 },
{ time: '2020-06-09T13:12:03.841', value: 40 },
{ time: '2020-06-09T13:13:03.841', value: 20 },
],
}
function device_list() {
// const prarmsObj = JSON.parse(prarms.body);

return raw_device_list
}
function device_add(param) {
// eslint-disable-next-line no-unused-vars
const paramObj = JSON.parse(param.body);

console.log(paramObj)
return param
}
if (process.env.VUE_APP_MODE == 'development') {
// Mock.mock( url, post/get , 返回的数据);
Mock.mock('/api/device/list', 'get', device_list);
Mock.mock('/api/device/add', 'post', device_add);
}

main.js

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
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import Video from 'video.js'
import axios from './axios/axios'

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'video.js/dist/video-js.css'


require('./mocks/mock.js')

Vue.use(BootstrapVue)
Vue.use(IconsPlugin)
Vue.prototype.$video = Video
Vue.prototype.axios = axios
Vue.config.productionTip = false




new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

Nginx

配置Nginx,用于耦合前后端程序。为了防止出现跨域,可以通过反向代理设置后端到前端接口上。

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
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
gzip on;
gzip_min_length 5k;
gzip_buffers 4 16k;
#gzip_http_version 1.0;
gzip_comp_level 3;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
server {
listen 80;
server_name nginx;
# 前端
location / {
index index.html index.htm; #添加属性。
root /usr/share/nginx/html; #站点目录
}
# 后端,反向代理
location /api/ {
proxy_pass http://django:8000/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}