This commit is contained in:
李博 2019-05-19 09:49:40 +08:00
commit 3ef680240c
23 changed files with 1282 additions and 1229 deletions

View File

@ -1,16 +1,18 @@
[#]: collector: (lujun9972)
[#]: translator: (MjSeven)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10867-1.html)
[#]: subject: (Building scalable social media sentiment analysis services in Python)
[#]: via: (https://opensource.com/article/19/4/social-media-sentiment-analysis-python-scalable)
[#]: author: (Michael McCune https://opensource.com/users/elmiko/users/jschlessman)
使用 Python 构建可扩展的社交媒体情感分析服务
======
学习如何使用 spaCy、vaderSentiment、Flask 和 Python 来为你的工作添加情感分析能力。
![Tall building with windows][1]
> 学习如何使用 spaCy、vaderSentiment、Flask 和 Python 来为你的作品添加情感分析能力。
![Tall building with windows](https://img.linux.net.cn/data/attachment/album/201905/17/235241zr0cs4czu4psmrl6.jpg)
本系列的[第一部分][2]提供了情感分析工作原理的一些背景知识,现在让我们研究如何将这些功能添加到你的设计中。
@ -20,7 +22,7 @@
* 一个终端 shell
* shell 中的 Python 语言二进制文件3.4+ 版本)
* 用于安装 Python 包的 **pip** 命令
* 用于安装 Python 包的 `pip` 命令
* (可选)一个 [Python 虚拟环境][3]使你的工作与系统隔离开来
#### 配置环境
@ -53,33 +55,44 @@ Type "help", "copyright", "credits" or "license" for more information.
>>>
```
_(你的 Python 解释器版本打印可能与此不同。)_
*(你的 Python 解释器版本打印可能与此不同。)*
1. 导入所需模块:
```
>>> import spacy
>>> from vaderSentiment import vaderSentiment
```
2. 从 spaCy 加载英语语言模型:
```
>>> english = spacy.load("en_core_web_sm")
```
3. 处理一段文本。本例展示了一个非常简单的句子,我们希望它能给我们带来些许积极的情感:
```
>>> result = english("I like to eat applesauce with sugar and cinnamon.")
```
4. 从处理后的结果中收集句子。SpaCy 已识别并处理短语中的实体,这一步为每个句子生成情感(即时在本例中只有一个句子):
```
>>> sentences = [str(s) for s in result.sents]
```
5. 使用 vaderSentiments 创建一个分析器:
```
>>> analyzer = vaderSentiment.SentimentIntensityAnalyzer()
```
6. 对句子进行情感分析:
```
>>> sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]
```
1、导入所需模块
```
>>> import spacy
>>> from vaderSentiment import vaderSentiment
```
2、从 spaCy 加载英语语言模型:
```
>>> english = spacy.load("en_core_web_sm")
```
3、处理一段文本。本例展示了一个非常简单的句子我们希望它能给我们带来些许积极的情感
```
>>> result = english("I like to eat applesauce with sugar and cinnamon.")
```
4、从处理后的结果中收集句子。SpaCy 已识别并处理短语中的实体,这一步为每个句子生成情感(即时在本例中只有一个句子):
```
>>> sentences = [str(s) for s in result.sents]
```
5、使用 vaderSentiments 创建一个分析器:
```
>>> analyzer = vaderSentiment.SentimentIntensityAnalyzer()
```
6、对句子进行情感分析
```
>>> sentiment = [analyzer.polarity_scores(str(s)) for s in sentences]
```
`sentiment` 变量现在包含例句的极性分数。打印出这个值,看看它是如何分析这个句子的。
@ -90,7 +103,7 @@ _(你的 Python 解释器版本打印可能与此不同。)_
这个结构是什么意思?
表面上,这是一个只有一个字典对象的数组。如果有多个句子,那么每个句子都会对应一个字典对象。字典中有四个键对应不同类型的情感。**neg** 键表示负面情感,因为在本例中没有报告任何负面情感,**0.0** 值证明了这一点。**neu** 键表示中性情感,它的得分相当高,为**0.737**(最高为 **1.0**)。**pos** 键代表积极情感,得分适中,为 **0.263**。最后,**cmpound** 键代表文本的总体得分,它可以从负数到正数,**0.3612** 表示积极方面的情感多一点。
表面上,这是一个只有一个字典对象的数组。如果有多个句子,那么每个句子都会对应一个字典对象。字典中有四个键对应不同类型的情感。`neg` 键表示负面情感,因为在本例中没有报告任何负面情感,`0.0` 值证明了这一点。`neu` 键表示中性情感,它的得分相当高,为 `0.737`(最高为 `1.0`)。`pos` 键代表积极情感,得分适中,为 `0.263`。最后,`cmpound` 键代表文本的总体得分,它可以从负数到正数,`0.3612` 表示积极方面的情感多一点。
要查看这些值可能如何变化,你可以使用已输入的代码做一个小实验。以下代码块显示了如何对类似句子的情感评分的评估。
@ -113,9 +126,9 @@ _(你的 Python 解释器版本打印可能与此不同。)_
#### 前提条件
* 一个终端 shell
* shell 中的 Python 语言二进制文件3.4+版本)
* 安装 Python 包的 **pip** 命令
* **curl** 命令
* shell 中的 Python 语言二进制文件3.4+ 版本)
* 安装 Python 包的 `pip` 命令
* `curl` 命令
* 一个文本编辑器
* (可选) 一个 [Python 虚拟环境][3]使你的工作与系统隔离开来
@ -123,19 +136,21 @@ _(你的 Python 解释器版本打印可能与此不同。)_
这个环境几乎与上一节中的环境相同,唯一的区别是在 Python 环境中添加了 Flask 包。
1. 安装所需依赖项:
```
pip install spacy vaderSentiment flask
```
2. 安装 spaCy 的英语语言模型:
```
python -m spacy download en_core_web_sm
```
1、安装所需依赖项
```
pip install spacy vaderSentiment flask
```
2、安装 spaCy 的英语语言模型:
```
python -m spacy download en_core_web_sm
```
#### 创建应用程序文件
打开编辑器,创建一个名为 **app.py** 的文件。添加以下内容 _不用担心我们将解释每一行_ :
打开编辑器,创建一个名为 `app.py` 的文件。添加以下内容 *(不用担心,我们将解释每一行)*
```
@ -179,10 +194,9 @@ analyzer = vader.SentimentIntensityAnalyzer()
english = spacy.load("en_core_web_sm")
```
接下来的三行代码创建了一些全局变量。第一个变量 **app**,它是 Flask 用于创建 HTTP 路由的主要入口点。第二个变量 **analyzer** 与上一个示例中使用的类型相同,它将用于生成情感分数。最后一个变量 **english** 也与上一个示例中使用的类型相同,它将用于注释和标记初始文本输入。
你可能想知道为什么全局声明这些变量。对于 **app** 变量,这是许多 Flask 应用程序的标准过程。但是,对于 **analyzer****english** 变量,将它们设置为全局变量的决定是基于与所涉及的类关联的加载时间。虽然加载时间可能看起来很短,但是当它在 HTTP 服务器的上下文中运行时,这些延迟会对性能产生负面影响。
接下来的三行代码创建了一些全局变量。第一个变量 `app`,它是 Flask 用于创建 HTTP 路由的主要入口点。第二个变量 `analyzer` 与上一个示例中使用的类型相同,它将用于生成情感分数。最后一个变量 `english` 也与上一个示例中使用的类型相同,它将用于注释和标记初始文本输入。
你可能想知道为什么全局声明这些变量。对于 `app` 变量,这是许多 Flask 应用程序的标准过程。但是,对于 `analyzer``english` 变量,将它们设置为全局变量的决定是基于与所涉及的类关联的加载时间。虽然加载时间可能看起来很短,但是当它在 HTTP 服务器的上下文中运行时,这些延迟会对性能产生负面影响。
```
def get_sentiments(text):
@ -192,8 +206,7 @@ def get_sentiments(text):
return sentiments
```
这部分是服务的核心 -- 一个用于从一串文本生成情感值的函数。你可以看到此函数中的操作对应于你之前在 Python 解释器中运行的命令。这里它们被封装在一个函数定义中,**text** 源作为文本变量传入,最后 **sentiments** 变量返回给调用者。
这部分是服务的核心 —— 一个用于从一串文本生成情感值的函数。你可以看到此函数中的操作对应于你之前在 Python 解释器中运行的命令。这里它们被封装在一个函数定义中,`text` 源作为文本变量传入,最后 `sentiments` 变量返回给调用者。
```
@app.route("/", methods=["POST", "GET"])
@ -206,11 +219,11 @@ def index():
return flask.json.dumps(sentiments)
```
源文件的最后一个函数包含了指导 Flask 如何为服务配置 HTTP 服务器的逻辑。它从一行开始,该行将 HTTP 路由 **/** 与请求方法 **POST****GET** 相关联。
源文件的最后一个函数包含了指导 Flask 如何为服务配置 HTTP 服务器的逻辑。它从一行开始,该行将 HTTP 路由 `/` 与请求方法 `POST``GET` 相关联。
在函数定义行之后,**if** 子句将检测请求方法是否为 **GET**。如果用户向服务发送此请求,那么下面的行将返回一条指示如何访问服务器的文本消息。这主要是为了方便最终用户。
在函数定义行之后,`if` 子句将检测请求方法是否为 `GET`。如果用户向服务发送此请求,那么下面的行将返回一条指示如何访问服务器的文本消息。这主要是为了方便最终用户。
下一行使用 **flask.request** 对象来获取请求的主体,该主体应包含要处理的文本字符串。**decode** 函数将字节数组转换为可用的格式化字符串。经过解码的文本消息被传递给 **get_sentiments** 函数以生成情感分数。最后,分数通过 HTTP 框架返回给用户。
下一行使用 `flask.request` 对象来获取请求的主体,该主体应包含要处理的文本字符串。`decode` 函数将字节数组转换为可用的格式化字符串。经过解码的文本消息被传递给 `get_sentiments` 函数以生成情感分数。最后,分数通过 HTTP 框架返回给用户。
你现在应该保存文件,如果尚未保存,那么返回 shell。
@ -222,7 +235,7 @@ def index():
FLASK_APP=app.py flask run
```
现在,你将在 shell 中看到来自服务器的一些输出,并且服务器将处于运行状态。要测试服务器是否正在运行,你需要打开第二个 shell 并使用 **curl** 命令。
现在,你将在 shell 中看到来自服务器的一些输出,并且服务器将处于运行状态。要测试服务器是否正在运行,你需要打开第二个 shell 并使用 `curl` 命令。
首先,输入以下命令检查是否打印了指令信息:
@ -252,11 +265,11 @@ curl http://localhost:5000 --header "Content-Type: application/json" --data "I l
### 继续探索
现在你已经了解了自然语言处理和情感分析背后的原理和机制,下面是进一步发现探索主题的一些方法。
现在你已经了解了自然语言处理和情感分析背后的原理和机制,下面是进一步发现探索主题的一些方法。
#### 在 OpenShift 上创建流式情感分析器
虽然创建本地应用程序来研究情绪分析很方便,但是接下来需要能够部署应用程序以实现更广泛的用途。按照[ Radnaalytics.io][11] 提供的指导和代码进行操作,你将学习如何创建一个情感分析仪,可以集装箱化并部署到 Kubernetes 平台。你还将了解如何将 APache Kafka 用作事件驱动消息传递的框架,以及如何将 Apache Spark 用作情绪分析的分布式计算平台。
虽然创建本地应用程序来研究情绪分析很方便,但是接下来需要能够部署应用程序以实现更广泛的用途。按照[Radnaalytics.io][11] 提供的指导和代码进行操作,你将学习如何创建一个情感分析仪,可以容器化并部署到 Kubernetes 平台。你还将了解如何将 Apache Kafka 用作事件驱动消息传递的框架,以及如何将 Apache Spark 用作情绪分析的分布式计算平台。
#### 使用 Twitter API 发现实时数据
@ -266,17 +279,17 @@ curl http://localhost:5000 --header "Content-Type: application/json" --data "I l
via: https://opensource.com/article/19/4/social-media-sentiment-analysis-python-scalable
作者:[Michael McCune ][a]
作者:[Michael McCune][a]
选题:[lujun9972][b]
译者:[MjSeven](https://github.com/MjSeven)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/elmiko/users/jschlessman
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/windows_building_sky_scale.jpg?itok=mH6CAX29 (Tall building with windows)
[2]: https://opensource.com/article/19/4/social-media-sentiment-analysis-python-part-1
[2]: https://linux.cn/article-10852-1.html
[3]: https://virtualenv.pypa.io/en/stable/
[4]: https://pypi.org/project/spacy/
[5]: https://pypi.org/project/vaderSentiment/

View File

@ -1,18 +1,18 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: (wxy)
[#]: publisher: ( )
[#]: url: ( )
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10864-1.html)
[#]: subject: (Format Python however you like with Black)
[#]: via: (https://opensource.com/article/19/5/python-black)
[#]: author: (Moshe Zadka https://opensource.com/users/moshez/users/moshez/users/moshez)
使用 Black 随意格式化 Python
使用 Black 自由格式化 Python
======
> 在我们覆盖 7 个 PyPI 库的系列文章中了解解决 Python 问题的更多信息。
![OpenStack source code \(Python\) in VIM][1]
![OpenStack source code \(Python\) in VIM](https://img.linux.net.cn/data/attachment/album/201905/16/220249ethkikh5h1uib5iy.jpg)
Python 是当今使用最多的[流行编程语言][2]之一,因为:它是开源的,它有广泛的用途(例如 Web 编程、业务应用、游戏、科学编程等等),它有一个充满活力和专注的社区支持它。这个社区可以让我们在 [Python Package Index][3]PyPI中有如此庞大、多样化的软件包用以扩展和改进 Python 并解决不可避免的问题。
@ -83,10 +83,10 @@ $ echo $?
via: https://opensource.com/article/19/5/python-black
作者:[Moshe Zadka ][a]
作者:[Moshe Zadka][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@ -1,26 +1,27 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: reviewer: (wxy)
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Say goodbye to boilerplate in Python with attrs)
[#]: via: (https://opensource.com/article/19/5/python-attrs)
[#]: author: (Moshe Zadka https://opensource.com/users/moshez/users/moshez)
[#]: author: (Moshe Zadka https://opensource.com/users/moshez/users/moshez)
使用 attrs 来告别 Python 中的样板
======
在我们覆盖 7 个 PyPI 库的系列文章中了解更多解决 Python 问题的信息。
![Programming at a browser, orange hands][1]
Python是当今使用最多[流行的编程语言] [2]之一 - 并且有充分的理由它是开源的它具有广泛的用途例如Web编程业务应用程序游戏科学编程等等更多它有一个充满活力和专注的社区支持它。这个社区是我们在[Python Package Index] [3]PyPI中提供如此庞大多样化的软件包的原因以扩展和改进Python并解决不可避免的问题
> 在我们覆盖 7 个 PyPI 库的系列文章中了解更多解决 Python 问题的信息。
在本系列中,我们将介绍七个可以帮助你解决常见 Python 问题的 PyPI 库。今天,我们将研究 [**attrs**][4],这是一个帮助你快速编写简洁,正确的代码的 Python 包。
![Programming at a browser, orange hands](https://img.linux.net.cn/data/attachment/album/201905/18/211211lhqqbemqwkeqc2bb.jpg)
Python是当今使用最多[流行的编程语言][2]之一,因为:它是开源的,它具有广泛的用途(例如 Web 编程、业务应用、游戏、科学编程等等),它有一个充满活力和专注的社区支持它。这个社区是我们在 [Python Package Index][3]PyPI中提供如此庞大、多样化的软件包的原因用以扩展和改进 Python。并解决不可避免的问题。
在本系列中,我们将介绍七个可以帮助你解决常见 Python 问题的 PyPI 库。今天,我们将研究 [attrs][4],这是一个帮助你快速编写简洁、正确的代码的 Python 包。
### attrs
如果你已经写过一段时间的 Python那么你可能习惯这样写代码
```
class Book(object):
@ -30,7 +31,7 @@ class Book(object):
self.author = author
```
接着写一个 **__repr__** 函数。否则,很难记录 **Book** 的实例:
接着写一个 `__repr__` 函数。否则,很难记录 `Book` 的实例:
```
@ -38,11 +39,10 @@ def __repr__(self):
return f"Book({self.isbn}, {self.name}, {self.author})"
```
接下来你会写一个好看的 docstring 来记录期望的类型。但是你注意到你忘了添加 **edition****published_year** 属性,所以你必须在五个地方修改它们。
接下来你会写一个好看的 docstring 来记录期望的类型。但是你注意到你忘了添加 `edition``published_year` 属性,所以你必须在五个地方修改它们。
如果你不必这么做如何?
```
@attr.s(auto_attribs=True)
class Book(object):
@ -53,11 +53,10 @@ class Book(object):
edition: int
```
使用新的类型注释语法注释类型属性,**attrs** 会检测注释并创建一个类。
使用新的类型注释语法注释类型属性,`attrs` 会检测注释并创建一个类。
ISBN 有特定格式。如果我们想强行使用该格式怎么办?
```
@attr.s(auto_attribs=True)
class Book(object):
@ -73,14 +72,14 @@ class Book(object):
edition: int
```
**attrs** 库也对[不可变风格编程][5]支持良好。将第一行改成 **@attr.s(auto_attribs=True, frozen=True)** 意味着 **Book** 现在是不可变的:尝试修改一个属性将会引发一个异常。相反,比如,如果希望将发布日期向后一年,我们可以修改成 **attr.evolve(old_book, published_year=old_book.published_year+1)** 来得到一个_新的_实例。
`attrs` 库也对[不可变式编程][5]支持良好。将第一行改成 `@attr.s(auto_attribs=True, frozen=True)` 意味着 `Book` 现在是不可变的:尝试修改一个属性将会引发一个异常。相反,比如,如果希望将发布日期向后一年,我们可以修改成 `attr.evolve(old_book, published_year=old_book.published_year+1)` 来得到一个*新的*实例。
本系列的下一篇文章我们将来看下 **singledispatch**,一个能让你向 Python 库添加方法的库。
本系列的下一篇文章我们将来看下 `singledispatch`,一个能让你向 Python 库添加方法的库。
#### 查看本系列先前的文章
* [Cython][6]
* [Black][7]
* [Cython][6]
* [Black][7]
@ -88,10 +87,10 @@ class Book(object):
via: https://opensource.com/article/19/5/python-attrs
作者:[Moshe Zadka ][a]
作者:[Moshe Zadka][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
@ -102,5 +101,5 @@ via: https://opensource.com/article/19/5/python-attrs
[3]: https://pypi.org/
[4]: https://pypi.org/project/attrs/
[5]: https://opensource.com/article/18/10/functional-programming-python-immutable-data-structures
[6]: https://opensource.com/article/19/4/7-python-problems-solved-cython
[7]: https://opensource.com/article/19/4/python-problems-solved-black
[6]: https://linux.cn/article-10859-1.html
[7]: https://linux.cn/article-10864-1.html

View File

@ -0,0 +1,198 @@
[#]: collector: (lujun9972)
[#]: translator: (warmfrog)
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10868-1.html)
[#]: subject: (Linux Shell Script To Monitor Disk Space Usage And Send Email)
[#]: via: (https://www.2daygeek.com/linux-shell-script-to-monitor-disk-space-usage-and-send-email/)
[#]: author: (Magesh Maruthamuthu https://www.2daygeek.com/author/magesh/)
用 Linux Shell 脚本来监控磁盘使用情况并发送邮件
============================================
市场上有很多用来监控 Linux 系统的监控工具,当系统到达阀值后它将发送一封邮件。它监控所有的东西例如 CPU 利用率、内存利用率、交换空间利用率、磁盘空间利用率等等。然而,它更适合小环境和大环境。
想一想如果你只有少量系统,那么什么是最好的方式来应对这种情况。
是的,我们想要写一个 [shell 脚本][1] 来实现。
在这篇指南中我们打算写一个 shell 脚本来监控系统的磁盘空间使用率。当系统到达给定的阀值,它将给对应的邮件地址发送一封邮件。在这篇文章中我们总共添加了四个 shell 脚本,每个用于不同的目的。之后,我们会想出其他 shell 脚本来监控 CPU内存和交换空间利用率。
在此之前,我想澄清一件事,根据我观察的磁盘空间使用率 shell 脚本使用情况。
大多数用户在多篇博客中评论说,当他们运行磁盘空间使用率脚本时他们获得了以下错误。
```
# sh /opt/script/disk-usage-alert-old.sh
/dev/mapper/vg_2g-lv_root
test-script.sh: line 7: [: /dev/mapper/vg_2g-lv_root: integer expression expected
/ 9.8G
```
是的,这是对的。甚至,当我第一次运行这个脚本的时候我遇到了相同的问题。之后,我发现了根本原因。
当你在基于 RHEL 5 & RHEL 6 的系统上运行包含用于磁盘空间警告的 `df -h``df -H` 的 shell 脚本中时,你会发现上述错误信息,因为输出格式不对,查看下列输出。
为了解决这个问题,我们需要用 `df -Ph` POSIX 输出格式),但是默认的 `df -h` 在基于 RHEL 7 的系统上运行的很好。
```
# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_2g-lv_root
10G 6.7G 3.4G 67% /
tmpfs 7.8G 0 7.8G 0% /dev/shm
/dev/sda1 976M 95M 830M 11% /boot
/dev/mapper/vg_2g-lv_home
5.0G 4.3G 784M 85% /home
/dev/mapper/vg_2g-lv_tmp
4.8G 14M 4.6G 1% /tmp
```
### 方法一Linux Shell 脚本来监控磁盘空间使用率和发送邮件
你可以使用下列 shell 脚本在 Linux 系统中来监控磁盘空间使用率。
当系统到达给定的阀值限制时,它将发送一封邮件。在这个例子中,我们设置阀值为 60% 用于测试目的,你可以改变这个限制来符合你的需求。
如果超过一个文件系统到达给定的阀值,它将发送多封邮件,因为这个脚本使用了循环。
同样,替换你的邮件地址来获取这份警告。
```
# vi /opt/script/disk-usage-alert.sh
#!/bin/sh
df -Ph | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5,$1 }' | while read output;
do
echo $output
used=$(echo $output | awk '{print $1}' | sed s/%//g)
partition=$(echo $output | awk '{print $2}')
if [ $used -ge 60 ]; then
echo "The partition \"$partition\" on $(hostname) has used $used% at $(date)" | mail -s "Disk Space Alert: $used% Used On $(hostname)" [email protected]
fi
done
```
输出:我获得了下列两封邮件警告。
```
The partition "/dev/mapper/vg_2g-lv_home" on 2g.CentOS7 has used 85% at Mon Apr 29 06:16:14 IST 2019
The partition "/dev/mapper/vg_2g-lv_root" on 2g.CentOS7 has used 67% at Mon Apr 29 06:16:14 IST 2019
```
最终添加了一个 [cronjob][2] 来自动完成。它会每 10 分钟运行一次。
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert.sh
```
### 方法二Linux Shell 脚本来监控磁盘空间使用率和发送邮件
作为代替,你可以使用下列的 shell 脚本。对比上面的脚本我们做了少量改变。
```
# vi /opt/script/disk-usage-alert-1.sh
#!/bin/sh
df -Ph | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5,$1 }' | while read output;
do
max=60%
echo $output
used=$(echo $output | awk '{print $1}')
partition=$(echo $output | awk '{print $2}')
if [ ${used%?} -ge ${max%?} ]; then
echo "The partition \"$partition\" on $(hostname) has used $used at $(date)" | mail -s "Disk Space Alert: $used Used On $(hostname)" [email protected]
fi
done
```
输出:我获得了下列两封邮件警告。
```
The partition "/dev/mapper/vg_2g-lv_home" on 2g.CentOS7 has used 85% at Mon Apr 29 06:16:14 IST 2019
The partition "/dev/mapper/vg_2g-lv_root" on 2g.CentOS7 has used 67% at Mon Apr 29 06:16:14 IST 2019
```
最终添加了一个 [cronjob][2] 来自动完成。它会每 10 分钟运行一次。
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert-1.sh
```
### 方法三Linux Shell 脚本来监控磁盘空间使用率和发送邮件
我更喜欢这种方法。因为,它工作起来很有魔力,你只会收到一封关于所有事的邮件。
这相当简单和直接。
```
*/10 * * * * df -Ph | sed s/%//g | awk '{ if($5 > 60) print $0;}' | mail -s "Disk Space Alert On $(hostname)" [email protected]
```
输出: 我获得了一封关于所有警告的邮件。
```
Filesystem Size Used Avail Use Mounted on
/dev/mapper/vg_2g-lv_root 10G 6.7G 3.4G 67 /
/dev/mapper/vg_2g-lv_home 5.0G 4.3G 784M 85 /home
```
### 方法四Linux Shell 脚本来监控某个分区的磁盘空间使用情况和发送邮件
```
# vi /opt/script/disk-usage-alert-2.sh
#!/bin/bash
used=$(df -Ph | grep '/dev/mapper/vg_2g-lv_dbs' | awk {'print $5'})
max=80%
if [ ${used%?} -ge ${max%?} ]; then
echo "The Mount Point "/DB" on $(hostname) has used $used at $(date)" | mail -s "Disk space alert on $(hostname): $used used" [email protected]
fi
```
输出: 我得到了下面的邮件警告。
```
The partition /dev/mapper/vg_2g-lv_dbs on 2g.CentOS6 has used 82% at Mon Apr 29 06:16:14 IST 2019
```
最终添加了一个 [cronjob][2] 来自动完成这些工作。它将每 10 分钟运行一次。
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert-2.sh
```
注意: 你将在 10 分钟后收到一封邮件警告,因为这个脚本被计划为每 10 分钟运行一次(但也不是精确的 10 分钟,取决于时间)。
例如这个例子。如果你的系统在 8:25 到达了限制,你将在 5 分钟后收到邮件警告。希望现在讲清楚了。
--------------------------------------------------------------------------------
via: https://www.2daygeek.com/linux-shell-script-to-monitor-disk-space-usage-and-send-email/
作者:[Magesh Maruthamuthu][a]
选题:[lujun9972][b]
译者:[warmfrog](https://github.com/warmfrog)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.2daygeek.com/author/magesh/
[b]: https://github.com/lujun9972
[1]: https://www.2daygeek.com/category/shell-script/
[2]: https://www.2daygeek.com/crontab-cronjob-to-schedule-jobs-in-linux/

View File

@ -1,18 +1,18 @@
[#]: collector: (lujun9972)
[#]: translator: (warmfrog)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10872-1.html)
[#]: subject: (How to Add Application Shortcuts on Ubuntu Desktop)
[#]: via: (https://itsfoss.com/ubuntu-desktop-shortcut/)
[#]: author: (Abhishek Prakash https://itsfoss.com/author/abhishek/)
在 Ubuntu 桌面如何添加应用快捷方式
如何在 Ubuntu 桌面手动添加应用快捷方式
===============================
_**在这篇快速指南中,你将学到如何在 Ubuntu 桌面和其他使用 GNOME 桌面的发行版中添加应用图标。**_
> 在这篇快速指南中,你将学到如何在 Ubuntu 桌面和其他使用 GNOME 桌面的发行版中添加应用图标。
一个经典的桌面操作系统在 ‘桌面屏’ 上总是有图标的。这些桌面图标包括文件管理器,回收站和应用图标。
一个经典的桌面操作系统在“桌面屏”上总是有图标的。这些桌面图标包括文件管理器、回收站和应用图标。
当在 Windows 中安装应用时,一些程序会询问你是否在桌面创建一个快捷方式。但在 Linux 系统中不是这样。
@ -26,43 +26,37 @@ _**在这篇快速指南中,你将学到如何在 Ubuntu 桌面和其他使用
![][5]
个人来讲,我更喜欢为应用图标准备的 Ubuntu 启动器方式。如果我经常使用一个程序,我会添加到启动器。但是我知道不是每个人都有相同的偏好并且少数人更喜欢桌面的快捷方式。
个人来讲,我更喜欢为应用图标准备的 Ubuntu 启动器方式。如果我经常使用一个程序,我会添加到启动器。但是我知道不是每个人都有相同的偏好,可能少数人更喜欢桌面的快捷方式。
让我们看在桌面中创建应用快捷方式的最简单方式。
免责声明
> 免责声明
这篇指南已经在 Ubuntu18.04 LTS 的 GNOME 桌面上测试过了。它可能在其他发行版和桌面环境上也能发挥作用,但你必须自己尝试。一些 GNOME 特定步骤可能会变,所以请在[其他桌面环境][7]尝试时注意。
[Subscribe to our YouTube Channel for More Linux Videos][8]
> 这篇指南已经在 Ubuntu 18.04 LTS 的 GNOME 桌面上测试过了。它可能在其他发行版和桌面环境上也能发挥作用,但你必须自己尝试。一些 GNOME 特定步骤可能会变,所以请在[其他桌面环境][7]尝试时注意。
#### 准备
首先最重要的事是确保你有 GNOME 桌面的图标权限。
如果你跟随 Ubuntu 18.04 自定义提示,你会知道如何安装 GNOME Tweaks 工具。在这个工具中,确保你设置 Show Icons 选项为允许
如果你跟随 Ubuntu 18.04 自定义提示,你会知道如何安装 GNOME Tweaks 工具。在这个工具中,确保你设置“Show Icons”选项为启用
![Allow icons on desktop in GNOME][9]
一旦你确保已经设置,是时候在桌面添加应用快捷方式了。
[][10]
建议阅读在双启动中如何替代一个 Linux 发行版 [保留 Home分区]
#### 第一步:定位应用的 .desktop 文件
到 Files -> Other Location -> Computer。
到 “Files -> Other Location -> Computer”。
![Go to Other Locations -> Computer][11]
从这里,到目录 usr -> share -> applications。你会在这里看到几个你已经安装的 [Ubuntu 应用][12]。即使你没有看到图标,你应该看到被命名为 应用名.desktop 形式的文件。
从这里,到目录 usr -> share -> applications。你会在这里看到几个你已经安装的 [Ubuntu 应用][12]。即使你没有看到图标,你应该看到被命名为“应用名.desktop”形式的文件。
![Application Shortcuts][13]
#### 第二步:拷贝 .desktop 文件到桌面
现在你要做的只是查找应用图标(或者它的 desktop 文件)。当你找到后,拖文件到桌面或者拷贝文件(使用 Ctrl+C 快捷方式)并在桌面粘贴(使用 Ctrl+V 快捷方式)。
现在你要做的只是查找应用图标(或者它的 desktop 文件)。当你找到后,拖文件到桌面或者拷贝文件(使用 `Ctrl+C` 快捷方式)并在桌面粘贴(使用 `Ctrl+V` 快捷方式)。
![Add .desktop file to the desktop][14]
@ -70,7 +64,7 @@ _**在这篇快速指南中,你将学到如何在 Ubuntu 桌面和其他使用
当你这么做,你应该在桌面上看到一个图标的文本文件而不是应用 logo。别担心一会就不一样了。
你要做的就是双击桌面的那个文件。它将警告你它是一个 ‘未信任的应用启动器’,点击信任并启动
你要做的就是双击桌面的那个文件。它将警告你它是一个“未信任的应用启动器’,点击“信任并启动”
![Launch Desktop Shortcut][15]
@ -80,20 +74,16 @@ _**在这篇快速指南中,你将学到如何在 Ubuntu 桌面和其他使用
#### Ubuntu 19.04 或者 GNOME 3.32 用户的疑难杂症
如果你使用 Ubuntu 19.04 或者 GNOME 3.32,你的 .desktop 文件可能根本不会启动。你应该右击 .desktop 文件并选择 “Allow Launching”。
如果你使用 Ubuntu 19.04 或者 GNOME 3.32,你的 .desktop 文件可能根本不会启动。你应该右击 .desktop 文件并选择 “允许启动”。
在这之后,你应该能够启动应用并且桌面上的应用快捷方式能够正常显示了。
**总结**
### 总结
如果你不喜欢桌面的某个应用启动器,选择删除就是了。它会删除应用快捷方式,但是应用仍安全的保留在你的系统中。
我希望你发现这篇快速指南有帮助并喜欢在 Ubuntu 桌面上的应用快捷方式。
[][17]
建议阅读在 Ubuntu 中如何安装和设置 Nemo 为默认的文件管理器。
如果你有问题或建议,请在下方评论让我知道。
--------------------------------------------------------------------------------
@ -103,7 +93,7 @@ via: https://itsfoss.com/ubuntu-desktop-shortcut/
作者:[Abhishek Prakash][a]
选题:[lujun9972][b]
译者:[warmfrog](https://github.com/warmfrog)
校对:[校对者ID](https://github.com/校对者ID)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

View File

@ -0,0 +1,139 @@
[#]: collector: (lujun9972)
[#]: translator: (warmfrog)
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10865-1.html)
[#]: subject: (How to use advanced rsync for large Linux backups)
[#]: via: (https://opensource.com/article/19/5/advanced-rsync)
[#]: author: (Alan Formy-Duval https://opensource.com/users/alanfdoss/users/marcobravo)
如何使用 rsync 的高级用法进行大型备份
=====================================
> 基础的 `rsync` 命令通常足够来管理你的 Linux 备份,但是额外的选项使大型备份集更快、更强大。
![Filing papers and documents][1]
很明显,备份一直是 Linux 世界的热门话题。回到 2017David Both 为 [Opensource.com][2] 的读者在[使用 rsync 备份 Linux 系统][3]方面提了一些建议,在这年的更早时候,他发起了一项问卷调查询问大家,[在 Linux 中你的 /home 目录的主要备份策略是什么][4]在今年的另一个问卷调查中Don Watkins 问到,[你使用哪种开源备份解决方案][5]。
我的回复是 [rsync][6]。我真的非常喜欢 rsync市场上有大量大而复杂的工具对于管理磁带机或者存储库设备这些可能是必要的但是可能你需要的只是一个简单的开源命令行工具。
### rsync 基础
我为一个大概拥有 35,000 开发者并有着几十 TB 文件的全球性机构管理二进制仓库。我经常一次移动或者归档上百 GB 的数据。使用的是 `rsync`。这种经历使我对这个简单的工具充满信心。(所以,是的,我在家使用它来备份我的 Linux 系统)
基础的 `rsync` 命令很简单。
```
rsync -av 源目录 目的地目录
```
实际上,在各种指南中教的 `rsync` 命令在大多数通用情况下都运行的很好。然而,假设我们需要备份大量的数据。例如包含 2,000 个子目录的目录,每个包含 50GB 到 700GB 的数据。在这个目录运行 `rsync` 可能需要大量时间,尤其是当你使用校验选项时(我倾向使用)。
当我们试图同步大量数据或者通过慢的网络连接时,可能遇到性能问题。让我给你展示一些我使用的方法来确保好的性能和可靠性。
### rsync 高级用法
`rsync` 运行时出现的第一行是:“正在发送增量文件列表。” 如果你在网上搜索这一行,你将看到很多类似的问题:为什么它一直运行,或者为什么它似乎挂起了。
这里是一个基于这个场景的例子。假设我们有一个 `/storage` 的目录,我们想要备份到一个外部 USB 磁盘,我们可以使用下面的命令:
```
rsync -cav /storage /media/WDPassport
```
`-c` 选项告诉 `rsync` 使用文件校验和而不是时间戳来决定改变的文件,这通常消耗的时间更久。为了分解 `/storage` 目录,我通过子目录同步,使用 `find` 命令。这是一个例子:
```
find /storage -type d -exec rsync -cav {} /media/WDPassport \;
```
这看起来可以,但是如果 `/storage` 目录有任何文件,它们将被跳过。因此,我们如何同步 `/storage` 目录中的文件呢?同样有一个细微的差别是这些选项将造成 `rsync` 会同步 `.` 目录,该目录是源目录自身;这意味着它会同步子目录两次,这并不是我们想要的。
长话短说,我的解决方案是一个 “双-递增”脚本。这允许我分解一个目录,例如,当你的家目录有多个大的目录,例如音乐或者家庭照片时,分解 `/home` 目录为单个的用户家目录。
这是我的脚本的一个例子:
```
HOMES="alan"
DRIVE="/media/WDPassport"
for HOME in $HOMES; do
cd /home/$HOME
rsync -cdlptgov --delete . /$DRIVE/$HOME
find . -maxdepth 1 -type d -not -name "." -exec rsync -crlptgov --delete {} /$DRIVE/$HOME \;
done
```
第一个 `rsync` 命令拷贝它在源目录中发现的文件和目录。然而,它将目录留着不处理,因此我们能够通过 `find` 命令迭代它们。这通过传递 `-d` 参数来完成,它告诉 `rsync` 不要递归目录。
```
-d, --dirs 传输目录而不递归
```
然后 `find` 命令传递每个目录来单独运行 `rsync`。之后 `rsync` 拷贝目录的内容。这通过传递 `-r` 参数来完成,它告诉 `rsync` 要递归目录。
```
-r, --recursive 递归进入目录
```
这使得 `rsync` 使用的增量文件保持在一个合理的大小。
大多数 `rsync` 指南为了简便使用 `-a` (或者 `archive` 参数。这实际是一个复合参数。
```
-a, --archive 归档模式;等价于 -rlptgoD没有 -H,-A,-X
```
我传递的其他参数包含在 `a` 中;这些是 `-l`、`-p`、`-t`、`-g`和 `-o`
```
-l, --links 复制符号链接作为符号链接
-p, --perms 保留权限
-t, --times 保留修改时间
-g, --group 保留组
-o, --owner 保留拥有者(只适用于超级管理员)
```
`--delete` 选项告诉 `rsync` 删除目的地目录中所有在源目录不存在的任意文件。这种方式,运行的结果仅仅是复制。你同样可以排除 `.Trash` 目录或者 MacOS 创建的 `.DS_Store` 文件。
```
-not -name ".Trash*" -not -name ".DS_Store"
```
### 注意
最后一条建议: `rsync` 可以是破坏性的命令。幸运的是,它的睿智的创造者提供了 “空运行” 的能力。如果我们加入 `n` 选项rsync 会显示预期的输出但不写任何数据。
```
`rsync -cdlptgovn --delete . /$DRIVE/$HOME`
```
这个脚本适用于非常大的存储规模和高延迟或者慢链接的情况。一如既往,我确信仍有提升的空间。如果你有任何建议,请在下方评论中分享。
--------------------------------------------------------------------------------
via: https://opensource.com/article/19/5/advanced-rsync
作者:[Alan Formy-Duval][a]
选题:[lujun9972][b]
译者:[warmfrog](https://github.com/warmfrog)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/alanfdoss/users/marcobravo
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/documents_papers_file_storage_work.png?itok=YlXpAqAJ (Filing papers and documents)
[2]: http://Opensource.com
[3]: https://linux.cn/article-8237-1.html
[4]: https://opensource.com/poll/19/4/backup-strategy-home-directory-linux
[5]: https://opensource.com/article/19/2/linux-backup-solutions
[6]: https://en.wikipedia.org/wiki/Rsync

View File

@ -0,0 +1,169 @@
[#]: collector: (lujun9972)
[#]: translator: (wxy)
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-10870-1.html)
[#]: subject: (PHP in 2019)
[#]: via: (https://stitcher.io/blog/php-in-2019)
[#]: author: (Brent https://stitcher.io/blog/php-in-2019)
9102 年的 PHP
======
你还记得篇流行的博客文章《[PHP设计糟糕的分形][3]》吗?我第一次读到它时,我在一个有很多遗留的 PHP 项目的糟糕地方工作。这篇文章让我觉得我是否应该放弃,并去做与编程完全不同的事情。
还好,我之后很快就换了工作,更重要的是,自从 5.x 版本以来PHP 成功地进步了很多。今天,我在向那些不再使用 PHP 编程,或者陷入遗留项目的人们致意。
剧透:今天有些事情仍然很糟糕,就像几乎每种编程语言都有它的怪癖一样。许多核心功能仍然有不一致的调用方法,仍然有令人困惑的配置设置,仍然有许多开发人员在那里写蹩脚的代码 —— 因为他们必须如此,或是他们不知道更好的写法。
今天我想看看好的一面:让我们关注已经发生变化的事情,以及编写干净而可维护的 PHP 代码的方法。在此之前,我想请你暂时搁置任何偏见。
然后,你可以像以前一样对 PHP 自由吐槽。虽然,你可能会对 PHP 在过去的几年里的一些改进感到惊讶。LCTT 译注:说实话,我是真的感到吃惊)
### 提前看结论
* PHP 在积极地开发,每年都有新版本
* 自 PHP 5 时代以来的性能已经翻倍,如果不是三倍的话
* 有一个非常活跃的框架、包和平台的生态系统
* PHP 在过去几年中添加了许多新功能,并且这种语言在不断发展
* 像静态分析这样的工具在过去几年中已经成熟,并且一直保持增长
  
更新:人们让我展示一些实际的代码。我觉得这没问题!这是我的一个业余项目的[源代码][4],用 PHP 和 Laravel 编写的;[这里][5]列出了我们在办公室维护的几百个自由开源软件包。这两者都是现代 PHP 项目的好例子。
那让我们开始吧。
### 历史总结
出于更好地衡量的目的,让我们快速回顾一下如今的 PHP 发布周期。我们现在的 PHP 为 7.3,预计在 2019 年底为 7.4。PHP 8.0 将是 7.4 之后的下一个版本。
自从 5.x 时代以来,核心团队试图保持每年发布一个版本的周期,并且他们在过去的四年中成功地做到了这一点。
一般来说,每个新版本都会在两年内得到积极支持,并再获得一年以上的“安全修复”。其目标是激励 PHP 开发人员尽可能保持最新:例如,每年进行小规模升级比在 5.4 到 7.0 之间跳转更容易。
可以在 [这里][6] 找到 PHP 时间轴的活动概述。
最后PHP 5.6 是最新的 5.x 版本,而 8.0 是当前的下一个大版本。如果你想知道 PHP 6 发生了什么,你可以听听 [PHP Roundtable 播客][7]。
了解了这个,让我们揭穿一些关于现代 PHP 的常见误解。
### PHP 的性能
早在 5.x 时代PHP 的表现就是……嗯,平均水平。但是在 7.0 版本中PHP 从头开始重写了核心部分,导致其性能提升了两到三倍!
但光是嘴说是不够的。让我们来看看基准测试。幸运的是,人们花了很多时间对 PHP 性能进行了基准测试。 我发现 [Kinsta][8] 有一个很好的更新的测试列表。
自 7.0 升级以来性能就一直在提升而没有回退。PHP Web 应用程序的性能可与其它语言中的 Web 框架相提并论,甚至在某些情况下更好。你可以看看这个[广泛的基准测试套件][9]。
当然 PHP 框架不会胜过 C 和 Rust但它们比 Rails 或 Django 要好得多,并且与 ExpressJS 相当。
### 框架和生态系统
说到框架PHP 可不仅仅是 WordPress。让我告诉你 —— 某些专业的 PHP 开发人员WordPress 绝不代表当代的 PHP 生态系统。
一般来说,有两个主要的 Web 应用程序框架,[Symfony][10] 和 [Laravel][11],以及一些较小的应用程序框架。当然还有 Zend、Yii、Cake、Code Igniter 等等,但是如果你想知道现代 PHP 开发是怎么样的,这两者之一都是很好的选择。
这两个框架都有一个庞大的包和产品的生态系统。从管理面板和 CRM 到独立软件包,从 CI 到分析器,以及几个 Web 套接字服务器、队列管理器、支付集成等众多服务。老实说,要列出的内容太多了。
这些框架虽然适用于实际开发。如果你只是需要个内容管理系统CMSWordPress 和 CraftCMS 等平台就够了。
衡量 PHP 生态系统当前状态的一种方法是查看 Packagist这是 PHP 主要的软件包存储库。它现在呈指数级增长。每天下载量达到了 2500 万次,可以说 PHP 生态系统已不再是以前的小型弱势群体了。
请查看此图表,它列出一段时间内的软件包和版本数量变化。它也可以在 [Packagist 网站][12]上找到它。
![][13]
除了应用程序框架和 CMS 之外,我们还看到过去几年里异步框架的兴起。
这些是用 PHP 或其他语言编写的框架和服务器,允许用户运行真正的异步 PHP这些例子包括 [Swoole][14](创始人韩天峰),以及 [Amp][15] 和 [ReactPHP][16]。
我们已经进入了异步的世界,像 Web 套接字和具有大量 I/O 的应用程序之类的东西在 PHP 世界中已经变得非常重要。
在内部邮件列表里PHP 核心开发人员讨论语言开发的地方)已经谈到了[将 libuv 添加到核心][17]。如果你还不知道 libuvNode.js 全有赖它提供异步性。
### 语言本身
虽然尚未提供 `async``await`但在过去几年中PHP 语言本身已经有了很多改进。这是 PHP 中新功能的非详尽列表:
+ [短闭包](https://stitcher.io/blog/short-closures-in-php)(箭头函数)
+ [Null 合并操作符](https://stitcher.io/blog/shorthand-comparisons-in-php#null-coalescing-operator)`??`
+ [Trait](https://www.php.net/manual/en/language.oop5.traits.php)(一种代码重用方式)
+ [属性类型](https://stitcher.io/blog/new-in-php-74#typed-properties-rfc)
+ [展开操作符](https://wiki.php.net/rfc/argument_unpacking)(参数解包 `...`
+ [JIT 编译器](https://wiki.php.net/rfc/jit)(即时编译器)
+ [FFI](https://wiki.php.net/rfc/ffi)(外部函数接口)
+ [匿名类](https://www.php.net/manual/en/language.oop5.anonymous.php)
+ [返回类型声明](https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration)
+ [现代化的加密支持](https://wiki.php.net/rfc/libsodium)
+ [生成器](https://wiki.php.net/rfc/generators)
+ [等等](https://www.php.net/ChangeLog-7.php)
当我们讨论语言功能时,我们还要谈谈当今该语言的发展过程。虽然社区可以提出 RFC但是得有一个活跃的志愿者核心团队才能推着它前进。
接下来,这些 RFC 将在“内部”邮件列表中进行讨论,这个邮件列表也可以[在线阅读][18]。在添加新的语言特性之前,必须进行投票。只有得到了至少 2/3 多数同意的 RFC 才能进入核心。
可能有大约 100 人能够投票,但不需要每个人对每个 RFC 进行投票。核心团队的成员当然可以投票,他们是维护代码库的人。除了他们之外,还有一群人从 PHP 社区中被单独挑选出来。这些人包括 PHP 文档的维护者,对 PHP 项目整体有贡献的人,以及 PHP 社区中的杰出开发人员。
虽然大多数核心开发都是在自愿的基础上完成的,但其中一位核心 PHP 开发人员 Nikita Popov 最近受雇于 [JetBrains][19] 全职从事于 PHP 语言的开发。另一个例子是 Linux 基金会最近决定[投资 Zend 框架][20]。像这样的雇佣和收购确保了 PHP 未来发展的稳定性。
### 工具
除了核心本身,我们看到过去几年中围绕它的工具有所增加。首先浮现于我脑海中的是静态分析器,比如由 Vimeo 创建 [Psalm][21],以及 [Phan][22] 和 [PHPStan][23]。
这些工具将静态分析你的 PHP 代码并报告任何类型错误和可能的错误等。在某种程度上,它们提供的功能可以与 TypeScript 进行比较,但是现在这种语言不能<ruby>转译<rt>transpiling</rt></ruby>,因此不支持使用自定义语法。
尽管这意味着我们需要依赖 docblocks但是 PHP 之父 Rasmus Lerdorf 确实提到了[添加静态分析引擎][24]到核心的想法。虽然会有很多潜力,但这是一项艰巨的任务。
说到转译,以及受到 JavaScript 社区的启发;他们已经努力在用户领域中扩展 PHP 语法。一个名为 [Pre][25] 的项目正是如此:允许将新的 PHP 语法转译为普通的 PHP 代码。
虽然这个思路已经在 JavaScript 世界中被证明了,但如果提供了适当的 IDE 和静态分析支持,它就能在 PHP 中工作了。这是一个非常有趣的想法,但必须发展起来才能称之为“主流”。
### 结语
尽管如此,你仍然可以将 PHP 视为一种糟糕的语言。虽然这种语言肯定有它的缺点和背负了 20 年的遗产;但我可以放胆地说,我喜欢用它工作。
根据我的经验,我能够创建可靠、可维护和高质量的软件。我工作的客户对最终结果感到满意,“俺也一样”。
尽管仍然可以用 PHP 做很多乱七八糟的事情,但我认为如果明智和正确地使用的话,它是 Web 开发的绝佳选择。
你不同意吗?让我知道为什么!你可以通过 [Twitter][2] 或 [电子邮件][26] 与我联系。
--------------------------------------------------------------------------------
via: https://stitcher.io/blog/php-in-2019
作者:[Brent][a]
选题:[lujun9972][b]
译者:[wxy](https://github.com/wxy)
校对:[wxy](https://github.com/wxy)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://stitcher.io/blog/php-in-2019
[b]: https://github.com/lujun9972
[1]: https://stitcher.io/
[2]: https://twitter.com/brendt_gd
[3]: https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
[4]: https://github.com/brendt/aggregate.stitcher.io
[5]: https://spatie.be/open-source/packages
[6]: https://www.php.net/supported-versions.php
[7]: https://www.phproundtable.com/episode/what-happened-to-php-6
[8]: https://kinsta.com/blog/php-benchmarks/
[9]: https://github.com/the-benchmarker/web-frameworks
[10]: https://symfony.com/
[11]: https://laravel.com/
[12]: https://packagist.org/statistics
[13]: https://stitcher.io/resources/img/blog/php-in-2019/packagist.png
[14]: https://www.swoole.co.uk/
[15]: https://amphp.org/
[16]: https://reactphp.org/
[17]: https://externals.io/message/102415#102415
[18]: https://externals.io/
[19]: https://blog.jetbrains.com/phpstorm/2019/01/nikita-popov-joins-phpstorm-team/
[20]: https://getlaminas.org/
[21]: https://github.com/vimeo/psalm
[22]: https://github.com/phan/phan
[23]: https://github.com/phpstan/phpstan
[24]: https://externals.io/message/101477#101592
[25]: https://preprocess.io/
[26]: mailto:brendt@stitcher.io

View File

@ -1,5 +1,5 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: translator: (ninifly )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )

View File

@ -1,92 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How to shop for enterprise firewalls)
[#]: via: (https://www.networkworld.com/article/3390686/how-to-shop-for-enterprise-firewalls.html#tk.rss_all)
[#]: author: (Zeus Kerravala https://www.networkworld.com/author/Zeus-Kerravala/)
How to shop for enterprise firewalls
======
Performance, form factors, and automation capabilities are key considerations when choosing a next-generation firewall (NGFW).
Firewalls have been around for years, but the technology keeps evolving as the threat landscape changes. Here are some tips about what to look for in a next-generation firewall ([NGFW][1]) that will satisfy business needs today and into the future.
### Don't trust firewall performance stats
Understanding how a NGFW performs requires more than looking at a vendors specification or running a bit of traffic through it. Most [firewalls][2] will perform well when traffic loads are light. Its important to see how a firewall responds at scale, particularly when [encryption][3] is turned on. Roughly 80% of traffic is encrypted today, and the ability to maintain performance levels with high volumes of encrypted traffic is critical.
**Learn more about network security**
* [How to boost collaboration between network and security teams][4]
* [What is microsegmentation? How getting granular improves network security][5]
* [What to consider when deploying a next-generation firewall][1]
* [How firewalls fit into enterprise security][2]
Also, be sure to turn on all major functions including application and user identification, IPS, anti-malware, URL filtering and logging during testing to see how a firewall will hold up in a production setting. Firewall vendors often tout a single performance number that's achieved with core features turned off. Data from [ZK Research][6] shows many IT pros learn this lesson the hard way: 58% of security professionals polled said they were forced to turn off features to maintain performance.
Before committing to a vendor, be sure to run tests with as many different types of traffic as possible and with various types of applications. Important metrics to look at include application throughput, connections per second, maximum sessions for both IPv4 and [IPv6][7], and SSL performance.
### NGFW needs to fit into broader security platform
Is it better to have a best-of-breed strategy or go with a single vendor for security? The issue has been debated for years, but the fact is, neither approach works flawlessly. Its important to understand that best-of-breed everywhere doesnt ensure best-in-class security. In fact, the opposite is typically true; having too many vendors can lead to complexity that can't be managed, which puts a business at risk. A better approach is a security platform, which can be thought of as an open architecture, that third-party products can be plugged into.
Any NGFW must be able to plug into a platform so it can "see" everything from IoT endpoints to cloud traffic to end-user devices. Also, once the NGFW has aggregated the data, it should be able to perform analytics to provide insights. This will enable the NGFW to take action and enforce policies across the network.
### Multiple form factors, consistent security features
Firewalls used to be relegated to corporate data centers. Today, networks have opened up, and customers need a consistent feature set at every point in the network. NGFW vendors should have the following form factors available to optimize price/performance:
* Data center
* Internet edge
* Midsize branch office
* Small branch office
* Ruggedized for IoT environments
* Cloud delivered
* Virtual machines that can run in private and public clouds
Also, NGFW vendors should have a roadmap for a containerized form factor. This certainly isnt a trivial task. Most vendors wont have a [container][8]-ready product yet, but they should be able to talk to how they plan to address the problem.
### Single-pane-of-glass firewall management
Having a broad product line doesnt matter if products need to be managed individually. This makes it hard to keep policies and rules up to date and leads to inconsistencies in features and functions. A firewall vendor must have a single management tool that provides end-to-end visibility and enables the administrator to make a change and push it out across the network at once. Visibility must extend everywhere, including the cloud, [IoT][9] edge, operational technology (OT) environments, and branch offices. A single dashboard is also the right place to implement and maintain software-based segmentation instead of having to configure each device.
### Firewall automation capabilities
The goal of [automation][10] is to help remove many of the manual steps that create "human latency" in the security process. Almost all vendors tout some automation capabilities as a way of saving on headcount, but automation goes well beyond that.
To continue reading this article register now
[Get Free Access][11]
[Learn More][12] Existing Users [Sign In][11]
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3390686/how-to-shop-for-enterprise-firewalls.html#tk.rss_all
作者:[Zeus Kerravala][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Zeus-Kerravala/
[b]: https://github.com/lujun9972
[1]: https://www.networkworld.com/article/3236448/what-to-consider-when-deploying-a-next-generation-firewall.html
[2]: https://www.networkworld.com/article/3230457/what-is-a-firewall-perimeter-stateful-inspection-next-generation.html
[3]: https://www.networkworld.com/article/3098354/enterprise-encryption-adoption-up-but-the-devils-in-the-details.html
[4]: https://www.networkworld.com/article/3328218/how-to-boost-collaboration-between-network-and-security-teams.html
[5]: https://www.networkworld.com/article/3247672/what-is-microsegmentation-how-getting-granular-improves-network-security.html
[6]: https://zkresearch.com/
[7]: https://www.networkworld.com/article/3254575/what-is-ipv6-and-why-aren-t-we-there-yet.html
[8]: https://www.networkworld.com/article/3159735/containers-what-are-containers.html
[9]: https://www.networkworld.com/article/3207535/what-is-iot-how-the-internet-of-things-works.html
[10]: https://www.networkworld.com/article/3184389/automation-rolls-on-what-are-you-doing-about-it.html
[11]: javascript://
[12]: /learn-about-insider/

View File

@ -1,54 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Must-know Linux Commands)
[#]: via: (https://www.networkworld.com/article/3391029/must-know-linux-commands.html#tk.rss_all)
[#]: author: (Tim Greene https://www.networkworld.com/author/Tim-Greene/)
Must-know Linux Commands
======
A compilation of essential commands for searching, monitoring and securing Linux systems - plus the Linux Command Line Cheat Sheet.
It takes some time working with Linux commands before you know which one you need for the task at hand, how to format it and what result to expect, but its possible to speed up the process.
With that in mind, weve gathered together some of the essential Linux commands as explained by Network World's [Unix as a Second Language][1] blogger Sandra Henry-Stocker to give aspiring power users what they need to get started with Linux systems.
The breakdown starts with the rich options available for finding files on Linux **find** , **locate** , **mlocate** , **which** , **whereis** , to name a few. Some overlap, but some are more efficient than others or zoom in on a narrow set of results. Theres even a command **apropos** to find the right command to do what you want to do. This section will demystify searches.
Henry-Stocker's article on memory provides a wealth of options for discovering the availability of physical and virtual memory and ways to have that information updated at intervals to constantly measure whether theres enough memory to go around. It shows how its possible to tailor your requests so you get a concise presentation of the results you seek.
Two remaining articles in this package show how to monitor activity on Linux servers and how to set up security parameters on these systems.
The first of these shows how to run the same command repetitively in order to have regular updates about any designated activity. It also tells about a command that focuses on user processes and shows changes as they occur, and a command that examines the time that users are connected.
The final article is a deep dive into commands that help keep Linux systems secure. It describes 22 of them that are essential for day-to-day admin work. They can restrict privileges to keep individuals from having more capabilities than their jobs call for and report on whos logged in, where from and how long theyve been there.
Some of these commands can track recent logins for individuals, which can be useful in running down who made changes. Others find files with varying characteristics, such as having no owner or by their contents. There are commands to control firewalls and to display routing tables.
As a bonus, our bundle of commands includes **The Linux Command-Line Cheat Sheet,** a concise summary of important commands that are useful every single day. Its suitable for printing out on two sides of a single sheet, laminating and keeping beside your keyboard.
Enjoy!
To continue reading this article register now
[Get Free Access][2]
[Learn More][3] Existing Users [Sign In][2]
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3391029/must-know-linux-commands.html#tk.rss_all
作者:[Tim Greene][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Tim-Greene/
[b]: https://github.com/lujun9972
[1]: https://www.networkworld.com/blog/unix-as-a-second-language/?nsdr=true
[2]: javascript://
[3]: /learn-about-insider/

View File

@ -1,81 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (hopefully2333)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Cisco issues critical security warning for Nexus data-center switches)
[#]: via: (https://www.networkworld.com/article/3392858/cisco-issues-critical-security-warning-for-nexus-data-center-switches.html#tk.rss_all)
[#]: author: (Michael Cooney https://www.networkworld.com/author/Michael-Cooney/)
Cisco issues critical security warning for Nexus data-center switches
======
Cisco released 40 security advisories around Nexus switches, Firepower firewalls and more
![Thinkstock][1]
Cisco issued some 40 security advisories today but only one of them was deemed “[critical][2]” a vulnerability in the Cisco Nexus 9000 Series Application Centric Infrastructure (ACI) Mode data-center switch that could let an attacker secretly access system resources.
The exposure, which was given a Common Vulnerability Scoring System importance of 9.8 out of 10, is described as a problem with secure shell (SSH) key-management for the Cisco Nexus 9000 that lets a remote attacker to connect to the affected system with the privileges of a root user, Cisco said.
**[ Read also:[How to plan a software-defined data-center network][3] ]**
“The vulnerability is due to the presence of a default SSH key pair that is present in all devices. An attacker could exploit this vulnerability by opening an SSH connection via IPv6 to a targeted device using the extracted key materials. This vulnerability is only exploitable over IPv6; IPv4 is not vulnerable," Cisco wrote.
This vulnerability affects Nexus 9000s if they are running a Cisco NX-OS software release prior to 14.1, and the company said there were no workarounds to address the problem.
However, Cisco has [released free software updates][4] that address the vulnerability.
The company also issued a “high” security warning advisory for the Nexus 9000 that involves an exploit that would let attackers execute arbitrary operating-system commands as root on an affected device. To succeed, an attacker would need valid administrator credentials for the device, Cisco said.
The vulnerability is due to overly broad system-file permissions, [Cisco wrote][5]. An attacker could exploit this vulnerability by authenticating to an affected device, creating a crafted command string and writing this crafted string to a specific file location.
**[[Prepare to become a Certified Information Security Systems Professional with this comprehensive online course from PluralSight. Now offering a 10-day free trial!][6] ]**
Cisco has released software updates that address this vulnerability.
Two other vulneraries rated “high” also involved the Nexus 9000:
* [A vulnerability][7] in the background-operations functionality of Cisco Nexus 9000 software could allow an authenticated, local attacker to gain elevated privileges as root on an affected device. The vulnerability is due to insufficient validation of user-supplied files on an affected device. Cisco said an attacker could exploit this vulnerability by logging in to the CLI of the affected device and creating a crafted file in a specific directory on the filesystem.
* A [weakness][7] in the background-operations functionality of the switch software could allow an attacker to login to the CLI of the affected device and create a crafted file in a specific directory on the filesystem. The vulnerability is due to insufficient validation of user-supplied files on an affected device, Cisco said.
Cisco has [released software][4] for these vulnerabilities as well.
Also part of these security alerts were a number of “high” rated warnings about vulneraries in Ciscos FirePower firewall series.
For example Cisco [wrote][8] that multiple vulnerabilities in the Server Message Block Protocol preprocessor detection engine for Cisco Firepower Threat Defense Software could allow an unauthenticated, adjacent or remote attacker to cause a denial of service (DoS) condition.
Yet [another vulnerability][9] in the internal packet-processing functionality of Cisco Firepower software for the Cisco Firepower 2100 Series could let an unauthenticated, remote attacker cause an affected device to stop processing traffic, resulting in a DOS situation, Cisco said.
[Software patches][4] are available for these vulnerabilities.
Other products such as the Cisco [Adaptive Security Virtual Appliance][10], and [Web Security appliance][11] had high priority patches as well.
Join the Network World communities on [Facebook][12] and [LinkedIn][13] to comment on topics that are top of mind.
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3392858/cisco-issues-critical-security-warning-for-nexus-data-center-switches.html#tk.rss_all
作者:[Michael Cooney][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Michael-Cooney/
[b]: https://github.com/lujun9972
[1]: https://images.idgesg.net/images/article/2018/02/lock_broken_unlocked_binary_code_security_circuits_protection_privacy_thinkstock_873916354-100750739-large.jpg
[2]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-nexus9k-sshkey
[3]: https://www.networkworld.com/article/3284352/data-center/how-to-plan-a-software-defined-data-center-network.html
[4]: https://www.cisco.com/c/en/us/about/legal/cloud-and-software/end_user_license_agreement.html
[5]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-nexus9k-rpe
[6]: https://pluralsight.pxf.io/c/321564/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fpaths%2Fcertified-information-systems-security-professional-cisspr
[7]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-aci-hw-clock-util
[8]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-frpwr-smb-snort
[9]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-frpwr-dos
[10]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-asa-ipsec-dos
[11]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-wsa-privesc
[12]: https://www.facebook.com/NetworkWorld/
[13]: https://www.linkedin.com/company/network-world

View File

@ -1,61 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Health care is still stitching together IoT systems)
[#]: via: (https://www.networkworld.com/article/3392818/health-care-is-still-stitching-together-iot-systems.html#tk.rss_all)
[#]: author: (Jon Gold https://www.networkworld.com/author/Jon-Gold/)
Health care is still stitching together IoT systems
======
The use of IoT technology in medicine is fraught with complications, but users are making it work.
_Government regulations, safety and technical integration are all serious issues facing the use of IoT in medicine, but professionals in the field say that medical IoT is moving forward despite the obstacles. A vendor, a doctor, and an IT pro all spoke to Network World about the work involved._
### Vendor: It's tough to gain acceptance**
**
Josh Stein is the CEO and co-founder of Adheretech, a medical-IoT startup whose main product is a connected pill bottle. The idea is to help keep seriously ill patients current with their medications, by monitoring whether theyve taken correct dosages or not.
The bottle which patients get for free (Adheretechs clients are hospitals and clinics) uses a cellular modem to call home to the companys servers and report on how much medication is left in the bottle, according to sensors that detect how many pills are touching the bottles sides and measuring its weight. There, the data is analyzed not just to determine whether patients are sticking to their doctors prescription, but to help identify possible side effects and whether they need additional help.
For example, a bottle that detects itself being moved to the bathroom too often might send up a flag that the patient is experiencing gastrointestinal side effects. The system can then contact patients or providers via phone or text to help them take the next steps.
The challenges to reach this point have been stiff, according to Stein. The company was founded in 2011 and spent the first four years of its existence simply designing and building its product.
“We had to go through many years of R&D to create a device thats replicatible a million times over,” he said. “If youre a healthcare company, you have to deal with HIPAA, the FDA, and then theres lots of other things like medication bottles have their whole own set of regulatory certifications.”
Beyond the simple fact of regulatory compliance, Stein said that theres resistance to this sort of new technology in the medical community.
“Healthcare is typically one of the last industries to adopt new technology,” he said.
### Doctor: Colleagues wonder if medical IoT plusses are worth the trouble
Dr. Rebecca Mishuris is the associate chief medical information officer at Boston Medical Center, a private non-profit hospital located in the South End. One of the institutions chief missions is to act as a safety net for the population of the area 57% of BMCs patients come from under-served populations, and roughly a third dont speak English as a primary language. That, in itself, can be a problem for IoT because many devices are designed to be used by native English speakers.
BMCs adoption of IoT tech has taken place mostly at the individual-practice level things like Bluetooth-enabled scales and diagnostic equipment for specific offices that want to use them but theres no hospital-wide IoT initiative happening, according to Mishuris.
Thats partially due to the fact that many practitioners arent convinced that connected healthcare devices are worth the trouble to purchase, install and manage, she said. HIPAA compliance and BMCs own privacy regulations are a particular concern, given that many of the devices deal with patient-generated data.
To continue reading this article register now
[Get Free Access][1]
[Learn More][2] Existing Users [Sign In][1]
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3392818/health-care-is-still-stitching-together-iot-systems.html#tk.rss_all
作者:[Jon Gold][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Jon-Gold/
[b]: https://github.com/lujun9972
[1]: javascript://
[2]: /learn-about-insider/

View File

@ -1,353 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (cycoe)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Using Pygame to move your game character around)
[#]: via: (https://opensource.com/article/17/12/game-python-moving-player)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
Using Pygame to move your game character around
======
In the fourth part of this series, learn how to code the controls needed to move a game character.
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python4-game.png?itok=tXFHaLdt)
In the first article in this series, I explained how to use Python to create a simple, [text-based dice game][1]. In the second part, we began building a game from scratch, starting with [creating the game's environment][2]. And, in the third installment, we [created a player sprite][3] and made it spawn in your (rather empty) game world. As you've probably noticed, a game isn't much fun if you can't move your character around. In this article, we'll use Pygame to add keyboard controls so you can direct your character's movement.
There are functions in Pygame to add other kinds of controls, but since you certainly have a keyboard if you're typing out Python code, that's what we'll use. Once you understand keyboard controls, you can explore other options on your own.
You created a key to quit your game in the second article in this series, and the principle is the same for movement. However, getting your character to move is a little more complex.
Let's start with the easy part: setting up the controller keys.
### Setting up keys for controlling your player sprite
Open your Python game script in IDLE, Ninja-IDE, or a text editor.
Since the game must constantly "listen" for keyboard events, you'll be writing code that needs to run continuously. Can you figure out where to put code that needs to run constantly for the duration of the game?
If you answered "in the main loop," you're correct! Remember that unless code is in a loop, it will run (at most) only once—and it may not run at all if it's hidden away in a class or function that never gets used.
To make Python monitor for incoming key presses, add this code to the main loop. There's no code to make anything happen yet, so use `print` statements to signal success. This is a common debugging technique.
```
while main == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                print('left')
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                print('right')
            if event.key == pygame.K_UP or event.key == ord('w'):
            print('jump')
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                print('left stop')
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                print('right stop')
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False    
```
Some people prefer to control player characters with the keyboard characters W, A, S, and D, and others prefer to use arrow keys. Be sure to include both options.
**Note: **It's vital that you consider all of your users when programming. If you write code that works only for you, it's very likely that you'll be the only one who uses your application. More importantly, if you seek out a job writing code for money, you are expected to write code that works for everyone. Giving your users choices, such as the option to use either arrow keys or WASD, is a sign of a good programmer.
Launch your game using Python, and watch the console window for output as you press the right, left, and up arrows, or the A, D, and W keys.
```
$ python ./your-name_game.py
  left
  left stop
  right
  right stop
  jump
```
This confirms that Pygame detects key presses correctly. Now it's time to do the hard work of making the sprite move.
### Coding the player movement function
To make your sprite move, you must create a property for your sprite that represents movement. When your sprite is not moving, this variable is set to `0`.
If you are animating your sprite, or should you decide to animate it in the future, you also must track frames to enable the walk cycle to stay on track.
Create the variables in the Player class. The first two lines are for context (you already have them in your code, if you've been following along), so add only the last three:
```
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0 # move along X
        self.movey = 0 # move along Y
        self.frame = 0 # count frames
```
With those variables set, it's time to code the sprite's movement.
The player sprite doesn't need to respond to control all the time; sometimes it will not be moving. The code that controls the sprite, therefore, is only one small part of all the things the player sprite will do. When you want to make an object in Python do something independent of the rest of its code, you place your new code in a function. Python functions start with the keyword `def`, which stands for define.
Make a function in your Player class to add some number of pixels to your sprite's position on screen. Don't worry about how many pixels you add yet; that will be decided in later code.
```
    def control(self,x,y):
        '''
        control player movement
        '''
        self.movex += x
        self.movey += y
```
To move a sprite in Pygame, you have to tell Python to redraw the sprite in its new location—and where that new location is.
Since the Player sprite isn't always moving, the updates need to be only one function within the Player class. Add this function after the `control` function you created earlier.
To make it appear that the sprite is walking (or flying, or whatever it is your sprite is supposed to do), you need to change its position on screen when the appropriate key is pressed. To get it to move across the screen, you redefine its position, designated by the `self.rect.x` and `self.rect.y` properties, to its current position plus whatever amount of `movex` or `movey` is applied. (The number of pixels the move requires is set later.)
```
    def update(self):
        '''
        Update sprite position
        '''
        self.rect.x = self.rect.x + self.movex        
```
Do the same thing for the Y position:
```
        self.rect.y = self.rect.y + self.movey
```
For animation, advance the animation frames whenever your sprite is moving, and use the corresponding animation frame as the player image:
```
        # moving left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[self.frame//ani]
        # moving right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[(self.frame//ani)+4]
```
Tell the code how many pixels to add to your sprite's position by setting a variable, then use that variable when triggering the functions of your Player sprite.
First, create the variable in your setup section. In this code, the first two lines are for context, so just add the third line to your script:
```
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10  # how many pixels to move
```
Now that you have the appropriate function and variable, use your key presses to trigger the function and send the variable to your sprite.
Do this by replacing the `print` statements in your main loop with the Player sprite's name (player), the function (.control), and how many steps along the X axis and Y axis you want the player sprite to move with each loop.
```
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(steps,0)
            if event.key == pygame.K_UP or event.key == ord('w'):
                print('jump')
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(-steps,0)
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False
```
Remember, `steps` is a variable representing how many pixels your sprite moves when a key is pressed. If you add 10 pixels to the location of your player sprite when you press D or the right arrow, then when you stop pressing that key you must subtract 10 (`-steps`) to return your sprite's momentum back to 0.
Try your game now. Warning: it won't do what you expect.
Why doesn't your sprite move yet? Because the main loop doesn't call the `update` function.
Add code to your main loop to tell Python to update the position of your player sprite. Add the line with the comment:
```
    player.update()  # update player position
    player_list.draw(world)
    pygame.display.flip()
    clock.tick(fps)
```
Launch your game again to witness your player sprite move across the screen at your bidding. There's no vertical movement yet because those functions will be controlled by gravity, but that's another lesson for another article.
In the meantime, if you have access to a joystick, try reading Pygame's documentation for its [joystick][4] module and see if you can make your sprite move that way. Alternately, see if you can get the [mouse][5] to interact with your sprite.
Most importantly, have fun!
### All the code used in this tutorial
For your reference, here is all the code used in this series of articles so far.
```
#!/usr/bin/env python3
# draw a world
# add a player and player control
# add player movement
# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
import pygame
import sys
import os
'''
Objects
'''
class Player(pygame.sprite.Sprite):
'''
Spawn a player
'''
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.frame = 0
self.images = []
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img.convert_alpha()
img.set_colorkey(ALPHA)
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
def control(self,x,y):
'''
control player movement
'''
self.movex += x
self.movey += y
def update(self):
'''
Update sprite position
'''
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# moving left
if self.movex < 0:
self.frame += 1
if self.frame > 3*ani:
self.frame = 0
self.image = self.images[self.frame//ani]
# moving right
if self.movex > 0:
self.frame += 1
if self.frame > 3*ani:
self.frame = 0
self.image = self.images[(self.frame//ani)+4]
'''
Setup
'''
worldx = 960
worldy = 720
fps = 40 # frame rate
ani = 4 # animation cycles
clock = pygame.time.Clock()
pygame.init()
main = True
BLUE = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)
ALPHA = (0,255,0)
world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.png')).convert()
backdropbox = world.get_rect()
player = Player() # spawn player
player.rect.x = 0
player.rect.y = 0
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10 # how fast to move
'''
Main loop
'''
while main == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
main = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(-steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(steps,0)
if event.key == pygame.K_UP or event.key == ord('w'):
print('jump')
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(-steps,0)
if event.key == ord('q'):
pygame.quit()
sys.exit()
main = False
# world.fill(BLACK)
world.blit(backdrop, backdropbox)
player.update()
player_list.draw(world) #refresh player position
pygame.display.flip()
clock.tick(fps)
```
You've come far and learned much, but there's a lot more to do. In the next few articles, you'll add enemy sprites, emulated gravity, and lots more. In the mean time, practice with Python!
--------------------------------------------------------------------------------
via: https://opensource.com/article/17/12/game-python-moving-player
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/article/17/10/python-101
[2]: https://opensource.com/article/17/12/program-game-python-part-2-creating-game-world
[3]: https://opensource.com/article/17/12/program-game-python-part-3-spawning-player
[4]: http://pygame.org/docs/ref/joystick.html
[5]: http://pygame.org/docs/ref/mouse.html#module-pygame.mouse

View File

@ -1,70 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (5G: A deep dive into fast, new wireless)
[#]: via: (https://www.networkworld.com/article/3385030/5g-a-deep-dive-into-fast-new-wireless.html#tk.rss_all)
[#]: author: (Craig Mathias https://www.networkworld.com/author/Craig-Mathias/)
5G: A deep dive into fast, new wireless
======
### 5G wireless networks are just about ready for prime time, overcoming backhaul and backward-compatibility issues, and promising the possibility of all-mobile networking through enhanced throughput.
The next step in the evolution of wireless WAN communications - [5G networks][1] \- is about to hit the front pages, and for good reason: it will complete the evolution of cellular from wireline augmentation to wireline replacement, and strategically from mobile-first to mobile-only.
So its not too early to start least basic planning to understanding how 5G will fit into and benefit IT plans across organizations of all sizes, industries and missions.
**[ From Mobile World Congress:[The time of 5G is almost here][2] ]**
5G will of course provide end-users with the additional throughput, capacity, and other elements to address the continuing and dramatic growth in geographic availability, user base, range of subscriber devices, demand for capacity, and application requirements, but will also enable service providers to benefit from new opportunities in overall strategy, service offerings and broadened marketplace presence.
A look at the key features you can expect in 5G wireless. (Click for larger image.)
![A look at the key features you can expect in 5G wireless.][3]
This article explores the technologies and market drivers behind 5G, with an emphasis on what 5G means to enterprise and organizational IT.
While 5G remains an imprecise term today, key objectives for the development of the advances required have become clear. These are as follows:
## 5G speeds
As is the case with Wi-Fi, major advances in cellular are first and foremost defined by new upper-bound _throughput_ numbers. The magic number here for 5G is in fact a _floor_ of 1 Gbps, with numbers as high as 10 Gbps mentioned by some. However, and again as is the case with Wi-Fi, its important to think more in terms of overall individual-cell and system-wide _capacity_. We believe, then, that per-user throughput of 50 Mbps is a more reasonable but clearly still remarkable working assumption, with up to 300 Mbps peak throughput realized in some deployments over the next five years. The possibility of reaching higher throughput than that exceeds our planning horizon, but such is, well, possible.
## Reduced latency
Perhaps even more important than throughput, though, is a reduction in the round-trip time for each packet. Reducing latency is important for voice, which will most certainly be all-IP in 5G implementations, video, and, again, in improving overall capacity. The over-the-air latency goal for 5G is less than 10ms, with 1ms possible in some defined classes of service.
## 5G network management and OSS
Operators are always seeking to reduce overhead and operating expense, so enhancements to both system management and operational support systems (OSS) yielding improvements in reliability, availability, serviceability, resilience, consistency, analytics capabilities, and operational efficiency, are all expected. The benefits of these will, in most cases, however, be transparent to end-users.
## Mobility and 5G technology
Very-high-speed user mobility, to as much as hundreds of kilometers per hour, will be supported, thus serving users on all modes of transportation. Regulatory and situation-dependent restrictions most notably, on aircraft however, will still apply.
To continue reading this article register now
[Get Free Access][4]
[Learn More][5] Existing Users [Sign In][4]
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3385030/5g-a-deep-dive-into-fast-new-wireless.html#tk.rss_all
作者:[Craig Mathias][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Craig-Mathias/
[b]: https://github.com/lujun9972
[1]: https://www.networkworld.com/article/3203489/what-is-5g-how-is-it-better-than-4g.html
[2]: https://www.networkworld.com/article/3354477/mobile-world-congress-the-time-of-5g-is-almost-here.html
[3]: https://images.idgesg.net/images/article/2017/06/2017_nw_5g_wireless_key_features-100727485-large.jpg
[4]: javascript://
[5]: /learn-about-insider/

View File

@ -1,61 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Get started with Libki to manage public user computer access)
[#]: via: (https://opensource.com/article/19/5/libki-computer-access)
[#]: author: (Don Watkins https://opensource.com/users/don-watkins/users/tony-thomas)
Get started with Libki to manage public user computer access
======
Libki is a cross-platform, computer reservation and time management
system.
![][1]
Libraries, schools, colleges, and other organizations that provide public computers need a good way to manage users' access—otherwise, there's no way to prevent some people from monopolizing the machines and ensure everyone has a fair amount of time. This is the problem that [Libki][2] was designed to solve.
Libki is an open source, cross-platform, computer reservation and time management system for Windows and Linux PCs. It provides a web-based server and a web-based administration system that staff can use to manage computer access, including creating and deleting users, setting time limits on accounts, logging out and banning users, and setting access restrictions.
According to lead developer [Kyle Hall][3], Libki is mainly used for PC time control as an open source alternative to Envisionware's proprietary computer access control software. When users log into a Libki-managed computer, they get a block of time to use the computer; once that time is up, they are logged off. The default setting is 45 minutes, but that can easily be adjusted using the web-based administration system. Some organizations offer 24 hours of access before logging users off, and others use it to track usage without setting time limits.
Kyle is currently lead developer at [ByWater Solutions][4], which provides open source software solutions (including Libki) to libraries. He developed Libki early in his career when he was the IT tech at the [Meadville Public Library][5] in Pennsylvania. He was occasionally asked to cover the children's room during lunch breaks for other employees. The library used a paper sign-up sheet to manage access to the computers in the children's room, which meant constant supervision and checking to ensure equitable access for the people who came there.
Kyle said, "I found this system to be cumbersome and awkward, and I wanted to find a solution. That solution needed to be both FOSS and cross-platform. In the end, no existing software package suited our particular needs, and that is why I developed Libki."
Or, as Libki's website proclaims, "Libki was born of the need to avoid interacting with teenagers and now allows librarians to avoid interacting with teenagers around the world!"
### Easy to set up and use
I recently decided to try Libki in our local public library, where I frequently volunteer. I followed the [documentation][6] for the automatic installation, using Ubuntu 18.04 Server, and very quickly had it up and running.
I am planning to support Libki in our local library, but I wondered about libraries that don't have someone with IT experience or the ability to build and deploy a server. Kyle says, "ByWater Solutions can cloud-host a Libki server, which makes maintenance and management much simpler for everyone."
Kyle says ByWater is not planning to bundle Libki with its most popular offering, open source integrated library system (ILS) Koha, or any of the other [projects][7] it supports. "Libki and Koha are different [types of] software serving different needs, but they definitely work well together in a library setting. In fact, it was quite early on that I developed Libki's SIP2 integration so it could support single sign-on using Koha," he says.
### How you can contribute
Libki client is licensed under the GPLv3 and Libki server is licensed under the AGPLv3. Kyle says he would love Libki to have a more active and robust community, and the project is always looking for new people to join its [contributors][8]. If you would like to participate, visit [Libki's Community page][9] and join the mailing list.
--------------------------------------------------------------------------------
via: https://opensource.com/article/19/5/libki-computer-access
作者:[Don Watkins ][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/don-watkins/users/tony-thomas
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/desk_clock_job_work.jpg?itok=Nj4fuhl6
[2]: https://libki.org/
[3]: https://www.linkedin.com/in/kylemhallinfo/
[4]: https://opensource.com/article/19/4/software-libraries
[5]: https://meadvillelibrary.org/
[6]: https://manual.libki.org/master/libki-manual.html#_automatic_installation
[7]: https://bywatersolutions.com/projects
[8]: https://github.com/Libki/libki-server/graphs/contributors
[9]: https://libki.org/community/

View File

@ -1,5 +1,5 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )

View File

@ -1,5 +1,5 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: translator: (way-ww)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )

View File

@ -1,202 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (warmfrog)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Linux Shell Script To Monitor Disk Space Usage And Send Email)
[#]: via: (https://www.2daygeek.com/linux-shell-script-to-monitor-disk-space-usage-and-send-email/)
[#]: author: (Magesh Maruthamuthu https://www.2daygeek.com/author/magesh/)
Linux Shell Script To Monitor Disk Space Usage And Send Email
======
There are numerous monitoring tools are available in market to monitor Linux systems and it will send an email when the system reaches the threshold limit.
It monitors everything such as CPU utilization, Memory utilization, swap utilization, disk space utilization and much more.
However, its suitable for small and big environment.
Think about if you have only few systems then what will be the best approach on this.
Yup, we want to write a **[shell script][1]** to achieve this.
In this tutorial we are going to write a shell script to monitor disk space usage on system.
When the system reaches the given threshold then it will trigger a mail to corresponding email id.
We have added totally four shell scripts in this article and each has been used for different purpose.
Later, we will come up with other shell scripts to monitor CPU, Memory and Swap utilization.
Before step into that, i would like to clarify one thing which i noticed regarding the disk space usage shell script.
Most of the users were commented in multiple blogs saying they were getting the following error message when they are running the disk space usage script.
```
# sh /opt/script/disk-usage-alert-old.sh
/dev/mapper/vg_2g-lv_root
test-script.sh: line 7: [: /dev/mapper/vg_2g-lv_root: integer expression expected
/ 9.8G
```
Yes thats right. Even, i had faced the same issue when i ran the script first time. Later, i had found the root causes.
When you use “df -h” or “df -H” in shell script for disk space alert on RHEL 5 & RHEL 6 based system, you will be end up with the above error message because the output is not in the proper format, see the below output.
To overcome this issue, we need to use “df -Ph” (POSIX output format) but by default “df -h” is working fine on RHEL 7 based systems.
```
# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_2g-lv_root
10G 6.7G 3.4G 67% /
tmpfs 7.8G 0 7.8G 0% /dev/shm
/dev/sda1 976M 95M 830M 11% /boot
/dev/mapper/vg_2g-lv_home
5.0G 4.3G 784M 85% /home
/dev/mapper/vg_2g-lv_tmp
4.8G 14M 4.6G 1% /tmp
```
### Method-1 : Linux Shell Script To Monitor Disk Space Usage And Send Email
You can use the following shell script to monitor disk space usage on Linux system.
It will send an email when the system reaches the given threshold limit. In this example, we set threshold limit at 60% for testing purpose and you can change this limit as per your requirements.
It will send multiple mails if more than one file systems get reached the given threshold limit because the script is using loop.
Also, replace your email id instead of us to get this alert.
```
# vi /opt/script/disk-usage-alert.sh
#!/bin/sh
df -Ph | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5,$1 }' | while read output;
do
echo $output
used=$(echo $output | awk '{print $1}' | sed s/%//g)
partition=$(echo $output | awk '{print $2}')
if [ $used -ge 60 ]; then
echo "The partition \"$partition\" on $(hostname) has used $used% at $(date)" | mail -s "Disk Space Alert: $used% Used On $(hostname)" [email protected]
fi
done
```
**Output:** I got the following two email alerts.
```
The partition "/dev/mapper/vg_2g-lv_home" on 2g.CentOS7 has used 85% at Mon Apr 29 06:16:14 IST 2019
The partition "/dev/mapper/vg_2g-lv_root" on 2g.CentOS7 has used 67% at Mon Apr 29 06:16:14 IST 2019
```
Finally add a **[cronjob][2]** to automate this. It will run every 10 minutes.
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert.sh
```
### Method-2 : Linux Shell Script To Monitor Disk Space Usage And Send Email
Alternatively, you can use the following shell script. We have made few changes in this compared with above script.
```
# vi /opt/script/disk-usage-alert-1.sh
#!/bin/sh
df -Ph | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5,$1 }' | while read output;
do
max=60%
echo $output
used=$(echo $output | awk '{print $1}')
partition=$(echo $output | awk '{print $2}')
if [ ${used%?} -ge ${max%?} ]; then
echo "The partition \"$partition\" on $(hostname) has used $used at $(date)" | mail -s "Disk Space Alert: $used Used On $(hostname)" [email protected]
fi
done
```
**Output:** I got the following two email alerts.
```
The partition "/dev/mapper/vg_2g-lv_home" on 2g.CentOS7 has used 85% at Mon Apr 29 06:16:14 IST 2019
The partition "/dev/mapper/vg_2g-lv_root" on 2g.CentOS7 has used 67% at Mon Apr 29 06:16:14 IST 2019
```
Finally add a **[cronjob][2]** to automate this. It will run every 10 minutes.
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert-1.sh
```
### Method-3 : Linux Shell Script To Monitor Disk Space Usage And Send Email
I would like to go with this method. Since, it work like a charm and you will be getting single email for everything.
This is very simple and straightforward.
```
*/10 * * * * df -Ph | sed s/%//g | awk '{ if($5 > 60) print $0;}' | mail -s "Disk Space Alert On $(hostname)" [email protected]
```
**Output:** I got a single mail for all alerts.
```
Filesystem Size Used Avail Use Mounted on
/dev/mapper/vg_2g-lv_root 10G 6.7G 3.4G 67 /
/dev/mapper/vg_2g-lv_home 5.0G 4.3G 784M 85 /home
```
### Method-4 : Linux Shell Script To Monitor Disk Space Usage Of Particular Partition And Send Email
If anybody wants to monitor the particular partition then you can use the following shell script. Simply replace your filesystem name instead of us.
```
# vi /opt/script/disk-usage-alert-2.sh
#!/bin/bash
used=$(df -Ph | grep '/dev/mapper/vg_2g-lv_dbs' | awk {'print $5'})
max=80%
if [ ${used%?} -ge ${max%?} ]; then
echo "The Mount Point "/DB" on $(hostname) has used $used at $(date)" | mail -s "Disk space alert on $(hostname): $used used" [email protected]
fi
```
**Output:** I got the following email alerts.
```
The partition /dev/mapper/vg_2g-lv_dbs on 2g.CentOS6 has used 82% at Mon Apr 29 06:16:14 IST 2019
```
Finally add a **[cronjob][2]** to automate this. It will run every 10 minutes.
```
# crontab -e
*/10 * * * * /bin/bash /opt/script/disk-usage-alert-2.sh
```
**Note:** You will be getting an email alert 10 mins later since the script has scheduled to run every 10 minutes (But its not exactly 10 mins and it depends the timing).
Say for example. If your system reaches the limit at 8.25 then you will get an email alert in another 5 mins. Hope its clear now.
--------------------------------------------------------------------------------
via: https://www.2daygeek.com/linux-shell-script-to-monitor-disk-space-usage-and-send-email/
作者:[Magesh Maruthamuthu][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.2daygeek.com/author/magesh/
[b]: https://github.com/lujun9972
[1]: https://www.2daygeek.com/category/shell-script/
[2]: https://www.2daygeek.com/crontab-cronjob-to-schedule-jobs-in-linux/

View File

@ -0,0 +1,164 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Querying 10 years of GitHub data with GHTorrent and Libraries.io)
[#]: via: (https://opensource.com/article/19/5/chaossearch-github-ghtorrent)
[#]: author: (Pete Cheslock https://opensource.com/users/petecheslock/users/ghaff/users/payalsingh/users/davidmstokes)
Querying 10 years of GitHub data with GHTorrent and Libraries.io
======
There is a way to explore GitHub data without any local infrastructure
using open source datasets.
![magnifying glass on computer screen][1]
Im always on the lookout for new datasets that we can use to show off the power of my team's work. [**CHAOS** SEARCH][2] turns your [Amazon S3][3] object storage data into a fully searchable [Elasticsearch][4]-like cluster. With the Elasticsearch API or tools like [Kibana][5], you can then query whatever data you find.
I was excited when I found the [GHTorrent][6] project to explore. GHTorrent aims to build an offline version of all data available through the GitHub APIs. If datasets are your thing, this is a project worth checking out or even consider [donating one of your GitHub API keys][7].
### Accessing GHTorrent data
There are many ways to gain access to and use [GHTorrents data][8], which is available in [NDJSON][9]** **format. This project does a great job making the data available in multiple forms, including[CSV][10] for restoring into a [MySQL][11] database, [MongoDB][12] dumps of all objects, and Google Big Query** **(free) for exporting data directly into Googles object storage. There is one caveat: this dataset has a nearly complete dataset from 2008 to 2017 but is not as complete from 2017 to today. That will impact our ability to query with certainty, but it is still an exciting amount of information.
I chose Google Big Query to avoid running any database myself, so I was quickly able to download a full corpus of data including users and projects. **CHAOS** SEARCH can natively analyze the NDJSON format, so after uploading the data to Amazon S3 I was able to index it in just a few minutes. The **CHAOS** SEARCH platform doesnt require users to set up index schemas or define mappings for their data, so it discovered all of the fields—strings, integers, etc.—itself.
With my data fully indexed and ready for search and aggregation, I wanted to dive in and see what insights we can learn, like which software languages are the most popular for GitHub projects.
(A note on formatting: this is a valid JSON query that we won't format correctly here to avoid scroll fatigue. To properly format it, you can copy it locally and send to a command-line utility like [jq][13].)
```
`{"aggs":{"2":{"date_histogram":{"field":"root.created_at","interval":"1M","time_zone":"America/New_York","min_doc_count":1}}},"size":0,"_source":{"excludes":[]},"stored_fields":["*"],"script_fields":{},"docvalue_fields":["root.created_at","root.updated_at"],"query":{"bool":{"must":[],"filter":[{"match_all":{}}],"should":[],"must_not":[{"match_phrase":{"root.language":{"query":""}}}]}}}`
```
This result is of little surprise to anyone whos followed the state of open source languages over recent years.
![Which software languages are the most popular on GitHub.][14]
[JavaScript][15] is still the reigning champion, and while some believe JavaScript is on its way out, it remains the 800-pound gorilla and is likely to remain that way for some time. [Java][16] faces similar rumors and this data shows that it's a major part of the open source ecosystem.
Given the popularity of projects like [Docker][17] and [Kubernetes][18], you might be wondering, “What about Go ([Golang][19])?” This is a good time for a reminder that the GitHub dataset discussed here contains some gaps, most significantly after 2017, which is about when I saw Golang projects popping up everywhere. I hope to repeat this search with a complete GitHub dataset and see if it changes the rankings at all.
Now let's explore the rate of project creation. (Reminder: this is valid JSON consolidated for readability.)
```
`{"aggs":{"2":{"date_histogram":{"field":"root.created_at","interval":"1M","time_zone":"America/New_York","min_doc_count":1}}},"size":0,"_source":{"excludes":[]},"stored_fields":["*"],"script_fields":{},"docvalue_fields":["root.created_at","root.updated_at"],"query":{"bool":{"must":[],"filter":[{"match_all":{}}],"should":[],"must_not":[{"match_phrase":{"root.language":{"query":""}}}]}}}`
```
Seeing the rate at which new projects are created would be fun impressive as well, with tremendous growth starting around 2012:
![The rate at which new projects are created on GitHub.][20]
Now that I knew the rate of projects created as well as the most popular languages used to create these projects, I wanted to find out what open source licenses these projects chose. Unfortunately, this data doesnt exist in the GitHub projects dataset, but the fantastic team over at [Tidelift][21] publishes a detailed list of GitHub projects, licenses used, and other details regarding the state of open source software in their [Libraries.io][22][ data][23]. Ingesting this dataset into **CHAOS** SEARCH took just minutes, letting me see which open source software licenses are the most popular on GitHub:
(Reminder: this is valid JSON consolidated for readability.)
```
`{"aggs":{"2":{"terms":{"field":"Repository License","size":10,"order":{"_count":"desc"}}}},"size":0,"_source":{"excludes":[]},"stored_fields":["*"],"script_fields":{},"docvalue_fields":["Created Timestamp","Last synced Timestamp","Latest Release Publish Timestamp","Updated Timestamp"],"query":{"bool":{"must":[],"filter":[{"match_all":{}}],"should":[],"must_not":[{"match_phrase":{"Repository License":{"query":""}}}]}}}`
```
The results show some significant outliers:
![Which open source software licenses are the most popular on GitHub.][24]
As you can see, the [MIT license][25] and the [Apache 2.0 license][26] by far outweighs most of the other open source licenses used for these projects, while [various BSD and GPL licenses][27] follow far behind. I cant say that Im surprised by these results given GitHubs open model. I would guess that users, not companies, create most projects and that they use the MIT license to make it simple for other people to use, share, and contribute. That Apache 2.0** **licensing is right behind also makes sense, given just how many companies want to ensure their trademarks are respected and have an open source component to their businesses.
Now that I identified the most popular licenses, I was curious to see the least used ones. By adjusting my last query, I reversed the top 10 into the bottom 10 and was able to find just two projects using the [University of Illinois—NCSA Open Source License][28]. I had never heard of this license before, but its pretty close to Apache 2.0. Its interesting to see just how many different software licenses are in use across all GitHub projects.
![The University of Illinois/NCSA open source license.][29]
The University of Illinois/NCSA open source license.
After that, I dove into a specific language (JavaScript) to see the most popular license used there. (Reminder: this is valid JSON consolidated for readability.)
```
`{"aggs":{"2":{"terms":{"field":"Repository License","size":10,"order":{"_count":"desc"}}}},"size":0,"_source":{"excludes":[]},"stored_fields":["*"],"script_fields":{},"docvalue_fields":["Created Timestamp","Last synced Timestamp","Latest Release Publish Timestamp","Updated Timestamp"],"query":{"bool":{"must":[{"match_phrase":{"Repository Language":{"query":"JavaScript"}}}],"filter":[{"match_all":{}}],"should":[],"must_not":[{"match_phrase":{"Repository License":{"query":""}}}]}}}`
```
There were some surprises in this output.
![The most popular open source licenses used for GitHub JavaScript projects.][30]
Even though the default license for [NPM][31] modules when created with **npm init **is the one from [Internet Systems Consortium (ISC)][32], you can see that a considerable number of these projects use MIT as well as Apache 2.0 for their open source license.
Since the Libraries.io dataset is rich in open source project content, and since the GHTorrent data is missing the last few years data (and thus missing any details about Golang projects), I decided to run a similar query to see how Golang projects license their code.
(Reminder: this is valid JSON consolidated for readability.)
```
`{"aggs":{"2":{"terms":{"field":"Repository License","size":10,"order":{"_count":"desc"}}}},"size":0,"_source":{"excludes":[]},"stored_fields":["*"],"script_fields":{},"docvalue_fields":["Created Timestamp","Last synced Timestamp","Latest Release Publish Timestamp","Updated Timestamp"],"query":{"bool":{"must":[{"match_phrase":{"Repository Language":{"query":"Go"}}}],"filter":[{"match_all":{}}],"should":[],"must_not":[{"match_phrase":{"Repository License":{"query":""}}}]}}}`
```
The results were quite different than Javascript.
![How Golang projects license their GitHub code.][33]
Golang offers a stunning reversal from JavaScript—nearly three times as many Golang projects are licensed with Apache 2.0 over MIT. While its hard precisely explain why this is the case, over the last few years theres been massive growth in Golang, especially among companies building projects and software offerings, both open source and commercially.
As we learned above, many of these companies want to enforce their trademarks, thus the move to the Apache 2.0 license makes sense.
#### Conclusion
In the end, I found some interesting results by diving into the GitHub users and projects data dump. Some of these I definitely would have guessed, but a few results were surprises to me as well, especially the outliers like the rarely-used NCSA license.
All in all, you can see how quickly and easily the **CHAOS** SEARCH platform lets us find complicated answers to interesting questions. I dove into this dataset and received deep analytics without having to run any databases myself, and even stored the data inexpensively on Amazon S3—so theres little maintenance involved. Now I can ask any other questions regarding the data anytime I want.
What other questions are you asking your data, and what data sets do you use? Let me know in the comments or on Twitter [@petecheslock][34].
_A version of this article was originally posted on[ **CHAOS** SEARCH][35]._
* * *
--------------------------------------------------------------------------------
via: https://opensource.com/article/19/5/chaossearch-github-ghtorrent
作者:[Pete Cheslock][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/petecheslock/users/ghaff/users/payalsingh/users/davidmstokes
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/search_find_code_issue_bug_programming.png?itok=XPrh7fa0 (magnifying glass on computer screen)
[2]: https://chaossearch.io/
[3]: https://aws.amazon.com/s3/
[4]: https://www.elastic.co/
[5]: https://www.elastic.co/products/kibana
[6]: http://ghtorrent.org
[7]: http://ghtorrent.org/services.html
[8]: http://ghtorrent.org/downloads.html
[9]: http://ndjson.org
[10]: https://en.wikipedia.org/wiki/Comma-separated_values
[11]: https://en.wikipedia.org/wiki/MySQL
[12]: https://www.mongodb.com/
[13]: https://stedolan.github.io/jq/
[14]: https://opensource.com/sites/default/files/uploads/github-1_500.png (Which software languages are the most popular on GitHub.)
[15]: https://en.wikipedia.org/wiki/JavaScript
[16]: /resources/java
[17]: /resources/what-docker
[18]: /resources/what-is-kubernetes
[19]: https://golang.org/
[20]: https://opensource.com/sites/default/files/uploads/github-2_500.png (The rate at which new projects are created on GitHub.)
[21]: https://tidelift.com
[22]: http://libraries.io/
[23]: https://libraries.io/data
[24]: https://opensource.com/sites/default/files/uploads/github-3_500.png (Which open source software licenses are the most popular on GitHub.)
[25]: https://opensource.org/licenses/MIT
[26]: https://opensource.org/licenses/Apache-2.0
[27]: https://opensource.org/licenses
[28]: https://tldrlegal.com/license/university-of-illinois---ncsa-open-source-license-(ncsa)
[29]: https://opensource.com/sites/default/files/uploads/github-4_500_0.png (The University of Illinois/NCSA open source license.)
[30]: https://opensource.com/sites/default/files/uploads/github-5_500_0.png (The most popular open source licenses used for GitHub JavaScript projects.)
[31]: https://www.npmjs.com/
[32]: https://en.wikipedia.org/wiki/ISC_license
[33]: https://opensource.com/sites/default/files/uploads/github-6_500.png (How Golang projects license their GitHub code.)
[34]: https://twitter.com/petecheslock
[35]: https://chaossearch.io/blog/where-are-the-github-users-part-1/

View File

@ -0,0 +1,82 @@
[#]: collector: (lujun9972)
[#]: translator: (hopefully2333)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Cisco issues critical security warning for Nexus data-center switches)
[#]: via: (https://www.networkworld.com/article/3392858/cisco-issues-critical-security-warning-for-nexus-data-center-switches.html#tk.rss_all)
[#]: author: (Michael Cooney https://www.networkworld.com/author/Michael-Cooney/)
思科针对 Nexus 数据中心交换机发出危急安全预警
======
思科围绕着 Nexus 的交换机、Firepower 防火墙和其他设备,发布了 40 个安全报告。
![Thinkstock][1]
今天思科发布了 40 个左右的安全报告,但只有其中的一个被评定为“危急”-思科 Nexus 9000 系列应用中心基础设施ACI模式数据中心交换机中的一个漏洞可能会让攻击者隐秘地访问到系统资源。
这个新发现的漏洞,被通用漏洞评分系统给到了 9.8 分(满分 10 分),思科表示,它是思科 Nexus 9000 系列的安全 shell ssh密钥管理方面的问题这个漏洞允许远程攻击者以 root 用户的权限来连接到受影响的系统。
**[ 另请阅读:如何规划一个软件定义的数据中心网络 ][3] ]**
思科表示,“这个漏洞是因为所有的设备都存在一对默认的 ssh 密钥对,攻击者可以使用提取到的密钥材料,并通过 IPv6 来创建连接到目标设备的 SSH 连接。这个漏洞仅能通过 IPv6 来进行利用IPv4 不会被攻击”。
型号为 Nexus 9000 系列且 NX-OS 软件版本在 14.1 之前的设备会受此漏洞的影响,该公司表示没有解决这个问题的办法。
然而,思科公司已经为解决这个漏洞发布了免费的软件更新。
该公司同样对 Nexus 9000 系列发布了一个“高危”级别的安全预警报告,报告中表示存在一种攻击,允许攻击者以 root 用户权限在受影响的设备上执行任意操作系统命令。思科表示,如果要用这种方式攻击成功,攻击者需要对应设备的有效的管理员用户凭证。
思科表示,这个漏洞是由于过于宽泛的系统文件权限造成的。攻击者可以通过向受影响的设备进行认证,构造一个精心设计的命令字符串,并将这个字符串写入到特定位置的文件里。攻击者通过这种方式来利用这个漏洞。
**[[通过 PluralSight 的综合在线课程成为一名认证信息安全系统工程师。现在提供为期 10 天的免费试用!][6] ]**
思科发布了解决这个漏洞的软件更新。
另外两个被评为“高危”级别的漏洞的影响范围同样包括 Nexus 9000 系列:
思科 Nexus 9000 系列软件后台操作功能中的漏洞,能够允许一个已认证的本地攻击者在受影响的设备上提升到 root 权限。这个漏洞是由于在受影响的设备上用户提供的文件验证不充分。思科表示,攻击者可以通过登录到受影响设备的命令行界面,并在文件系统的特定目录中构造一个精心设计过的文件,以此来利用这个漏洞。
交换机软件后台操作功能中的弱点能够允许攻击者登录到受影响设备的命令行界面,并在文件系统的特定目录里创建一个精心构造过的文件。思科表示,这个漏洞是由于在受影响的设备上用户提供的文件验证不充分。
思科同样为这些漏洞发布了软件更新。
此外,这些安全警告中的一部分是针对思科 FirePower 防火墙系列中大量的“高危”漏洞警告。
例如,思科写道,思科 Firepower 威胁防御软件的 SMB 协议预处理检测引擎中的多个漏洞能够允许未认证的相邻、远程攻击者造成拒绝服务攻击DoS的情况。
思科表示,思科 Firepower 2100 系列中思科 Firepower 软件里的内部数据包处理功能有另一个漏洞,能够让未认证的远程攻击者造成受影响的设备停止处理流量,从而导致 DOS 的情况。
软件补丁可用于这些漏洞。
其他的产品,比如思科自适应安全虚拟设备和 web 安全设备同样也有高优先级的补丁。
加入 Facebook 和 LinkedIn 中的网络世界社区,在最上面的主题里做评论。
--------------------------------------------------------------------------------
via: https://www.networkworld.com/article/3392858/cisco-issues-critical-security-warning-for-nexus-data-center-switches.html#tk.rss_all
作者:[Michael Cooney][a]
选题:[lujun9972][b]
译者:[hopefully2333](https://github.com/hopefully2333)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://www.networkworld.com/author/Michael-Cooney/
[b]: https://github.com/lujun9972
[1]: https://images.idgesg.net/images/article/2018/02/lock_broken_unlocked_binary_code_security_circuits_protection_privacy_thinkstock_873916354-100750739-large.jpg
[2]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-nexus9k-sshkey
[3]: https://www.networkworld.com/article/3284352/data-center/how-to-plan-a-software-defined-data-center-network.html
[4]: https://www.cisco.com/c/en/us/about/legal/cloud-and-software/end_user_license_agreement.html
[5]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-nexus9k-rpe
[6]: https://pluralsight.pxf.io/c/321564/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fpaths%2Fcertified-information-systems-security-professional-cisspr
[7]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-aci-hw-clock-util
[8]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-frpwr-smb-snort
[9]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-frpwr-dos
[10]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-asa-ipsec-dos
[11]: https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190501-wsa-privesc
[12]: https://www.facebook.com/NetworkWorld/
[13]: https://www.linkedin.com/company/network-world

View File

@ -0,0 +1,353 @@
[#]: collector: (lujun9972)
[#]: translator: (cycoe)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Using Pygame to move your game character around)
[#]: via: (https://opensource.com/article/17/12/game-python-moving-player)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
用 Pygame 使你的游戏角色移动起来
======
在本系列的第四部分,学习如何编写移动游戏角色的控制代码。
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python4-game.png?itok=tXFHaLdt)
在这个系列的第一篇文章中,我解释了如何使用 Python 创建一个简单的[基于文本的骰子游戏][1]。在第二部分中,我向你们展示了如何从头开始构建游戏,即从 [创建游戏的环境][2] 开始。然后在第三部分,我们[创建了一个玩家妖精][3],并且使它在你的(而不是空的)游戏世界内生成。你可能已经注意到,如果你不能移动你的角色,那么游戏不是那么有趣。在本篇文章中,我们将使用 Pygame 来添加键盘控制,如此一来你就可以控制你的角色的移动。
在 Pygame 中有许多函数可以用来添加(除键盘外的)其他控制,但如果你正在敲击 Python 代码,那么你一定是有一个键盘的,这将成为我们接下来会使用的控制方式。一旦你理解了键盘控制,你可以自己去探索其他选项。
在本系列的第二篇文章中,你已经为退出游戏创建了一个按键,移动角色的(按键)原则也是相同的。但是,使你的角色移动起来要稍微复杂一点。
让我们从简单的部分入手:设置控制器按键
### 为控制你的玩家妖精设置按键
在 IDLE、Ninja-IDE 或文本编辑器中打开你的 Python 游戏脚本。
因为游戏需要时刻“监听”键盘事件,所以你写的代码需要连续运行。你知道应该把需要在游戏周期中持续运行的代码放在哪里吗?
如果你回答“放在主循环中”,那么你是正确的!记住除非代码在循环中,否则(大多数情况下)它只会运行仅一次。如果它被写在一个从未被使用的类或函数中,它可能根本不会运行。
要使 Python 监听传入的按键,将如下代码添加到主循环。目前的代码还不能产生任何的效果,所以使用 `print` 语句来表示成功的信号。这是一种常见的调试技术。
```
while main == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                print('left')
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                print('right')
            if event.key == pygame.K_UP or event.key == ord('w'):
            print('jump')
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                print('left stop')
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                print('right stop')
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False    
```
一些人偏好使用键盘字母 W、A、S 和 D 来控制玩家角色,而另一些偏好使用方向键。因此确保你包含了两种选项。
**注意:**当你在编程时,同时考虑所有用户是非常重要的。如果你写代码只是为了自己运行,那么很可能你会成为你写的程序的唯一用户。更重要的是,如果你想找一个通过写代码赚钱的工作,你写的代码就应该让所有人都能运行。给你的用户选择权,比如提供使用方向键或 WASD 的选项,是一个优秀程序员的标志。
使用 Python 启动你的游戏,并在你按下“上下左右”方向键或 A、D 和 W 键的时候查看控制台窗口的输出。
```
$ python ./your-name_game.py
  left
  left stop
  right
  right stop
  jump
```
这验证了 Pygame 可以正确地检测按键。现在是时候来完成使妖精移动的艰巨任务了。
### 编写玩家移动函数
为了使你的妖精移动起来,你必须为你的妖精创建一个属性代表移动。当你的妖精没有在移动时,这个变量被设为 `0`
如果你正在为你的妖精设置动画,或者你决定在将来为他设置动画,你还必须跟踪帧来使走路循环保持在轨迹上。
在 Player 类中创建如下变量。开头两行作为上下文对照(如果你一直跟着做,你的代码中就已经有这两行),因此只需要添加最后三行:
```
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.movex = 0 # 沿 X 方向移动
        self.movey = 0 # 沿 Y 方向移动
        self.frame = 0 # 帧计数
```
设置好了这些变量,是时候去为妖精移动编写代码了。
玩家妖精不需要时刻响应控制,优势它并没有在移动。控制妖精的代码,仅仅只是玩家妖精所有能做的事情中的一小部分。在 Python 中当你想要使一个对象做某件事并独立于剩余其他代码时你可以将你的新代码放入一个函数。Python 的函数以关键词 `def` 开头,(该关键词)代表了定义函数。
在你的 Player 类中创建如下函数,来为你的妖精在屏幕上的位置增加几个像素。现在先不要担心你增加几个像素,这将在后续的代码中确定。
```
    def control(self,x,y):
        '''
        控制玩家移动
        '''
        self.movex += x
        self.movey += y
```
为了在 Pygame 中移动妖精,你需要告诉 Python 在新的位置重绘妖精,以及这个新位置在哪里。
因为玩家妖精并不总是在移动,所以更新只需要是 Player 类中的一个函数。将此函数添加前面创建的 `control` 函数之后。
要使妖精看起来像是在行走(或者飞行,或是你的妖精应该做的任何事),你需要在按下适当的键时改变它在屏幕上的位置。要让它在屏幕上移动,你需要将它的位置(由 `self.rect.x``self.rect.y` 属性指定)重新定义为当前位置加上已应用的任意 `movex``movey`。(移动的像素数量将在后续进行设置。)
```
    def update(self):
        '''
        更新妖精位置
        '''
        self.rect.x = self.rect.x + self.movex        
```
对 Y 方向做同样的处理:
```
        self.rect.y = self.rect.y + self.movey
```
对于动画,在妖精移动时推进动画帧,并使用相应的动画帧作为玩家的图像:
```
        # 向左移动
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[self.frame//ani]
        # 向右移动
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3*ani:
                self.frame = 0
            self.image = self.images[(self.frame//ani)+4]
```
通过设置一个变量来告诉代码为你的妖精位置增加多少像素,然后在触发你的玩家妖精的函数时使用这个变量。
首先,在你的设置部分创建这个变量。在如下代码中,开头两行是上下文对照,因此只需要在你的脚本中增加第三行代码:
```
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10  # 移动多少个像素
```
现在你已经有了适当的函数和变量,使用你的按键来触发函数并将变量传递给你的妖精。
为此,将主循环中的 `print` 语句替换为玩家妖精的名字player、函数.control)以及你希望玩家妖精在每个循环中沿 X 轴和 Y 轴移动的步数。
```
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(steps,0)
            if event.key == pygame.K_UP or event.key == ord('w'):
                print('jump')
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                player.control(steps,0)
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                player.control(-steps,0)
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False
```
记住,`steps` 变量代表了当一个按键被按下时,你的妖精会移动多少个像素。如果当你按下 D 或右方向键时,你的妖精的位置增加了 10 个像素。那么当你停止按下这个键时,你必须(将 `step`)减 10`-steps`)来使你的妖精的动量回到 0。
现在尝试你的游戏。注意:它不会像你预想的那样运行。
为什么你的妖精仍无法移动?因为主循环还没有调用 `update` 函数。
将如下代码加入到你的主循环中来告诉 Python 更新你的玩家妖精的位置。增加带注释的那行:
```
    player.update()  # 更新玩家位置
    player_list.draw(world)
    pygame.display.flip()
    clock.tick(fps)
```
再次启动你的游戏来见证你的玩家妖精在你的命令下在屏幕上来回移动。现在还没有垂直方向的移动,因为这部分函数会被重力控制,不过这是另一篇文章中的课程了。
与此同时,如果你拥有一个摇杆,你可以尝试阅读 Pygame 中 [joystick][4] 模块相关的文档,看看你是否能通过这种方式让你的妖精移动起来。或者,看看你是否能通过[鼠标][5]与你的妖精互动。
最重要的是,玩的开心!
### 本教程中用到的所有代码
为了方便查阅,以下是目前本系列文章用到的所有代码。
```
#!/usr/bin/env python3
# 绘制世界
# 添加玩家和玩家控制
# 添加玩家移动控制
# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
import pygame
import sys
import os
'''
Objects
'''
class Player(pygame.sprite.Sprite):
'''
生成玩家
'''
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.frame = 0
self.images = []
for i in range(1,5):
img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
img.convert_alpha()
img.set_colorkey(ALPHA)
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
def control(self,x,y):
'''
控制玩家移动
'''
self.movex += x
self.movey += y
def update(self):
'''
更新妖精位置
'''
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# 向左移动
if self.movex < 0:
self.frame += 1
if self.frame > 3*ani:
self.frame = 0
self.image = self.images[self.frame//ani]
# 向右移动
if self.movex > 0:
self.frame += 1
if self.frame > 3*ani:
self.frame = 0
self.image = self.images[(self.frame//ani)+4]
'''
设置
'''
worldx = 960
worldy = 720
fps = 40 # 帧刷新率
ani = 4 # 动画循环
clock = pygame.time.Clock()
pygame.init()
main = True
BLUE = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)
ALPHA = (0,255,0)
world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load(os.path.join('images','stage.png')).convert()
backdropbox = world.get_rect()
player = Player() # 生成玩家
player.rect.x = 0
player.rect.y = 0
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10 # 移动速度
'''
主循环
'''
while main == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
main = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(-steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(steps,0)
if event.key == pygame.K_UP or event.key == ord('w'):
print('jump')
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(steps,0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(-steps,0)
if event.key == ord('q'):
pygame.quit()
sys.exit()
main = False
# world.fill(BLACK)
world.blit(backdrop, backdropbox)
player.update()
player_list.draw(world) # 更新玩家位置
pygame.display.flip()
clock.tick(fps)
```
你已经学了很多,但还仍有许多可以做。在接下来的几篇文章中,你将实现添加敌方妖精、模拟重力等等。与此同时,练习 Python 吧!
--------------------------------------------------------------------------------
via: https://opensource.com/article/17/12/game-python-moving-player
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[cycoe](https://github.com/cycoe)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/article/17/10/python-101
[2]: https://opensource.com/article/17/12/program-game-python-part-2-creating-game-world
[3]: https://opensource.com/article/17/12/program-game-python-part-3-spawning-player
[4]: http://pygame.org/docs/ref/joystick.html
[5]: http://pygame.org/docs/ref/mouse.html#module-pygame.mouse

View File

@ -0,0 +1,60 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Get started with Libki to manage public user computer access)
[#]: via: (https://opensource.com/article/19/5/libki-computer-access)
[#]: author: (Don Watkins https://opensource.com/users/don-watkins/users/tony-thomas)
开始使用 Libk i来管理公共用户访问计算机
======
Libki 是一个跨平台的计算机预约和时间管理系统。
![][1]
提供公共计算机的图书馆、学校、学院和其他组织需要一种管理用户访问权限的好方法 - 否则,就无法阻止某些人独占机器并确保每个人都有公平的时间。这是 [Libki][2] 要解决的问题。
Libki 是一个面向 Windows 和 Linux PC 的开源、跨平台的计算机预约和时间管理系统。它提供了一个基于 Web 的服务器和一个基于 Web 的管理系统,员工可以使用它来管理计算机访问,包括创建和删除用户、设置帐户时间限制、登出和禁止用户以及设置访问限制。
根据首席开发人员 [Kyle Hall][3] 所说Libki 主要用于 PC 时间控制,作为 Envisionware 的专有计算机访问控制软件的开源替代品。当用户登录 Libki 管理的计算机时,他们会有一段时间来使用计算机。时间到了之后,他们就会被登出。时间默认设置为 45 分钟,但可以使用基于 Web 的管理系统轻松调整。一些组织在登出用户之前提供 24 小时访问权限,而有的组织则使用它来跟踪使用情况而不设置时间限制。
Kyle 目前是 [ByWater Solutions][4] 的首席开发人员,该公司为图书馆提供开源软件解决方案(包括 Libki。在职业生涯早期他在宾夕法尼亚州的[米德维尔公共图书馆][5]担任 IT 技术时开发了 Libki。在其他员工的午休期间偶尔会要求他关注孩子的房间。图书馆使用纸质注册表来管理对儿童房间计算机的访问这意味着不断的监督和检查以确保来到那里的人能够公平地使用。
Kyle 说,“我发现这个系统很麻烦、很尴尬,我想找到一个解决方案。这个解决方案需要同时是 FOSS 和跨平台的。最后,没有现有的软件适合我们的特殊需求,那就是为什么我开发了 Libki。“
或者,正如 Libki 的网站所宣称的那样“Libki 的诞生是为了避免与青少年互动,现在允许图书馆员避免与世界各地的青少年互动!”
### 易于安装和使用
我最近决定在我经常在那里做志愿者的当地的公共图书馆尝试 Libki。我按照[文档][6]在 Ubuntu 18.04 Server 中自动进行了安装,它很快就启动起来了。
我计划在我们当地的图书馆支持 Libki但我想知道在那些没有 IT 相关经验的人或者无法构建和部署服务器的图书馆是怎样的。Kyle 说“ByWater Solutions 可以云端托管 Libki 服务器,这使得每个人的维护和管理变得更加简单。”
Kyle 表示ByWater 并不打算将 Libki 与其最受欢迎的产品,开源集成图书馆系统 ILSKoha 或其支持的任何其他[项目][7]捆绑在一起。他说: “Libki 和 Koha 是不同[类型]的软件,满足不同的需求,但它们在图书馆中确实很好地协同工作。事实上,我很早就开发了 Libki 的 SIP2 集成,因此它可以支持使用 Koha 进行单点登录,“ 。
### 如何贡献
Libki 客户端是 GPLv3 许可Libki 服务器是 AGPLv3 许可。Kyle 说他希望 Libki 拥有一个更加活跃和强大的社区,项目一直在寻找新人加入其[贡献者][8]。如果你想参加,请访问 [Libki 社区页面][9]并加入邮件列表。
--------------------------------------------------------------------------------
via: https://opensource.com/article/19/5/libki-computer-access
作者:[Don Watkins ][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/don-watkins/users/tony-thomas
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/desk_clock_job_work.jpg?itok=Nj4fuhl6
[2]: https://libki.org/
[3]: https://www.linkedin.com/in/kylemhallinfo/
[4]: https://opensource.com/article/19/4/software-libraries
[5]: https://meadvillelibrary.org/
[6]: https://manual.libki.org/master/libki-manual.html#_automatic_installation
[7]: https://bywatersolutions.com/projects
[8]: https://github.com/Libki/libki-server/graphs/contributors
[9]: https://libki.org/community/

View File

@ -1,140 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (warmfrog)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How to use advanced rsync for large Linux backups)
[#]: via: (https://opensource.com/article/19/5/advanced-rsync)
[#]: author: (Alan Formy-Duval https://opensource.com/users/alanfdoss/users/marcobravo)
如何使用高级工具 rsync 进行大的 Linux 备份
=====================================
基础的 rsync 命令通常足够来管理你的 Linux 备份,但是额外的选项使大数据集备份更快更强大。
![Filing papers and documents][1]
很明显备份一直是Linux世界的热门话题。回到 2017David Both 为 [Opensource.com][2] 的读者在"[使用 rsync 备份你的 Linux 系统][3]方面提了一些建议,在这年的更早时候,他发起了一项问卷调查询问大家,"[在 Linux 中你的 /home 目录的主要备份策略是什么][4]"在今年的另一个问卷调查中Don Watkins 问到,"[你使用哪种开源备份解决方案][5]"。
我的回复是 [rsync][6]。市场上有大量大的复杂的工具,对于管理磁带机或者存储库设备,这些可能是必要的,但是可能你需要的只是一个简单的开源命令行工具。
### rsync 基础
我为一个大概拥有 35,000 开发者并有着几十 TB 文件的全球组织管理二进制仓库。我经常一次移动或者归档上百 GB 的数据。使用的是 rsync。这种经历使我对这个简单的工具充满信心。所以是的我在家使用它来备份我的 Linux 系统)
基础的 rsync 命令很简单。
```
`rsync -av 源目录 目的地目录`
```
实际上,在任何指南中教的 rsync 命令在大多数通用情况下都运行的很好。然而,假设我们需要备份大量的数据。例如包含 2,000 个子目录的目录,每个包含 50GB 到 700GB 的数据。在这个目录运行 rsync 可能需要大量时间,尤其是当你使用 checksum 选项时(我倾向使用的)。
当我们试图同步大量数据或者通过慢的网络连接时,可能遇到性能问题。让我给你展示一些我使用的方法来确保好的性能和可靠性。
### 高级 rsync
当 rsync 运行时出现的第一行是:“正在发送增量文件列表。” 如果你搜索这一行,你将看到很多类似的问题:为什么它一直运行,或者为什么它似乎挂起了。
这里是一个基于这个场景的例子。假设我们有一个 **/storage** 的目录,我们想要备份到一个外部 USB 磁盘,我们可以使用下面的命令:
```
`rsync -cav /storage /media/WDPassport`
```
**c** 选项告诉 rsync 使用文件校验和而不是时间戳来决定改变的文件,这通常消耗的时间更久。为了分解 **/storage** 目录,我通过子目录同步,使用 **find** 命令。这是一个例子:
```
`find /storage -type d -exec rsync -cav {} /media/WDPassport \;`
```
这看起来可以,但是如果 **/storage** 目录有任何文件,它们将被跳过。因此,我们如何同步 **/storage** 目录中的文件呢?同样有一个细微的差别是具体的选项将造成 rsync 同步 **.** 目录,该目录是源目录自身;这意味着它会同步子目录两次,这并不是我们想要的。
长话短说,我的解决方案是一个 “双-递增”脚本。这允许我分解一个目录,例如,当你的 home 目录有多个大的目录,例如音乐或者家庭照片时,分解 **/home** 目录为单个的用户 home 目录。
这是我的脚本的一个例子:
```
HOMES="alan"
DRIVE="/media/WDPassport"
for HOME in $HOMES; do
cd /home/$HOME
rsync -cdlptgov --delete . /$DRIVE/$HOME
find . -maxdepth 1 -type d -not -name "." -exec rsync -crlptgov --delete {} /$DRIVE/$HOME \;
done
```
第一个 rsync 命令拷贝它在源目录中发现的文件和目录。然而,它将目录留空,因此我们能够通过 **find** 命令迭代他们。这通过传递 **d** 参数来完成,它告诉 rsync 不要递归目录。
```
`-d, --dirs transfer directories without recursing`
```
然后 **find** 命令传递每个目录来单独运行 rsync。之后 rsync 拷贝目录的内容。这通过传递 **r** 参数来完成,它告诉 rsync 要递归目录。
```
`-r, --recursive 递归进入目录`
```
这使得 rsync使用的增量文件保持在一个可管理的大小。
大多数 rsync 指南为了简便使用 **a** (或者 **archive** 参数。这实际是一个复合参数。
```
`-a, --archive 归档模式; equals -rlptgoD (no -H,-A,-X)`
```
我传递的其他参数包含在 **a** 中;这些是 **l** **p** **t** **g** **o**
```
-l, --links 复制符号链接作为符号链接
-p, --perms 保留权限
-t, --times 保留修改时间
-g, --group 保留组
-o, --owner 保留拥有者(只适用于超级管理员)
```
**\--delete** 选项告诉 rsync 删除目的地目录中所有在源目录不存在的任意文件。这种方式,运行的结果仅仅是复制。你同样可以排除 **.Trash** 目录或者 MacOS 创建的 **.DS_Store** 文件。
```
`-not -name ".Trash*" -not -name ".DS_Store"`
```
### 注意
最后一条建议: rsync 可以是破坏性的命令。幸运的是,它的睿智的创造者提供了 “空运行”的能力。如果我们加入 **n** 选项rsync 会显示预期的输出但不写任何数据。
```
`rsync -cdlptgovn --delete . /$DRIVE/$HOME`
```
这个脚本适用于非常大的存储规模和高延迟或者慢链接的情况。一如既往,我确信仍有提升的空间。如果你有任何建议,请在下方评论中分享。
--------------------------------------------------------------------------------
via: https://opensource.com/article/19/5/advanced-rsync
作者:[Alan Formy-Duval ][a]
选题:[lujun9972][b]
译者:[warmfrog](https://github.com/warmfrog)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/alanfdoss/users/marcobravo
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/documents_papers_file_storage_work.png?itok=YlXpAqAJ (Filing papers and documents)
[2]: http://Opensource.com
[3]: https://opensource.com/article/17/1/rsync-backup-linux
[4]: https://opensource.com/poll/19/4/backup-strategy-home-directory-linux
[5]: https://opensource.com/article/19/2/linux-backup-solutions
[6]: https://en.wikipedia.org/wiki/Rsync