diff options
-rw-r--r-- | CONTRIBUTING.markdown | 94 | ||||
-rw-r--r-- | awk.html.markdown | 31 | ||||
-rw-r--r-- | docker.html.markdown | 409 | ||||
-rw-r--r-- | es-es/awk-es.html.markdown | 44 | ||||
-rw-r--r-- | fr-fr/awk-fr.html.markdown | 106 | ||||
-rw-r--r-- | pt-br/awk-pt.html.markdown | 4 | ||||
-rw-r--r-- | python.html.markdown | 1 |
7 files changed, 416 insertions, 273 deletions
diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 8d2a8320..430ecea0 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -16,27 +16,29 @@ review them more effectively and/or individually. ## Style Guidelines -- **Keep lines under 80 chars** - + Try to keep **line length in code blocks to 80 characters or fewer**. - + Otherwise, the text will overflow and look odd. -- **Prefer example to exposition** - + Try to use as few words as possible. - + Code examples are preferred over exposition in all cases. -- **Eschew surplusage** - + We welcome newcomers, but the target audience for this site is programmers - with some experience. - + Try to avoid explaining basic concepts except for those specific to the - language in question. - + Keep articles succinct and scannable. We all know how to use Google here. -- **Use UTF-8** - + For translations (or EN articles with non-ASCII characters) please make sure - your file is UTF-8 encoded. - + Try to leave out the byte-order-mark at the start of the file. (`:set nobomb` - in Vim) - + You can check if the file contains a BOM on Linux/Unix systems by running +* **Keep lines under 80 chars** + * Try to keep **line length in code blocks to 80 characters or fewer**. + * Otherwise, the text will overflow and look odd. + * This and other potential pitfalls to format the content consistently are + identified by the freely available + [markdownlint](https://github.com/markdownlint/markdownlint). +* **Prefer example to exposition** + * Try to use as few words as possible. + * Code examples are preferred over exposition in all cases. +* **Eschew surplusage** + * We welcome newcomers, but the target audience for this site is programmers + with some experience. + * Try to avoid explaining basic concepts except for those specific to the + language in question. + * Keep articles succinct and scannable. We all know how to use Google here. +* **Use UTF-8** + * For translations (or EN articles with non-ASCII characters) please ensure + your file is UTF-8 encoded. + * Try to leave out the byte-order-mark at the start of the file (in Vim, use + `:set nobomb`). + * You can check if the file contains a BOM on Linux/Unix systems by running `file language.html.markdown` You will see this if it uses a BOM: - `UTF-8 Unicode (with BOM) text`. - + `UTF-8 Unicode (with BOM) text`. ### Header configuration @@ -47,31 +49,31 @@ some key information be defined in the header. The following fields are necessary for English articles about programming languages: -- **language** The *programming language* in question -- **contributors** A list of [author, URL] lists to credit +* **language** The *programming language* in question +* **contributors** A list of [author, URL] lists to credit Other fields: -- **category**: The category of the article. So far, can be one of *language*, +* **category**: The category of the article. So far, can be one of *language*, *tool* or *Algorithms & Data Structures*. Defaults to *language* if omitted. -- **filename**: The filename for this article's code. It will be fetched, mashed +* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable. - + For non-English articles, *filename* should have a language-specific - suffix. -- **lang**: For translations, the human language this article is in. For + * For non-English articles, *filename* should have a language-specific + suffix. +* **lang**: For translations, the human language this article is in. For categorization, mostly. Here's an example header for an Esperanto translation of Ruby: ```yaml ---- +*-- language: ruby filename: learnruby-epo.ruby contributors: - ["Doktor Esperanto", "http://example.com/"] - ["Someone else", "http://someoneelseswebsite.com/"] lang: ep-ep ---- +*-- ``` ### Should I add myself as a Contributor? @@ -85,21 +87,25 @@ addition or not. You can build the site locally to test your changes. Follow the steps below. -* Install Ruby language runtime and RubyGems. See [here](https://middlemanapp.com/basics/install/) for more details. -* Clone or zip download the [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) repo. - * `git clone https://github.com/adambard/learnxinyminutes-site` +* Install Ruby language runtime and RubyGems. See + [here](https://middlemanapp.com/basics/install/) + for more details. +* Clone or zip download the + [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) + repository. + * `git clone https://github.com/adambard/learnxinyminutes-site` * Install Middleman and other required dependencies using Bundler. - * `cd learnxinyminutes-site/` - * `bundle install` + * `cd learnxinyminutes-site/` + * `bundle install` * Get the source in place - * Copy the contents of your clone of the fork of learnxinyminutes-docs repo - into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs` - folder inside the `docs` folder, it should just contain all the repo - contents. - * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`. - * `cd source/docs/` - * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/` + * Copy the contents of your clone of the fork of learnxinyminutes-docs repo + into the `source/docs` folder. There shouldn't be a `learnxinyminutes-docs` + folder inside the `docs` folder, it should just contain all the repo + contents. + * Checkout your fork of the learnxinyminutes-docs repo as `source/docs`. + * `cd source/docs/` + * `git clone https://github.com/YOUR-USERNAME/learnxinyminutes-docs ./source/docs/` * Build the site or run a development server to test your changes (NOTE: run -these commands at `learnxinyminutes-site/`). - * Build - `bundle exec middleman build` - * Dev server - `bundle exec middleman --force-polling --verbose` + these commands at `learnxinyminutes-site/`). + * Build - `bundle exec middleman build` + * Dev server - `bundle exec middleman --force-polling --verbose` diff --git a/awk.html.markdown b/awk.html.markdown index 34013251..dc22a2bd 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -118,12 +118,12 @@ BEGIN { # Arrays arr[0] = "foo"; arr[1] = "bar"; - + # You can also initialize an array with the built-in function split() - + n = split("foo:bar:baz", arr, ":"); - - # You also have associative arrays (actually, they're all associative arrays) + + # You also have associative arrays (indeed, they're all associative arrays) assoc["foo"] = "bar"; assoc["bar"] = "baz"; @@ -216,7 +216,8 @@ function string_functions( localvar, arr) { match(localvar, "t"); # => 4, since the 't' is the fourth character # Split on a delimiter - n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 + n = split("foo-bar-baz", arr, "-"); + # result: a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 # Other useful stuff sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" @@ -238,9 +239,9 @@ function io_functions( localvar) { # AWK doesn't have file handles, per se. It will automatically open a file # handle for you when you use something that needs one. The string you used # for this can be treated as a file handle, for purposes of I/O. This makes - # it feel sort of like shell scripting, but to get the same output, the string - # must match exactly, so use a variable: - + # it feel sort of like shell scripting, but to get the same output, the + # string must match exactly, so use a variable: + outfile = "/tmp/foobar.txt"; print "foobar" > outfile; @@ -261,7 +262,7 @@ function io_functions( localvar) { # Reads a line from a file and stores in localvar infile = "/tmp/foobar.txt"; - getline localvar < infile; + getline localvar < infile; close(infile); } @@ -273,10 +274,10 @@ function io_functions( localvar) { # When you pass arguments to AWK, they are treated as file names to process. # It will process them all, in order. Think of it like an implicit for loop, # iterating over the lines in these files. these patterns and actions are like -# switch statements inside the loop. +# switch statements inside the loop. /^fo+bar$/ { - + # This action will execute for every line that matches the regular # expression, /^fo+bar$/, and will be skipped for any line that fails to # match it. Let's just print the line: @@ -376,11 +377,15 @@ END { } ``` + Further Reading: * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU Awk is found on most Linux systems. * [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) -* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical summary and list of "gotchas" (places where different implementations may behave in different or unexpected ways). +* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical + summary and list of "gotchas" (places where different implementations may + behave in different or unexpected ways). * [basic libraries for awk](https://github.com/dubiousjim/awkenough) diff --git a/docker.html.markdown b/docker.html.markdown index 1df49cc3..e18db5c9 100644 --- a/docker.html.markdown +++ b/docker.html.markdown @@ -5,144 +5,277 @@ filename: docker.bat contributors:
- ["Ruslan López", "http://javapro.org/"]
- ["Michael Chen", "https://github.com/ML-Chen"]
+ - ["Akshita Dixit", "https://github.com/akshitadixit"]
+ - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"]
---
-```bat
-:: download, install and run hello-world image
-docker run hello-world
-
-:: if this is the first time you should be able to see the message
-:: Unable to find image 'hello-world:latest' locally
-:: latest: Pulling from library/hello-world
-:: 1b930d010525: Pull complete
-:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064
-:: Status: Downloaded newer image for hello-world:latest
-::
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-:: now let's see currently running images
-docker ps
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: let's see the images we have ran previously
-docker ps -a
-
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago
-:: happy_poincare
-:: the name part is generated automatically so it probably will be different for you
-
-:: let's remove our previously generated image
-docker rm happy_poincare
-
-:: let's test if it was really deleted
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-
-:: specify a custom name for the container
-docker run --name test_container hello-world
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago
-:: test_container
-:: as you can see the name is now what we have specified
-
-:: retrieve logs from a named container
-docker logs test_container
-:: Hello from Docker!
-:: This message shows that your installation appears to be working correctly.
-::
-:: To generate this message, Docker took the following steps:
-:: 1. The Docker client contacted the Docker daemon.
-:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
-:: (amd64)
-:: 3. The Docker daemon created a new container from that image which runs the
-:: executable that produces the output you are currently reading.
-:: 4. The Docker daemon streamed that output to the Docker client, which sent it
-:: to your terminal.
-::
-:: To try something more ambitious, you can run an Ubuntu container with:
-:: $ docker run -it ubuntu bash
-::
-:: Share images, automate workflows, and more with a free Docker ID:
-:: https://hub.docker.com/
-::
-:: For more examples and ideas, visit:
-:: https://docs.docker.com/get-started/
-
-docker rm test_container
-
-docker run ubuntu
-:: Unable to find image 'ubuntu:latest' locally
-:: latest: Pulling from library/ubuntu
-:: 2746a4a261c9: Pull complete
-:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4
-:: Status: Downloaded newer image for ubuntu:latest
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago
-:: relaxed_nobel
-
-:: running a container in an interactive mode
-docker run -it ubuntu
-:: root@e2cac48323d2:/# uname
-:: Linux
-:: root@e2cac48323d2:/# exit
-:: exit
-
-docker rm relaxed_nobel
-
-docker ps -a
-:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
-:: NAMES
-:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago
-:: nifty_goldwasser
-
-docker rm nifty_goldwasser
+Docker is a tool that helps you build, test, ship and run applications
+seamlessly across various machines. It replicates the environment our software
+needs on any machine. You can get Docker for your machine from
+https://docs.docker.com/get-docker/
+
+It has grown in popularity over the last decade due to being lightweight and
+fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker
+does not need a full blown OS of its own to be loaded to start and does not
+compete for resources other than what the application it is running will use.
+VMs on the other hand are pretty resource intensive on our processors, disks and
+memory hence running multiple VMs for various applications becomes a challenge
+in a limited capacity architecture.
+
+<pre>
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ ┌───────────────────┐ │ │ ┌──────────────────┐ │
+│ │ Guest OS │ │ │ │ Guest OS │ │
+│ └───────────────────┘ │ │ └──────────────────┘ │
+│ VM1 │ │ VM2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hypervisor │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Host OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (VM based architecture)
+
+┌────────────────────────┐ ┌───────────────────────┐
+│ ┌───────────┐ │ │ ┌───────────┐ │
+│ │ App │ │ │ │ App │ │
+│ └───────────┘ │ │ └───────────┘ │
+│ ┌────────┐ ┌────────┐ │ │ ┌────────┐ ┌───────┐ │
+│ │ Libs │ │ Deps │ │ │ │ Libs │ │ Deps │ │
+│ └────────┘ └────────┘ │ │ └────────┘ └───────┘ │
+│ Container1 │ │ Container2 │
+└────────────────────────┘ └───────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Docker │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ OS │
+└──────────────────────────────────────────────────┘
+┌──────────────────────────────────────────────────┐
+│ Hardware Infrastructure │
+└──────────────────────────────────────────────────┘
+ (Docker based architecture)
+
+</pre>
+
+Couple of terms we will encounter frequently are Docker Images and Docker
+Containers. Images are packages or templates of containers all stored in a
+container registry such as [Docker Hub](https://hub.docker.com/). Containers
+are standalone, executable instances of these images which include code,
+runtime, system tools, system libraries and settings - everything required to
+get the software up and running. Coming to Docker, it follows a client-server
+architecture wherein the CLI client communicates with the server component,
+which here is, the Docker Engine using RESTful API to issue commands.
+
+## The Docker CLI
+```bash
+# after installing Docker from https://docs.docker.com/get-docker/
+# To list available commands, either run `docker` with no parameters or execute
+# `docker help`
+$ docker
+
+>>> docker [OPTIONS] COMMAND [ARG...]
+ docker [ --help | -v | --version ]
+
+ A self-sufficient runtime for containers.
+
+ Options:
+ --config string Location of client config files (default "/root/.docker")
+ -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
+ -D, --debug Enable debug mode
+ --help Print usage
+ -H, --host value Daemon socket(s) to connect to (default [])
+ -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
+ --tls Use TLS; implied by --tlsverify
+ --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem")
+ --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem")
+ --tlskey string Path to TLS key file (default "/root/.docker/key.pem")
+ --tlsverify Use TLS and verify the remote
+ -v, --version Print version information and quit
+
+ Commands:
+ attach Attach to a running container
+ # […]
+
+$ docker run hello-world
+# `docker run <container-name>` is used to run a container, it will pull the
+# images from Docker Hub if they don't already exist in your system. Here the
+# docker client connects to the daemon which in turn pulls the "hello-world"
+# image from the Docker Hub. The daemon then builds a new container from the
+# image which runs the executable that produces the output streamed back to the
+# client that we see on our terminals.
+
+$ docker run -d ubuntu sleep 60s
+# The -d (or --detach) flag is when we want to run a container in the background
+# and return back to the terminal. Here we detach an ubuntu container from the
+# terminal, the output should be the id and the command exits. If we check
+# running containers, we should still see ours there:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould
+
+$ docker run <container-id> -p 3000:8000
+# The -p (or --publish) flag is used to expose port 8000 inside the container to
+# port 3000 outside the container. This is because the app inside the container
+# runs in isolation, hence the port 8000 where the app runs is private to the
+# container.
+
+$ docker run -i
+# or
+$ docker run -it
+# Docker runs our containers in a non-interactive mode i.e. they do not accept
+# inputs or work dynamically while running. The -i flag keeps input open to the
+# container, and the -t flag creates a pseudo-terminal that the shell can attach
+# to (can be combined as -it)
+
+$ docker ps -a
+# The `docker ps` command only shows running containers by default. To see all
+# containers, use the -a (or --all) flag
+# Running the above command should output something similar in the terminal:
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet
+
+
+$ docker stop hello-world
+# or
+$ docker start hello-world
+# The stop command simply stops one or more containers, and the start command
+# starts the container(s) up again! `docker start -a ubuntu` will attach our
+# detached container back to the terminal i.e. runs in the foreground
+
+$ docker create alpine
+# `docker create` creates a new container for us with the image specified (here,
+# alpine), the container does not auto-start unlike `docker run`. This command
+# is used to set up a container configuration and then `docker start` to shoot
+# it up when required. Note that the status is "Created":
+# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
+# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie
+
+$ docker rm 82f84
+# Removes one or more containers using their container ID.
+# P.S.: we can use only the first few characters of the entire ID to identify
+# containers
+
+$ docker images
+# Displays all images and their information, created here means the latest image
+# tag updated on Docker Hub:
+# REPOSITORY TAG IMAGE ID CREATED SIZE
+# ubuntu latest a8780b506fa4 9 days ago 77.8MB
+# alpine latest 9c6f07244728 3 months ago 5.54MB
+# hello-world latest feb5d9fea6a5 13 months ago 13.3kB
+
+$ docker rmi
+# Removes one or more images from your system which do not have their instances
+# (or containers as we know them) running. If the image has an attached
+# container, either delete the container first or use the -f (or --force) flag
+# to forcefully delete both the container and image.
+
+$ docker pull busybox
+# The pull command downloads the specified image on our system from Docker Hub.
+
+$ docker exec -it 7b272 bash
+# This command is used to run a command in the running container's default
+# directory. Here 7b272 was our ubuntu container and the above command would
+# help us interact with the container by opening a bash session.
+
+$docker logs <container-id>
+# Displays the information logged by the specified container
+# root@7b27222e4bb7:/# whoami
+# root
+# root@7b27222e4bb7:/# pwd
+# /
+# root@7b27222e4bb7:/# ls
+# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var
+# root@7b27222e4bb7:/# exit
+# exit
+
+# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/
+```
+## The Dockerfile
+The Dockerfile is a blueprint of a Docker image. We can mention the artifacts
+from our application along with their configurations into this file in the
+specific syntax to let anyone create a Docker image of our application.
+
+### A few things to keep in mind:
+* It is always strictly named `Dockerfile` without any extensions
+* We have to build our custom image on top of some already available Docker base
+image. (there is an empty image called `scratch` which literally lets you build
+an image from scratch)
+* All capitalised commands are part of the syntax, they are not case-sensitive
+but used like a convention
+* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/).
+
+```Dockerfile
+FROM <base-image>
+# define base image
+
+ENV USERNAME='admin'\
+ PWD='****'
+# optionally define environmental variables
+
+RUN apt-get update
+# run linux commands inside container env, does not affect host env
+# This executes during the time of image creation
+
+COPY <src> <target>
+# executes on the host, copies files from src (usually on the host) to target
+# on the container
+
+ENTRYPOINT ["some-script.sh"]
+# executes an entire script as an entrypoint
+
+CMD [<args>,...]
+# always part of dockerfile, introduces entry point linux command e.g.
+# `CMD node server.js`
+# This executes after image creation only when the container from the image
+# is running.
+```
+### Build your images
+Use the `docker build` command after wrapping your application into a Docker
+image to run ( or build) it.
+
+```bash
+
+$docker build <path-to-dockerfile>
+# used to build an image from the specified Dockerfile
+# instead of path we could also specify a URL
+# -t tag is optional and used to name and tag your images for e.g.
+# `$docker build -t my-image:0.1 ./home/app`
+# rebuild images everytime you make changes in the dockerfile
+```
+
+## Push your image to DockerHub
+If you want your application's Docker image to be made publically available for
+any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a
+registry of Docker images. Make sure you have an account with a username and
+password on Docker Hub.
+
+When pushing an image to Docker Hub, we must specify our Docker Hub username
+as part of the source image name. We need to create the target image with the
+tag name of username/image-name much like GitHub repositories.
+
+```bash
+$docker login
+# to login to Docker Hub using your username and password
+
+$docker tag <src-image>[:<src-tag>] <target-image>[:<target-tag>]
+# this tags a local src-image to a public target-image
+# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app`
+# if tags are not specified, they're defaulted to `latest`
+
+$docker push <target-image>[:<target-tag>]
+# uploads our image to Docker Hub
+# e.g. `docker push akshitadixit/my-sample-app`
+# this image will be accessible under your profile's repositories as
+# `https://hub.docker.com/r/username/image-name`
+
```
diff --git a/es-es/awk-es.html.markdown b/es-es/awk-es.html.markdown index 2f771320..725dae1d 100644 --- a/es-es/awk-es.html.markdown +++ b/es-es/awk-es.html.markdown @@ -11,8 +11,8 @@ lang: es-es AWK es una herramienta estándar en cada sistema UNIX compatible con POSIX. Es como un Perl restringido, perfecto para tareas de procesamiento de texto y -otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin -puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo +otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin +puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo desde un script de shell o usarlo como un lenguaje stand-alone para scripting. ¿Por qué elegir AWK sobre Perl? Principalmente, porque AWK es parte de UNIX. @@ -74,8 +74,8 @@ BEGIN { # Bloques formados por múltiples líneas usan llaves while (a < 10) { - print "La concatenación de strings se hace " " con series " - print " de" " strings separados por espacios" + print "La concatenación de strings se hace " " con series " + print " de" " strings separados por espacios" print a a++ @@ -153,13 +153,13 @@ function arithmetic_functions(a, b, c, localvar) { # Todo es global. No es problema en scripts pequeños, pero sí para # scripts más grandes. - # Hay un work-around (mmm... hack). Los argumentos de las funciones son + # Hay un work-around (mmm... hack). Los argumentos de las funciones son # locales para la función, y AWK permite definir más argumentos de función - # de los que necesita, por lo que define las variables locales en la + # de los que necesita, por lo que define las variables locales en la # declaración como en la función de arriba. Como convención, agrega - # espacios en blanco para distinguir los parámetros de la función de las - # variables locales. En este ejemplo, a, b y c son parámetros y localvar es una - # variable local. + # espacios en blanco para distinguir los parámetros de la función de las + # variables locales. En este ejemplo, a, b y c son parámetros y localvar es + # una variable local. # Ahora, a demostrar las funciones aritméticas @@ -222,10 +222,10 @@ function io_functions( localvar) { # También hay printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un - # handle de archivo cuando use algo que necesite uno. El string que usaste - # para esto puede ser tratada como un handle de archivo para propósitos de I/O. - # Esto lo hace similar al scripting de shell: + # AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un + # handle de archivo cuando use algo que necesite uno. El string que usaste + # para esto puede ser tratada como un handle de archivo para propósitos + # de I/O. Esto lo hace similar al scripting de shell: print "foobar" >"/tmp/foobar.txt" @@ -247,17 +247,17 @@ function io_functions( localvar) { close("/tmp/foobar.txt") } -# Como dije al inicio, los programas en AWK son una colección de patrones y +# Como dije al inicio, los programas en AWK son una colección de patrones y # acciones. Ya conociste el patrón BEGIN. otros patrones sólo se usan si estás # procesando líneas desde archivos o stdin. -# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a -# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for +# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a +# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for # implícito, iterando sobre las líneas de estos archivos. Estos patrones y # acciones son como instrucciones switch dentro del ciclo. /^fo+bar$/ { - + # Esta acción se ejecutará por cada línea que haga match con la expresión # regular /^fo+bar$/, y será saltada por cualquier línea que no haga match. # Vamos a sólo mostrar la línea: @@ -268,7 +268,7 @@ function io_functions( localvar) { # $0 es el nombre de la línea actual que se está procesando. # Se crea automáticamente para ti. - # Probablemente puedas adivinar que hay otras variables $. Cada línea es + # Probablemente puedas adivinar que hay otras variables $. Cada línea es # separada implícitamente antes de que se llame cada acción, justo como lo # hace shell. Y, como shell, cada campo puede ser accesado con $. @@ -301,7 +301,7 @@ a > 0 { # Y ya te das una idea. Procesar archivos de texto, leyendo una línea a la vez, # y haciendo algo con ella, particularmente separando en un deliminator, es tan # común en UNIX que AWK es un lenguaje de scripting que hace todo eso por ti -# sin que tengas que pedirlo. Basta con escribir los patrones y acciones +# sin que tengas que pedirlo. Basta con escribir los patrones y acciones # basados en lo que esperas de la entrada y lo quieras quieras hacer con ella. # Aquí está un ejemplo de un script simple, para lo que AWK es perfecto. @@ -343,7 +343,7 @@ $1 == name { nlines++ } -# Otro patrón especial es END. Va a ejecutarse después de procesar todos los +# Otro patrón especial es END. Va a ejecutarse después de procesar todos los # archivos de texto. A diferencia de BEGIN, sólo se ejecuta si le das dado una # entrada a procesar. Se ejecutará después de que todos los archivos hayan sido # leídos y procesados según las reglas y acciones que programaste. El propósito @@ -356,8 +356,10 @@ END { } ``` + Más información: * [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html) * [Página man de AWK](https://linux.die.net/man/1/awk) -* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): GNU Awk se encuentra en la mayoría de los sistemas Linux. +* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): + GNU Awk se encuentra en la mayoría de los sistemas Linux. diff --git a/fr-fr/awk-fr.html.markdown b/fr-fr/awk-fr.html.markdown index 9e45a89b..a5db24b2 100644 --- a/fr-fr/awk-fr.html.markdown +++ b/fr-fr/awk-fr.html.markdown @@ -24,14 +24,12 @@ ce qui concerne le traitement de texte simple. Notamment le traitement de ceux qui nécessitent de lire des fichiers ligne par ligne ; chaque ligne comportant des champs séparés par des délimiteur. - ```awk #!/usr/bin/awk -f # Les commentaires commencent par un # - -# les programmes AWK consistent en une collection de règles et d'actions +# Les programmes AWK consistent en une collection de règles et d'actions. règle1 { action; } règle2 { action; } @@ -46,14 +44,14 @@ règle2 { action; } # texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le # point d’entrée principal du script. # À l'opposé de BEGIN, il existe la règle END. Cette règle est présente après -#chaque fin de fichier (EOF : End Of File). +# chaque fin de fichier (EOF : End Of File). BEGIN { # Les variables sont globales. Pas besoin de les déclarer. count = 0; - # les opérateurs sont identiques au langage C et aux langages similaires + # Les opérateurs sont identiques au langage C et aux langages similaires # (tels que C#, C++, etc.) a = count + 1; # addition b = count - 1; # soustraction @@ -73,7 +71,8 @@ BEGIN { a++; b--; - # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui est retournée + # En tant qu'opérateur préfixé, c'est la valeur incrémentée qui + # est retournée ++a; --b; @@ -121,7 +120,6 @@ BEGIN { arr[1] = "bar"; # Vous pouvez aussi initialiser un tableau avec la fonction split() - n = split("foo:bar:baz", arr, ":"); # Il y a aussi les tableaux associatifs @@ -130,7 +128,6 @@ BEGIN { # et les tableaux multi-dimensions, avec certaines limitations que l'on ne # mentionnera pas ici - multidim[0,0] = "foo"; multidim[0,1] = "bar"; multidim[1,0] = "baz"; @@ -149,18 +146,16 @@ BEGIN { for (argnum in ARGV) print ARGV[argnum]; - # Vous pouvez supprimer des éléments d'un tableau + # Vous pouvez supprimer des éléments d'un tableau. # C'est utile pour empêcher AWK de supposer que certains arguments soient # des fichiers à traiter. - delete ARGV[1]; - # Le nombre d'arguments de la ligne de commande est assigné à la variable ARGC + # Le nombre d'arguments de la ligne de commande est assigné à + # la variable ARGC print ARGC; - # AWK inclue trois catégories de fonction. - # On les examinera plus tard - + # AWK inclue trois catégories de fonction. On les examinera plus tard. return_value = arithmetic_functions(a, b, c); string_functions(); io_functions(); @@ -175,13 +170,13 @@ function arithmetic_functions(a, b, c, d) { # Il y a cependant une solution de contournement (enfin ... une bidouille). # Les arguments d'une fonction sont locaux à cette fonction. - # Et AWK vous permet de définir plus d'arguments à la fonction que nécessaire. - # Il suffit donc de mettre une variable locale dans la déclaration de fonction, - # comme ci-dessus. La convention veut que vous mettiez quelques espaces - # supplémentaires pour faire la distinction entre les paramètres réels et - # les variables locales. - # Dans cet exemple, a, b et c sont des paramètres réels, - # alors que d est simplement une variable locale. + # Et AWK vous permet de définir plus d'arguments à la fonction que + # nécessaire. Il suffit donc de mettre une variable locale dans la + # déclaration de fonction, comme ci-dessus. La convention veut que vous + # mettiez quelques espaces supplémentaires pour faire la distinction entre + # les paramètres réels et les variables locales. + # Dans cet exemple, a, b et c sont des paramètres réels, alors que d est + # simplement une variable locale. # Maintenant, les fonctions arithmétiques @@ -217,20 +212,21 @@ function string_functions( localvar, arr) { # AWK a plusieurs fonctions pour le traitement des chaînes de caractères, # dont beaucoup reposent sur des expressions régulières. - # Chercher et remplacer, la première occurrence (sub) ou toutes les - # occurrences (gsub) + # Chercher et remplacer, la première occurrence (sub), ou toutes les + # occurrences (gsub). # Les deux renvoient le nombre de correspondances remplacées - localvar = "fooooobar"; sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar" gsub("e", ".", localvar); # localvar => "m..t m. at th. bar" - # Rechercher une chaîne de caractères qui correspond à une expression régulière - # index() fait la même chose, mais n'autorise pas les expressions régulières + # Rechercher une chaîne de caractères qui correspond à une expression + # régulière index() fait la même chose, mais n'autorise pas les expressions + # régulières. match(localvar, "t"); # => 4, puisque 't' est le quatrième caractère # Séparer par un délimiteur - n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 + n = split("foo-bar-baz", arr, "-"); + # résultat : a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 # Autre astuces utiles sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" @@ -251,23 +247,20 @@ function io_functions( localvar) { # AWK n'a pas de descripteur de fichier en soi. Il ouvrira automatiquement # un descripteur de fichier lorsque vous utilisez quelque chose qui en a - # besoin. - # La chaîne de caractères que vous avez utilisée pour cela peut être traitée - # comme un descripteur de fichier à des fins d'entrée / sortie. - + # besoin. La chaîne de caractères que vous avez utilisée pour cela peut être + # traitée comme un descripteur de fichier à des fins d'entrée / sortie. outfile = "/tmp/foobar.txt"; - print "foobar" > outfile; - # Maintenant, la chaîne de caractères "outfile" est un descripteur de fichier. - # Vous pouvez le fermer + # Maintenant, la chaîne de caractères "outfile" est un descripteur de + # fichier. Vous pouvez le fermer. close(outfile); # Voici comment exécuter quelque chose dans le shell system("echo foobar"); # => affiche foobar - # Lire quelque chose depuis l'entrée standard et la stocker dans une variable - # locale + # Lire quelque chose depuis l'entrée standard et la stocker dans une + # variable locale getline localvar; # Lire quelque chose à partir d'un pipe (encore une fois, utilisez une @@ -294,23 +287,24 @@ function io_functions( localvar) { # Cette action sera exécutée pour chaque ligne qui correspond à l'expression # régulière, /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond - # pas. Imprimons simplement la ligne: + # pas. Imprimons simplement la ligne : print; # Pas d'argument ! C'est parce que print a un défaut : $0. - # $0 est le nom de la ligne en cours de traitement. Il est créé automatiquement. + # $0 est le nom de la ligne en cours de traitement. Il est créé + # automatiquement. # Vous devinez probablement qu'il existe d'autres variables $. - # Chaque ligne est divisée implicitement avant que chaque action soit exécutée, - # comme le fait le shell. Et, comme le shell, chaque champ est accessible - # avec un signe dollar + # Chaque ligne est divisée implicitement avant que chaque action soit + # exécutée, comme le fait le shell. Et, comme le shell, chaque champ est + # accessible avec un signe dollar. - # Ceci affichera les deuxième et quatrième champs de la ligne. + # Ceci affichera les deuxième et quatrième champs de la ligne. print $2, $4; # AWK défini automatiquement beaucoup d'autres variables qui peuvent vous - # aider à inspecter et traiter chaque ligne. La plus importante est NF + # aider à inspecter et traiter chaque ligne. La plus importante est NF. # Affiche le nombre de champs de la ligne print NF; @@ -320,7 +314,6 @@ function io_functions( localvar) { } # Chaque règle est en réalité un test conditionnel. - a > 0 { # Ceci s’exécutera une fois pour chaque ligne, tant que le test est positif } @@ -328,19 +321,16 @@ a > 0 { # Les expressions régulières sont également des tests conditionnels. # Si le test de l'expression régulières n'est pas vrais alors le bloc # n'est pas exécuté. - $0 /^fobar/ { print "la ligne commence par foobar" } # Dans le cas où vous voulez tester votre chaîne de caractères sur la ligne # en cours de traitement $0 est optionnelle. - /^[a-zA-Z0-9]$/ { print "La ligne courante ne contient que des caractères alphanumériques."; } - # AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en # fonction de règles établies. Cela est si courant sous UNIX qu'AWK est un # langage de script. @@ -349,7 +339,7 @@ $0 /^fobar/ { # parfait. Le script lit un nom à partir de l'entrée standard, puis affiche # l'âge moyen de toutes les personnes portant ce prénom. # Supposons que vous fournissiez comme argument le nom d'un fichier comportant -# ces données: +# ces données : # # Bob Jones 32 # Jane Doe 22 @@ -364,22 +354,24 @@ BEGIN { # Premièrement, on demande à l'utilisateur le prénom voulu print "Pour quel prénom voudriez vous savoir l'age moyen ?"; - # On récupère la ligne à partir de l'entrée standard, pas de la ligne de commande + # On récupère la ligne à partir de l'entrée standard, pas de la ligne + # de commande : getline name < "/dev/stdin"; } # Maintenant, pour chaque ligne dont le premier champ est le prénom donné $1 == name { - # Ici, nous avons accès à un certain nombre de variables utiles déjà préchargées : + # Ici, nous avons accès à un certain nombre de variables utiles déjà + # préchargées : # $0 est la ligne entière # $3 est le troisième champ. Ici il correspond à l'age qui nous intéresse # NF est le nombre de champs et vaut 3 # NR est le nombre d'enregistrements (lignes) vus jusqu'à présent # FILENAME est le nom du fichier en cours de traitement # FS est séparateur de champs, ici c'est " " (un espace) - # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de man. - # Pour cela exécutez "man awk" dans votre terminal + # ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de + # man. Pour cela exécutez "man awk" dans votre terminal. # Garder une trace du total accumulé et du nombre de lignes correspondant. sum += $3; @@ -390,9 +382,9 @@ $1 == name { # les fichiers texte. Contrairement à BEGIN, il ne fonctionne que si vous lui # donnez une entrée à traiter. Il sera exécuté une fois que tous les fichiers # auront été lus et traités conformément aux règles et aux actions que vous -# avez fournies. Le but est généralement de produire un rapport final -# ou de faire quelque chose avec l'ensemble des données que vous avez -# accumulées au cours du script. +# avez fournies. Le but est généralement de produire un rapport final, ou de +# faire quelque chose avec l'ensemble des données que vous avez accumulées +# au cours du script. END { @@ -401,9 +393,11 @@ END { } ``` + Pour plus d'informations : * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk est dans la majorité des systèmes Linux. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU Awk est dans la majorité des systèmes Linux. * [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown index 366ae886..597b0e7a 100644 --- a/pt-br/awk-pt.html.markdown +++ b/pt-br/awk-pt.html.markdown @@ -370,8 +370,10 @@ END { } ``` + Leituras adicionais (em inglês): * [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) * [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux. +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) + GNU AWK é encontrado na maioria dos sistemas GNU/Linux. diff --git a/python.html.markdown b/python.html.markdown index 2247f263..175f17ec 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -503,6 +503,7 @@ contents = {"aa": 12, "bb": 21} with open("myfile1.txt", "w+") as file: file.write(str(contents)) # writes a string to a file +import json with open("myfile2.txt", "w+") as file: file.write(json.dumps(contents)) # writes an object to a file |