Merge pull request #21 from LCTT/master

update
This commit is contained in:
zxp 2020-12-30 09:27:56 +08:00 committed by GitHub
commit 962e6d5883
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 580 additions and 144 deletions

View File

@ -1,36 +1,38 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: reviewer: (wxy)
[#]: publisher: (wxy)
[#]: url: (https://linux.cn/article-12967-1.html)
[#]: subject: (4 reasons businesses adopted open source in 2020)
[#]: via: (https://opensource.com/article/20/12/open-source-survey)
[#]: author: (Chris Grams https://opensource.com/users/cgrams)
2020 年企业采用开源的 4 个原因
======
根据 Tidelift 的第三次托管开源调查,根据公司规模,出现了差异。
![Metrics and a graph illustration][1]
Tidelift 的[第三次托管开源调查][2]发现企业在大流行期间正在转向开源44% 的组织报告他们将增加使用开源进行应用开发
> 根据 Tidelift 的第三次开源管理调查,根据公司规模,出现了差异。
我们以前见过类似现象。在以前的经济衰退中,组织转向开源[以节省成本][3],并因其[其他转型效益][4]而留下来。我们想了解哪些长期利益对不同规模的组织最有帮助。以下是我们发现的摘要。
![](https://img.linux.net.cn/data/attachment/album/202012/30/062849dn8amhiait1cvnne.jpg)
**开源正在推动成本和时间的节约,同时提高效率。**68% 的组织提到的一个关键驱动力是节约资金和开发时间,因为使用开源减少了开发人员从头开始编写新代码的时间。近半数 48% 报告称,它提高了应用开发和维护效率。拥有超过 1000 名员工的组织更有可能将此作为鼓励使用更多开源的原因61%,而少于 1000 人的组织为 41%)。
Tidelift 的[第三次开源管理调查][2]发现企业在大流行期间正在转向开源44% 的组织报告他们将增加使用开源进行应用开发。
我们以前见过类似现象。在以前的经济衰退中,组织转向开源[以节省成本][3],并因[其它一些转型收益][4]而留下来。我们想了解哪些长期收益对不同规模的组织最有帮助。以下是我们发现的摘要。
**开源正在推动成本和时间的节约,同时提高效率。** 68% 的组织提到的一个关键驱动力是节约资金和开发时间因为使用开源减少了开发人员从头开始编写新代码的时间。近半数48%)报告称,它提高了应用开发和维护效率。拥有超过 1000 名员工的组织更有可能将此作为鼓励使用更多开源的原因61%,而少于 1000 人的组织为 41%)。
![Graph showing reasons for using open source][5]
Tidelift ©2020
*Tidelift ©2020*
**在组织使用更多的开源的原因中,消除供应商锁定是一个重要原因。** 我们发现 40 的受访者将这视为主要原因。用开源软件取代昂贵的专有软件,可以确保组织更加灵活,避免对供应商的依赖。同样,规模较大的组织也倾向于这个原因。在拥有 1000 名以上员工的组织中,有 50% 的组织将此作为主要优势。
**增加开发人员的满意度是使用更多开源的另一个原因,有 31% 的组织提到了这一点.**随着企业对人才的激烈竞争,他们了解确保开发人员在工作中和使用的工具中感到快乐的价值。调查发现,开发人员使用的前三种语言是 JavaScript78%、Python52%)和 Java41%)。
**增加开发人员的满意度是使用更多开源的另一个原因,有 31% 的组织提到了这一点。** 随着企业对人才的激烈竞争,他们了解确保开发人员在工作中和使用的工具中感到快乐的价值。调查发现,开发人员使用的前三种语言是 JavaScript78%、Python52%)和 Java41%)。
**此外随着开源使用量的增加83% 的组织继续对其贡献,近一半的组织制定了管理贡献的政策**。这些政策包括:在工作时间对组织使用但不赞助或管理的项目的贡献、对他们赞助或管理的项目的贡献、在个人时间对与工作无关的(个人)项目的贡献、以及在工作时间对与工作无关的(个人)项目的贡献。
**此外随着开源使用量的增加83% 的组织继续对其贡献,近一半的组织制定了管理贡献的政策。** 这些政策包括:在工作时间对组织使用但不赞助或管理的项目的贡献、对他们赞助或管理的项目的贡献、在个人时间对与工作无关的(个人)项目的贡献、以及在工作时间对与工作无关的(个人)项目的贡献。
虽然向开源的长期迁移仍在继续但很明显COVID-19 的影响可能正在加速这一进程,组织继续从使用和贡献中获得更深层次的价值。
更多信息,请查看 [2020 年托管开源调查][2]的所有调查结果。
更多信息,请查看 [2020 年开源管理调查][2]的所有调查结果。
--------------------------------------------------------------------------------
@ -39,7 +41,7 @@ via: https://opensource.com/article/20/12/open-source-survey
作者:[Chris Grams][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,131 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How to use heredoc as a text editor)
[#]: via: (https://opensource.com/article/20/12/heredoc)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
How to use heredoc as a text editor
======
This obscure terminal feature provides a text editor in a pinch.
![woman on laptop sitting at the window][1]
Theres a somewhat obscure feature in Linux and Unix shells that allows you to open a sort of do-while loop for the [cat][2] command. Its called the _heredoc_, and it enables you to have, more or less, a text editor no matter what shell youre using. The syntax is:
```
`$ cat << EOF >> example.txt`
```
The string in the middle is, essentially, a conditional that stops the loop. That is, if you type alone on a line, the loop ends. During the loop, whatever you type into your terminal is piped into the destination file (in this case).
### Installing
As long as you have a terminal, you already have the ability to initiate a heredoc. Ive used this syntactical trick in [Bash][3], [tsch][4], and Korn shell.
### Using heredoc
To open a heredoc "session", you use the cat command with redirection that points first to cat with a terminating string (common convention is **EOF** for "End Of File", but it can actually be anything). After the terminating keyword, you redirect your output to a destination file. You're then able to type directly into your terminal, using most common shell keyboard shortcuts to navigate through your work. Your session ends when you type your designated terminating string on a line by itself. You know you're in a heredoc loop by the unique prompt (usually the **&gt;** character).
```
$ cat &lt;&lt; EOF &gt;&gt; example.txt
&gt; Everything you type here will be placed into example.txt when I type EOF on a line by itself. Until then, you can type...
&gt;
&gt; whatever...
&gt;
&gt; you want to type.
&gt;
&gt; EOF
$  
```
Everything you enter while your terminal is waiting for **EOF** is placed into the destination file. Prompt characters are omitted, and EOF itself is not part of the file.
```
Everything you type here will be placed into example.txt when I type EOF on a line by itself. Until then, you can type...
whatever...
you want to type.
```
Realistically, youre probably not going to use heredoc syntax as a substitute for a good text editor. It's a great quick hack to enter more than one line, but more than 10 lines or so starts to strain its usefulness. For instance, you cant go up to edit previous lines without triggering your shells [history][5] function. Depending on your shell and how it's configured, you may be able to go up, then down to recall your text, and then move back through your text with **Ctrl+B**. 
Most features of your shell work as expected, but theres probably no undo and very little error recovery.
And besides, even the most minimal of installs are likely to have at least [Vi][6] or [ed][7] installed.
And yet heredoc is still useful! It's more flexible than **echo**, and when youre working on a shell script, it's indispensable. For instance, imagine youre writing an installer script so you can automate the install of a set of custom applications. One of the applications isnt distributed with a `.dekstop` file, so it does not appear in your Application menu. To fix this, you decide to generate a `.desktop` file at install time.
Rather than writing a `.desktop` file and carrying it around as an external dependency for your install script, you could use heredoc in your install script itself:
```
#!/bin/sh
VERSION=${VERSION:-x.y.z}
PKGNAM=${VERSION:-example}
PKG="${PKGNAM}"-"${VERSION}"-`arch`.tgz
# download package
wget "${PKG}"
tar txvf "${PKG}"
# use here doc to create missing .desktop file
cat &lt;&lt; EOF &gt;&gt; $HOME/.local/share/applications/example.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name="${PKGNAM}"
Comment="${PKGNAM}"
Exec="${PKGNAM}" %F
EOF
# insert the rest of an install script...
```
You have automated text entry into a file, no text editor involved (except the one you use to write your script, obviously). Heres what the resulting `.desktop` file looks like:
```
[Desktop Entry]
Version=1.0
Type=Application
Name=example
Comment=example
Exec=example %F
```
As you can see, you can use variables within the heredoc, and theyre correctly resolved. The `EOF` string doesnt appear in the file; it only signals the end of the heredoc.
### Better than echo
The heredoc technique is generally considered easier than `echo` or [printf][8] because once youre "in" the document, youre free to do whatever you want. Its liberating in that sense, but its limited compared to a proper text editor.
Use heredoc for quick notes and for shell scripts, and never puzzle over how to dynamically generate configuration files again.
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/heredoc
作者:[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/sites/default/files/styles/image-full-size/public/lead-images/lenovo-thinkpad-laptop-window-focus.png?itok=g0xPm2kD (young woman working on a laptop)
[2]: https://opensource.com/article/19/2/getting-started-cat-command
[3]: https://opensource.com/article/20/4/bash-sysadmins-ebook
[4]: https://opensource.com/article/20/8/tcsh
[5]: https://opensource.com/article/20/6/bash-history-commands
[6]: https://opensource.com/article/19/3/getting-started-vim
[7]: https://opensource.com/article/20/12/gnu-ed
[8]: https://opensource.com/article/20/8/printf

View File

@ -0,0 +1,196 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Bring an old MacBook back to life with Linux)
[#]: via: (https://opensource.com/article/20/12/linux-macbook)
[#]: author: (Eric D. Schabell https://opensource.com/users/eschabell)
Bring an old MacBook back to life with Linux
======
It takes about an hour to make an outdated Mac useful again with Fedora.
![Digital images of a computer desktop][1]
Recently, I stumbled on an old MacBook Pro 13" from late 2011, with a 125GB SSD and 8GB RAM. I've taken this machine on trips around the world, and back in the day, I ran many a session, workshop, or demo to share all the AppDev goodness from JBoss technologies.
After verifying that its battery works, charging it up, and reinstalling a new OS X, it turns out that the Safari browser version is limited to an old security specification, which means it can't connect to a lot of HTTPS sites now. This renders this solution defunct.
What to do with this old thing?
It's been a few years since I worked solely on Linux workstations as a developer. I specifically worked on Fedora, so I decided to try to install the latest version on this MacBook Pro.
It took me just over an hour to get [Fedora 33][2] working on this laptop with the steps below.
### Download Fedora 33 and create a live USB
The first step is to find the right way to install Fedora. This machine has a CD slot, so you could burn an ISO and boot from it, but I chose to go straight to a bootable USB option.
I got on my other MacBook and visited the [Fedora Workstation site][3], which links to Fedora Media Writer. Click on the icon for your machine type (in my case, the Apple logo), and you get an installation package.
![Fedora Media Writer download screen][4]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Start installing it to see a graphical user interface (GUI) that guides you through the process. Select the Fedora Workstation 33 option:
![Fedora Workstation download in Fedora Media Writer][6]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Next, select the Create Live USB option in the top-right corner:
![Create Live USB button][7]
(Eric D. Shabell, [CC BY-SA 4.0][5])
The image will start to download, and you will see a drop-down menu to select where to install it:
![Downloading Fedora Workstation][8]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Plug in a USB stick with enough space available, then after the download finishes, you can select and install the image on it. Once it's finished, close the GUI and remove the USB stick.
### Install Linux
Insert the USB stick you created into the port on the left side of your MacBook Pro, and restart it while holding down the **Option** (or **Alt**) key just to the left of the **Cmd** key. This opens a menu of options to start the machine; use the EFI option, as that's the USB image.
The laptop will boot from the USB device, and you can follow the [normal Fedora installation][9] process. It helps if you can plug the MacBook Pro into a network cable connection, as the Broadcom WiFi device will not work out of the box.
![MacBook Pro][10]
(Eric D. Shabell, [CC BY-SA 4.0][5])
You should get the opportunity to install Fedora to your hard drive and put it on your machine permanently.
![Installing Fedora on MacBook Pro][11]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Once the installer completes, reboot your machine, and Fedora 33 should now be the option to boot from.
![MacBook Pro booting into Fedora][12]
(Eric D. Shabell, [CC BY-SA 4.0][5])
The only thing missing is a WiFi driver, so keep your network cable connected to install the development packages for the kernel you are running and to build the `broadcom-wl` driver for that kernel.
Verify the card you need for WiFi:
```
`$ lspci -vnn -d 14e4:`
```
There will be several items in the output, including something like:
```
Network controller [0280]: Broadcom Inc. and subsidiaries....
Subsystem: Apple Inc. AirPort Extreme...
```
Install a repository to pull the Broadcom stuff:
```
`$ su -c 'dnf install -y http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm'`
```
The next part is interesting: As you look at the running kernel, you'll see `v5.9.8-200.fc33`, but you will use the development kernel packages to build your Broadcom wireless driver. So, you need to install `v5.8.15-301.fc33` (available at the time of this writing). Check them using `uname -r`, and list the installed kernel packages using `sudo dnf list kernel`:
```
$ sudo dnf list kernel
kernel.x86_64                     5.8.15-301.fc33
kernel.x86_64                     5.9.8-200.fc33
```
Install the development packages:
```
`$ sudo dnf install -y akmods kernel-devel-5.8.15-301.fc33`
```
![Installing development packages][13]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Install the Broadcom wireless package:
```
`$ sudo dnf install -y broadcom-wl`
```
Build the kernel module:
```
`$ sudo akmods`
```
![Building the kernel module][14]
(Eric D. Shabell, [CC BY-SA 4.0][5])
Reboot your machine, and you should be able to view the wireless driver (`wl`) with:
```
`$ lsmod | grep wl`
```
Set up your wireless connection in Fedora:
![Set up wireless connection][15]
(Eric D. Shabell, [CC BY-SA 4.0][5])
This article is a bit out of the ordinary for me, but I hope it might help someone else enjoy some fun on the weekend with some old hardware!
> Going off the beaten path now... installing [#Fedora][16] on a macbook pro from 2011. Wish me luck! [pic.twitter.com/zlsESnq2Px][17]
>
> — Eric D. Schabell (@ericschabell) [November 22, 2020][18]
* * *
_This originally appeared on [Schabell.org][19] and is republished with permission._
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/linux-macbook
作者:[Eric D. Schabell][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/eschabell
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/computer_desk_home_laptop_browser.png?itok=Y3UVpY0l (Digital images of a computer desktop)
[2]: https://getfedora.org/en/
[3]: https://getfedora.org/en/workstation/download/
[4]: https://opensource.com/sites/default/files/uploads/fedoramediawriter.png (Fedora Media Writer download screen)
[5]: https://creativecommons.org/licenses/by-sa/4.0/
[6]: https://opensource.com/sites/default/files/uploads/fedoraworkstation33-installation.png (Fedora Workstation download in Fedora Media Writer)
[7]: https://opensource.com/sites/default/files/uploads/create-live-usb.png (Create Live USB button)
[8]: https://opensource.com/sites/default/files/uploads/download_fedora-workstation.png (Downloading Fedora Workstation)
[9]: https://docs.fedoraproject.org/en-US/fedora/f33/install-guide/install/Booting_the_Installation/
[10]: https://opensource.com/sites/default/files/uploads/macbook.jpeg (MacBook Pro)
[11]: https://opensource.com/sites/default/files/uploads/macbook_install-fedora.jpeg (Installing Fedora on MacBook Pro)
[12]: https://opensource.com/sites/default/files/uploads/macbook_fedora-boot.jpeg (MacBook Pro booting into Fedora)
[13]: https://opensource.com/sites/default/files/uploads/install-development-packages.jpeg (Installing development packages)
[14]: https://opensource.com/sites/default/files/uploads/build-kernel-module.jpeg (Building the kernel module)
[15]: https://opensource.com/sites/default/files/uploads/wireless-setup.jpeg (Set up wireless connection)
[16]: https://twitter.com/hashtag/Fedora?src=hash&ref_src=twsrc%5Etfw
[17]: https://t.co/zlsESnq2Px
[18]: https://twitter.com/ericschabell/status/1330434517883121665?ref_src=twsrc%5Etfw
[19]: https://www.schabell.org/2020/11/installing-fedora33-on-macbook-pro-13inch-late-2011.html

View File

@ -0,0 +1,79 @@
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Experience alternate computing with the Pe text editor)
[#]: via: (https://opensource.com/article/20/12/pe)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
Experience alternate computing with the Pe text editor
======
With elements of legacy systems, Pe is refreshingly simple with plenty
of additional features.
![Programming keyboard.][1]
The Haiku operating system is a bold but successful attempt at reviving an old OS called BeOS. In the 1990s, BeOS was positioned to become the foundation for the next evolution of the Apple Mac line of computers. Back in the 1990s, Apple Inc. was poised to acquire BeOS as its next generation operating system. At the last minute, however, Apple decided the price was too steep and acquired the UNIX-based NeXT operating system instead (and so Mac OS X was born). BeOS, however, had [made some remarkable progress][2] in multi-threading, file systems and attributes, and interface design. When the company finally folded, its userbase persisted.
I like to check in on Haiku every now and again, and while it still lists itself as beta software, its a striking achievement. Haiku is not Linux or UNIX, although it is POSIX-compliant. It stays true and compatible with BeOS, while making lots of improvements so that it largely feels like an OS that was developed today and not 30 years ago.
Between BeOS and Haiku, there have been lots of text editors on this platform, including **ne**, **pad**, **TextEdit**, **YATE**, and many more ([JOVE][3], [Emacs][4], and [Vim][5] have all been ported to it, too). For this article, however, I decided to try one of the default text editors included with Haiku: [the Pe editor][6] or _programmers editor_.
![Blue HAIKU desktop with Pe editor buffer, a white box with gray text][7]
### Install
Pe is written for Haiku OS and is released under a BSD license. To run it, you must have [Haiku installed][8]. Haiku is an operating system, so in theory, you could install it on a spare computer, but it also runs well in a virtual machine, such as [GNOME Boxes][9]. With Haiku installed on hardware or in a virtual machine, you have Pe by default.
### Launching
If youre new to BeOS or Haiku, then the easiest way to launch Pe is from the Deskbar. The Deskbar is a precursor to the modern Dock (like the one in macOS). Click the Haiku feather icon in the top-right corner of the desktop and select **Applications**. In the **Applications** submenu, click on **Pe** to launch the text editor.
Alternately, you can double-click the hard drive icon on the desktop and navigate to your home directory. Once there, right-click and create a new text file. Right-click on the text file and open it with Pe.
### Using Pe
When Pe first launches, it opens an empty buffer for text entry, with a menu and a toolbar at the top of the window. Once youre using Pe, the relative unfamiliarity of the OS fades away because Pe works largely like every other text editor youve ever used. You type text, and it appears on the screen. Its refreshingly simple, but there are lots of exciting features for you to discover.
#### Syntax highlighting
I tried writing in Asciidoc, Docbook XML, Markdown, Python, and C++. Both XML and C++ were recognized by Pe, and it automatically themed the keywords and elements. The color scheme only activated when a text file was saved with the appropriate file extension, so its not a bad idea to create your file on the desktop first and then open it with Pe to ensure that the correct syntax definition is loaded. Languages included in Pe are stored in **/system/apps/Pe/Languages**. The color themes followed the general visual design of Haiku itself: soft and calming shades, mostly earth tones, but easy to see. I usually use a dark theme on my desktop, but I found Haikus theme pleasing enough that I didnt feel a special urge to change it (which is convenient because I couldnt find a built-in dark theme that didnt involve me redefining every system color myself).
#### Text modifiers
Text editors ideally make editing text easy, and thats exactly the aim of the **Text** menu. This menu contains lots of convenience functions that most people writing text probably dont ever think about but that programmers seem to use all the time. Theres **twiddle** to swap characters (a quick way to change "hte" to "the" or "cmo" to "com," and so on), **change case** to alter capitalization of words and sentences, **shift left** and **shift right** to adjust indentation, **comment** and **uncomment** to transform a line into a comment, and much more. This menu, along with its robust **Preferences,** is where Pe really excels. Its a sign of developers who include what they, and other people serious about computing, want.
#### Saving
Saving and opening files are essentially the same in Pe as with most editors. You go to the **File** menu and select the action you want. However, Pe provides some extra services, too. You can open files from a server, save them directly to a server, save just one file, or save several files in a group.
#### Keyboard shortcuts
Most keyboard shortcuts in Haiku are based around the **Alt** key instead of the **Ctrl** key. I find this somewhat refreshing because Ive often felt that the **Ctrl** (or **Command** on macOS) is overloaded. Pe, being a native Haiku application, inherits this preference, although the keyboard shortcuts can be changed in its **Preferences**. Unfortunately, I think the **Alt** key ends up being overloaded in Haiku, so the change from one modifier key to another doesnt actually help relieve that issue (I still have no idea how a user is meant to know a global action from a local action), but its an interesting experiment. I find the **Alt** key is easier to press for common actions; its right next to the spacebar, after all, and in the future, I may swap **Ctrl** and **Alt** on Linux.
### Alternate computing
Haiku, and BeOS before it, are interesting if only because they let you peek into an alternate reality in which Apple didnt join in with the UNIX crowd. Its a fun diversion to look into an OS based on a unique system design, and its interesting to see what Apple has borrowed from BeOS, what Haiku has borrowed from UNIX, and how a little variety can help inform each of us about different perspectives and new ideas for interfacing with the tools we use every day of our lives. Whether youre looking at the OS or the text editor, take an afternoon to get some perspective with Pe.
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/pe
作者:[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/sites/default/files/styles/image-full-size/public/lead-images/programming_keyboard_coding.png?itok=E0Vvam7A (Programming keyboard.)
[2]: http://birdhouse.org/beos/bible
[3]: https://opensource.com/article/20/12/jove-emacs
[4]: https://opensource.com/article/20/12/emacs
[5]: https://opensource.com/article/20/12/vi-text-editor
[6]: http://github.com/olta/pe
[7]: https://opensource.com/sites/default/files/uploads/haiku-31_days-pe-opensource.jpg (Blue HAIKU desktop with Pe editor buffer, a white box with gray text)
[8]: http://haiku-os.org
[9]: https://opensource.com/article/19/5/getting-started-gnome-boxes-virtualization

View File

@ -0,0 +1,159 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Show progress in your Python apps with tqdm)
[#]: via: (https://opensource.com/article/20/12/tqdm-python)
[#]: author: (Moshe Zadka https://opensource.com/users/moshez)
Show progress in your Python apps with tqdm
======
If your program takes a while to show results, avoid frustrating users
by showing the progress it's making.
![arrows cycle symbol for failing faster][1]
The Semitic root _q-d-m_ in Aramaic, Hebrew, and Arabic is usually associated with moving forward or making progress. The Arabic word _taqaddum_ (تقدّم) means "progress." Progress is important. As every feel-good movie will tell you, the journey is as important as the destination.
Most programs have a clear goal, a desired end state. Sometimes, calculating that end state can take a long time. While computers don't care, not having feelings, people do. Humans are not happy sitting around waiting without any visible sign of progress. Doubt creeps in. Has the program crashed? Is the disk thrashing? Did the operating system allocate all its computing resources to other tasks?
Like justice, progress must be seen, not merely done. The [tqdm][2] Python library helps make progress explicit.
The tqdm module works with the console, but it also has special support for one of my favorite environments: Jupyter. To use tqdm in Jupyter, you need to import the `notebook` submodule and have [ipywidgets][3] installed. The `notebook` submodule is interface-compatible with tqdm.
This means you can do some import-time shenanigans to import the correct module while keeping tqdm usage the same. The trick is to check if the `__main__` module has the global variable `get_ipython`. While this is a heuristic, it is a reasonably accurate one:
```
import sys
if hasattr(sys.modules["__main__"], "get_ipython"):
    from tqdm import notebook as tqdm
else:
    import tqdm
```
The simplest case is when something needs to run for a certain number of iterations (known in advance), and each of those iterations takes about the same amount of time. For example, there is an algorithm to calculate the square root of any number by starting with 1 as a guess and then calculating an improved guess:
```
def improve_guess(rt, n):
    return (rt + n/rt) / 2
```
A small number of improvements gets you pretty close. For example, you can calculate the square root of two:
```
guess = 1
target = 2
for i in tqdm.trange(10):
    guess = improve_guess(guess, target)
```
![tqdm output][4]
(Moshe Zadke, [CC BY-SA 4.0][5])
It's correct to 10 decimal places!
```
`round(2 - guess*guess, 10)`[/code] [code]`0.0`
```
A slightly more complicated example is when the number of elements is known, and processing each element takes a similar amount of time. As an example, you can calculate the product of some numbers. For that, you'll want some random numbers:
```
import random
numbers = [random.uniform(0, 2.8) for i in range(100)]
numbers[:5]
[/code] [code]
[2.6575636572230916,
0.1286674965830302,
1.0634250104041332,
1.1760969844376505,
0.45192978568125486]
```
Now that the numbers are in, it's time to multiply them. The easiest way to use tqdm is by wrapping a Python iterable. The values will be the same, but tqdm will also display a progress bar:
```
result = 1
for num in tqdm.tqdm(numbers):
    result *= num
result
[/code] [code]`2.4081854901728303`
```
![tqdm output][6]
(Moshe Zadke, [CC BY-SA 4.0][5])
However, not all things are predictable. One of the least predictable things is network speed. When you download a big file, the only way to measure progress is to explicitly check how much has been downloaded:
```
url = "<https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz>"
import httpx
with httpx.stream("GET", url) as response:
    total = int(response.headers["Content-Length"])
    with tqdm.tqdm(total=total) as progress:
        for chunk in response.iter_bytes():
            progress.update(len(chunk))
```
![tqdm output][7]
(Moshe Zadke, [CC BY-SA 4.0][5])
Sometimes, it makes sense to "nest" progress bars. For example, if you are downloading a directory, you'll want a progress bar tracking the files and a progress bar per file.
Here is an example (but without actually downloading a directory):
```
files = [f"vid-{i}.mp4" for i in range(4)]
for fname in tqdm.tqdm(files, desc="files"):
    total = random.randrange(10**9, 2 * 10**9)
    with tqdm.tqdm(total=total, desc=fname) as progress:
        current = 0
        while current &lt; total:
            chunk_size = min(random.randrange(10**3, 10**5), total - current)
            current += chunk_size
            if random.uniform(0, 1) &lt; 0.01:
                time.sleep(0.1)
            progress.update(chunk_size)
```
![tqdm output][8]
(Moshe Zadke, [CC BY-SA 4.0][5])
So, if your program takes a while to show final results, avoid frustrating your users: Show the progress it's making!
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/tqdm-python
作者:[Moshe Zadka][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/moshez
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/fail_progress_cycle_momentum_arrow.png?itok=q-ZFa_Eh (arrows cycle symbol for failing faster)
[2]: https://pypi.org/project/tqdm/
[3]: https://opensource.com/article/20/11/daily-journal-jupyter
[4]: https://opensource.com/sites/default/files/uploads/output_8_0.png (tqdm output)
[5]: https://creativecommons.org/licenses/by-sa/4.0/
[6]: https://opensource.com/sites/default/files/uploads/output_15_0.png (tqdm output)
[7]: https://opensource.com/sites/default/files/uploads/output_18_0.png (tqdm output)
[8]: https://opensource.com/sites/default/files/uploads/output_21_0.png (tqdm output)

View File

@ -0,0 +1,131 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How to use heredoc as a text editor)
[#]: via: (https://opensource.com/article/20/12/heredoc)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
如何使用 heredoc 作为一个文本编辑器
======
这个不起眼的终端功能在紧要关头提供了一个文本编辑器。
![woman on laptop sitting at the window][1]
在 Linux 和 Unix shells 中有一个不为人知的功能,它能让你为 [cat][2] 命令打开一个 do-while 循环。它被称为 _heredoc_,无论你使用什么 shell它都能让你或多或少地拥有一个文本编辑器。它的语法是
```
`$ cat << EOF >> example.txt`
```
中间的字符串,本质上是一个停止循环的条件。也就是说,如果你在一行中单独输入它,循环就会结束。在循环过程中,无论你在终端中输入什么,都会被管道传送到目标文件中(在本例中)。
### 安装
只要你有一个终端,你就能够启动 heredoc。我在 [Bash][3]、[tsh][4] 和 Korn shell 中使用过这个语法技巧。
### 使用 heredoc
要打开一个 heredoc “会话”,你可以使用 cat 命令重定向,它首先指向具有终止字符串的 cat常见约定是 **EOF**,代表 “End Of File”但它实际上可以是任何东西。在终止关键字之后你将输出重定向到一个目标文件。然后你就可以直接在终端中输入使用最常见的 shell 键盘快捷键来处理你的工作。当你在一行上输入你指定的终止字符串时,你的会话就结束了。你可以通过唯一的提示符(通常是 **&gt;**)知道你是在一个 heredoc 循环中。
```
$ cat &lt;&lt; EOF &gt;&gt; example.txt
&gt; Everything you type here will be placed into example.txt when I type EOF on a line by itself. Until then, you can type...
&gt;
&gt; whatever...
&gt;
&gt; you want to type.
&gt;
&gt; EOF
$  
```
在终端等待 **EOF**你输入的所有内容都会被放入目标文件中提示符被省略EOF 本身也不是文件的一部分。
```
Everything you type here will be placed into example.txt when I type EOF on a line by itself. Until then, you can type...
whatever...
you want to type.
```
现实中,你可能不会用 heredoc 语法来代替一个好的文本编辑器。它是一个很好的快速处理,可以输入多行,但超过 10 行左右就开始限制它的作用了。例如,如果不触发你 shell 的 [history][5] 功能,你就不能编辑以前的行。根据你的 shell 和配置,你可能可以先向上,然后向下来调用你的文本,然后用 **Ctrl+B** 来后退。 
你的 shell 的大部分功能都能正常工作,但可能没有撤销功能,也没有什么错误恢复功能。
此外,即使是最简安装,也可能至少安装了 [Vi][6] 或 [ed][7]。
然而 heredoc 还是很有用的!它比 **echo** 更灵活,当你在使用 shell 脚本时,它是不可缺少的。例如,想象一下你正在编写一个安装脚本,这样你就可以自动安装一组自定义应用。其中一个应用没有生成 `.dekstop`文件,所以它不会出现在你的应用菜单中。为了解决这个问题,你决定在安装时生成一个 `.desktop` 文件。
与其编写一个 `.desktop` 文件,然后作为安装脚本的外部依赖,不如在安装脚本中使用 heredoc
```
#!/bin/sh
VERSION=${VERSION:-x.y.z}
PKGNAM=${VERSION:-example}
PKG="${PKGNAM}"-"${VERSION}"-`arch`.tgz
# download package
wget "${PKG}"
tar txvf "${PKG}"
# use here doc to create missing .desktop file
cat &lt;&lt; EOF &gt;&gt; $HOME/.local/share/applications/example.desktop
[Desktop Entry]
Version=1.0
Type=Application
Name="${PKGNAM}"
Comment="${PKGNAM}"
Exec="${PKGNAM}" %F
EOF
# insert the rest of an install script...
```
你可以自动将文本输入到一个文件中,不需要文本编辑器(当然,除了你用来写脚本的那个)。下面是生成的 `.desktop` 文件的样子:
```
[Desktop Entry]
Version=1.0
Type=Application
Name=example
Comment=example
Exec=example %F
```
正如你所看到的,你可以在 heredoc 中使用变量,而且它们得到了正确的解析。`EOF` 字符串并没有出现在文件中,它只是标志着 heredoc 的结束。
### 比 echo 更好
heredoc 技术通常被认为比 `echo` 或 [printf][8] 更容易,因为一旦你“进入”了文档,你就可以自由地做任何你想做的事情。从这个意义上说,它是自由的,但与合适的文本编辑器相比,它是有限的。
使用 heredoc 来做快速笔记和 shell 脚本,再也不用为如何动态生成配置文件而烦恼了。
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/12/heredoc
作者:[Seth Kenlon][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/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/lenovo-thinkpad-laptop-window-focus.png?itok=g0xPm2kD (young woman working on a laptop)
[2]: https://opensource.com/article/19/2/getting-started-cat-command
[3]: https://opensource.com/article/20/4/bash-sysadmins-ebook
[4]: https://opensource.com/article/20/8/tcsh
[5]: https://opensource.com/article/20/6/bash-history-commands
[6]: https://opensource.com/article/19/3/getting-started-vim
[7]: https://opensource.com/article/20/12/gnu-ed
[8]: https://opensource.com/article/20/8/printf