From f559b33f2f12a6bb445d0ba99f4b0128a0fa41d0 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 9 Jun 2017 14:05:58 +0200 Subject: template, main topics placed --- ansible.html.markdown | 660 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 660 insertions(+) create mode 100644 ansible.html.markdown diff --git a/ansible.html.markdown b/ansible.html.markdown new file mode 100644 index 00000000..b03b04fb --- /dev/null +++ b/ansible.html.markdown @@ -0,0 +1,660 @@ +--- +category: tool +tool: git +contributors: + - ["Jakub Muszynski" , "http://github.com/sirkubax"] +filename: LearnAnsible.txt +--- + +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +Ansible have great integration with multiple operating systems (even Windows using Power Shell) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) + +## Main cons and pros + +### Cons + +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) + +### Pros + +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. + + +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. + + +## Ansible naming and basic concept + +### Naming + +### ansible (run module (task)) + +### ansible-playbook (run set of tasks) + +### ansible-roles (a 'template-playbooks in right structure') + +### ansible - variables +lookup's + +### ansible-vault + +### inventory + +### dynamic inventory + +### Jinja2 and templates +jinja filters + +### ansible profiling - callback + +### facts-cache and ansible-cmdb + +### debugging ansible + +### Infrastructure as a code - what about Ansible +virtualenv + +### ansible - dynamic in AWS + +### create instance in AWS + +### create env in AWS + +## Bonus + +### writing own module + +### Python API + +### Web-UI: Ansible Tower, Jenkins, Rundeck + + +### Tips and tricks +AND,XOR +--check --diff +tags +meta +no_logs + +--- +Github template placeholder - to be removed + +### Centralized Versioning VS Distributed Versioning + +* Centralized version control focuses on synchronizing, tracking, and backing +up files. +* Distributed version control focuses on sharing changes. Every change has a +unique id. +* Distributed systems have no defined structure. You could easily have a SVN +style, centralized system, with git. + +[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Why Use Git? + +* Can work offline. +* Collaborating with others is easy! +* Branching is easy! +* Branching is fast! +* Merging is easy! +* Git is fast. +* Git is flexible. + +## Git Architecture + +### Repository + +A set of files, directories, historical records, commits, and heads. Imagine it +as a source code data structure, with the attribute that each source code +"element" gives you access to its revision history, among other things. + +A git repository is comprised of the .git directory & working tree. + +### .git Directory (component of repository) + +The .git directory contains all the configurations, logs, branches, HEAD, and +more. +[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Working Tree (component of repository) + +This is basically the directories and files in your repository. It is often +referred to as your working directory. + +### Index (component of .git dir) + +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power +over what gets sent to the Git repository. + +### Commit + +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be +pushed to other repositories, or not! + +### Branch + +A branch is essentially a pointer to the last commit you made. As you go on +committing, this pointer will automatically update to point the latest commit. + +### Tag + +A tag is a mark on specific point in history. Typically people use this +functionality to mark release points (v1.0, and so on) + +### HEAD and head (component of .git dir) + +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number +of heads. + +### Stages of Git +* Modified - Changes have been made to a file but file has not been committed +to Git Database yet +* Staged - Marks a modified file to go into your next commit snapshot +* Committed - Files have been committed to the Git Database + +### Conceptual Resources + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + +## Commands + +### init + +Create an empty Git repository. The Git repository's settings, stored +information, and more is stored in a directory (a folder) named ".git". + +```bash +$ git init +``` + +### config + +To configure settings. Whether it be for the repository, the system itself, +or global configurations ( global config file is `~/.gitconfig` ). + +```bash +# Print & Set Some Basic Config Variables (Global) +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Learn More About git config.](http://git-scm.com/docs/git-config) + +### help + +To give you quick access to an extremely detailed guide of each command. Or to +just give you a quick reminder of some semantics. + +```bash +# Quickly check available commands +$ git help + +# Check all available commands +$ git help -a + +# Command specific help - user manual +# git help +$ git help add +$ git help commit +$ git help init +# or git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignore files + +To intentionally untrack file(s) & folder(s) from git. Typically meant for +private & temp files which would otherwise be shared in the repository. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore +``` + +### status + +To show differences between the index file (basically your working copy/repo) +and the current HEAD commit. + +```bash +# Will display the branch, untracked files, changes and other differences +$ git status + +# To learn other "tid bits" about git status +$ git help status +``` + +### add + +To add files to the staging area/index. If you do not `git add` new files to +the staging area/index, they will not be included in commits! + +```bash +# add a file in your current working directory +$ git add HelloWorld.java + +# add a file in a nested dir +$ git add /path/to/file/HelloWorld.c + +# Regular Expression support! +$ git add ./*.java +``` + +This only adds a file to the staging area/index, it doesn't commit it to the +working directory/repo. + +### branch + +Manage your branches. You can view, edit, create, delete branches using this +command. + +```bash +# list existing branches & remotes +$ git branch -a + +# create a new branch +$ git branch myNewBranch + +# delete a branch +$ git branch -d myBranch + +# rename a branch +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# edit a branch's description +$ git branch myBranchName --edit-description +``` + +### tag + +Manage your tags + +```bash +# List tags +$ git tag + +# Create a annotated tag +# The -m specifies a tagging message,which is stored with the tag. +# If you don’t specify a message for an annotated tag, +# Git launches your editor so you can type it in. +$ git tag -a v2.0 -m 'my version 2.0' + +# Show info about tag +# That shows the tagger information, the date the commit was tagged, +# and the annotation message before showing the commit information. +$ git show v2.0 + +# Push a single tag to remote +$ git push origin v2.0 + +# Push a lot of tags to remote +$ git push origin --tags +``` + +### checkout + +Updates all files in the working tree to match the version in the index, or +specified tree. + +```bash +# Checkout a repo - defaults to master branch +$ git checkout + +# Checkout a specified branch +$ git checkout branchName + +# Create a new branch & switch to it +# equivalent to "git branch ; git checkout " + +$ git checkout -b newBranch +``` + +### clone + +Clones, or copies, an existing repository into a new directory. It also adds +remote-tracking branches for each branch in the cloned repo, which allows you +to push to a remote branch. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# shallow clone - faster cloning that pulls only latest snapshot +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# clone only a specific branch +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Stores the current contents of the index in a new "commit." This commit +contains the changes made and a message created by the user. + +```bash +# commit with a message +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" + +# automatically stage modified or deleted files, except new files, and then commit +$ git commit -a -m "Modified foo.php and removed bar.php" + +# change last commit (this deletes previous commit with a fresh commit) +$ git commit --amend -m "Correct message" +``` + +### diff + +Shows differences between a file in the working directory, index and commits. + +```bash +# Show difference between your working dir and the index +$ git diff + +# Show differences between the index and the most recent commit. +$ git diff --cached + +# Show differences between your working dir and the most recent commit +$ git diff HEAD +``` + +### grep + +Allows you to quickly search a repository. + +Optional Configurations: + +```bash +# Thanks to Travis Jeffery for these +# Set line numbers to be shown in grep search results +$ git config --global grep.lineNumber true + +# Make search results more readable, including grouping +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Search for "variableName" in all java files +$ git grep 'variableName' -- '*.java' + +# Search for a line that contains "arrayListName" and, "add" or "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google is your friend; for more examples +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Display commits to the repository. + +```bash +# Show all commits +$ git log + +# Show only commit message & ref +$ git log --oneline + +# Show merge commits only +$ git log --merges + +# Show all commits represented by an ASCII graph +$ git log --graph +``` + +### merge + +"Merge" in changes from external commits into the current branch. + +```bash +# Merge the specified branch into the current. +$ git merge branchName + +# Always generate a merge commit when merging +$ git merge --no-ff branchName +``` + +### mv + +Rename or move a file + +```bash +# Renaming a file +$ git mv HelloWorld.c HelloNewWorld.c + +# Moving a file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force rename or move +# "existingFile" already exists in the directory, will be overwritten +$ git mv -f myFile existingFile +``` + +### pull + +Pulls from a repository and merges it with another branch. + +```bash +# Update your local repo, by merging in new changes +# from the remote "origin" and "master" branch. +# git pull +$ git pull origin master + +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + +# Merge in changes from remote branch and rebase +# branch commits onto your local repo, like: "git fetch , git +# rebase /" +$ git pull origin master --rebase +``` + +### push + +Push and merge changes from a branch to a remote & branch. + +```bash +# Push and merge changes from a local repo to a +# remote named "origin" and "master" branch. +# git push +$ git push origin master + +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + +# To link up current local branch with a remote branch, add -u flag: +$ git push -u origin master +# Now, anytime you want to push from that same local branch, use shortcut: +$ git push +``` + +### stash + +Stashing takes the dirty state of your working directory and saves it on a +stack of unfinished changes that you can reapply at any time. + +Let's say you've been doing some work in your git repo, but you want to pull +from the remote. Since you have dirty (uncommited) changes to some files, you +are not able to run `git pull`. Instead, you can run `git stash` to save your +changes onto a stack! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Now you can pull! + +```bash +git pull +``` +`...changes apply...` + +Now check that everything is OK + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +You can see what "hunks" you've stashed so far using `git stash list`. +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +change will be at top. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log +``` + +Now let's apply our dirty changes back by popping them off the stack. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` does the same thing + +Now you're ready to get back to work on your stuff! + +[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + +### rebase (caution) + +Take all changes that were committed on one branch, and replay them onto +another branch. +*Do not rebase commits that you have pushed to a public repo*. + +```bash +# Rebase experimentBranch onto master +# git rebase +$ git rebase master experimentBranch +``` + +[Additional Reading.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (caution) + +Reset the current HEAD to the specified state. This allows you to undo merges, +pulls, commits, adds, and more. It's a great command but also dangerous if you +don't know what you are doing. + +```bash +# Reset the staging area, to match the latest commit (leaves dir unchanged) +$ git reset + +# Reset the staging area, to match the latest commit, and overwrite working dir +$ git reset --hard + +# Moves the current branch tip to the specified commit (leaves dir unchanged) +# all changes still exist in the directory. +$ git reset 31f2bb1 + +# Moves the current branch tip backward to the specified commit +# and makes the working dir match (deletes uncommited changes and all commits +# after the specified commit). +$ git reset --hard 31f2bb1 +``` + +### reflog (caution) + +Reflog will list most of the git commands you have done for a given time period, +default 90 days. + +This give you the a change to reverse any git commands that have gone wrong +for instance if a rebase is has broken your application. + +You can do this: + +1. `git reflog` to list all of the git commands for the rebase +``` +38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog +38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators +4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown +34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) +ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) +2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d +``` +2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` +3. 'git reset --hard HEAD@{5}' this will reset your repo to that head +4. You can start the rebase again or leave it alone. + +[Additional Reading.](https://git-scm.com/docs/git-reflog) + +### revert + +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new +commit which is the inverse of the specified commit, thus reverting it. + +```bash +# Revert a specified commit +$ git revert +``` + +### rm + +The opposite of git add, git rm removes files from the current working tree. + +```bash +# remove HelloWorld.c +$ git rm HelloWorld.c + +# Remove a file from a nested dir +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Further Information + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/) + +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) + +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From d6468f27ea7abda52b9ed9fa4afa959c692aea3d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 9 Jun 2017 14:07:58 +0200 Subject: tool name :) --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b03b04fb..f28abb68 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,6 +1,6 @@ --- category: tool -tool: git +tool: ansible contributors: - ["Jakub Muszynski" , "http://github.com/sirkubax"] filename: LearnAnsible.txt -- cgit v1.2.3 From bcb1b623b1db1057085982507399c62eaa053e7b Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Fri, 23 Jun 2017 13:35:19 -0700 Subject: [scala/en] Make return value example actually demonstrate issue Previously the `return z` didn't actually have any effect on the output, since the outer function just return the anon function's result directly. Updated to make the outer function do something to demonstrate the difference. Also renamed functions to make what they're doing easier to follow, and added a couple examples of behavior w/ explanations --- scala.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..e541f4b3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,16 +253,20 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def foo(x: Int): Int = { - val anonFunc: Int => Int = { z => +def addTenButMaybeTwelve(x: Int): Int = { + val anonMaybeAddTwo: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of addTenButMaybeTwelve! else z + 2 // This line is the return value of anonFunc } - anonFunc(x) // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of foo } +addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 +addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so + // last line doesn't get called and 10 is not added + ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3 From 23cee36b4c056dcd3c01676132cb9a6588fb75ad Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Thu, 29 Jun 2017 10:49:44 -0700 Subject: Update more function mentions in comments --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e541f4b3..192af953 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -258,9 +258,9 @@ def addTenButMaybeTwelve(x: Int): Int = { if (z > 5) return z // This line makes z the return value of addTenButMaybeTwelve! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonMaybeAddTwo } - anonMaybeAddTwo(x) + 10 // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of addTenButMaybeTwelve } addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 -- cgit v1.2.3 From cd21e6da04a5f9fcba49093984c03ffe6c0216dd Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:44:20 +0200 Subject: add some lines --- ansible.html.markdown | 60 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index f28abb68..e074ed44 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -7,7 +7,7 @@ filename: LearnAnsible.txt --- Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -Ansible have great integration with multiple operating systems (even Windows using Power Shell) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) ## Main cons and pros @@ -15,10 +15,12 @@ Ansible have great integration with multiple operating systems (even Windows usi It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. ### Pros It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) @@ -30,12 +32,66 @@ Writing own modules and extension is fairly easy. ### Neutral Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. +## Basics on ansible + +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. ## Ansible naming and basic concept ### Naming -### ansible (run module (task)) +#### Inventory +Inventory is a set of objects/hosts against which we are executing our playbooks +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ + +#### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) +This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). +Example: Module:shell - a module that executes shell command on a delegated host(s). +Example: Module:file - performs file operations (stat, link, dir, ...) + +##### Task +Execution of a single module is called a `task` + +Example of a Task run in CLI: +###### Run a ansible module + +ansible -m shell -a 'date; whoami' + +as a contrast - please note a module `command` that allows to execute a single command only + +ansible -m command -a 'date; whoami' # FAILURE + +ansible -m command -a 'date' +ansible -m command -a 'whoami' + +##### Playbook + +A list of tasks written in a file of proper structure is called a `playbook` +Playbook must have a list (or group) of hosts that is executed against, some task(s) or role(s) that are going to be executed, and multiple optional settings. + +Example of the playbook: + +``` +hosts: all + +tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" +``` + +### Basic ansible commands + +There are few binaries you should know + +`ansible` (to run modules in CLI) +`ansible-playbook` (to run playbooks) +`ansible-vault` (to manage secrets) +`ansible-galaxy` (to install roles from github/galaxy) +and other! ### ansible-playbook (run set of tasks) -- cgit v1.2.3 From bd05f751631d71d823a197cc5a506b05a60be849 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:46:45 +0200 Subject: add some lines --- ansible.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index e074ed44..24821862 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -93,10 +93,15 @@ There are few binaries you should know `ansible-galaxy` (to install roles from github/galaxy) and other! -### ansible-playbook (run set of tasks) +### More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') +There are tasks (modules) that can be run via CLI +The execution plans of multiple tasks (with variables and logic) are called playbooks. + +Fot parts of the code, that is reusable, a concept called `role` was introduced + ### ansible - variables lookup's -- cgit v1.2.3 From 3069c1b9451768369cee30ea22c3e150dafef294 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:48:01 +0200 Subject: add some lines --- ansible.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 24821862..37c3e299 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -57,14 +57,18 @@ Execution of a single module is called a `task` Example of a Task run in CLI: ###### Run a ansible module +``` ansible -m shell -a 'date; whoami' +``` as a contrast - please note a module `command` that allows to execute a single command only +``` ansible -m command -a 'date; whoami' # FAILURE ansible -m command -a 'date' ansible -m command -a 'whoami' +``` ##### Playbook -- cgit v1.2.3 From dff02575a0a417e3d23802f4d115d52d1503232c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:55:44 +0200 Subject: add some lines --- ansible.html.markdown | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 37c3e299..c0de7ac0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -38,6 +38,8 @@ Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! + ## Ansible naming and basic concept ### Naming @@ -104,7 +106,30 @@ and other! There are tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -Fot parts of the code, that is reusable, a concept called `role` was introduced +For parts of the code, that is reusable, a concept called `role` was introduced + +Role in a way is just a structured way to keep your set of tasks, your variables, handlers, default settings, and way more (meta, files, templates). +Rele allows to reuse the same parts of code in multiple plybooks (usually with some parametisation). +It is a great way to introduce `object oriented` management for your applications. + +Role can be included in your playbook (executed in your playbook). + + +``` +hosts: all + +tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" + +role: + - some_role + +pre_tasks: + - name: some pre-task + shell: echo 'this task is the last, but would be executed before roles, and before tasks' ### ansible - variables lookup's -- cgit v1.2.3 From fa55726a683cf5bdee1d5e262f60df9042db3db6 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:20:52 +0200 Subject: continue description --- ansible.html.markdown | 136 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 87 insertions(+), 49 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c0de7ac0..3234fe5c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -7,38 +7,11 @@ filename: LearnAnsible.txt --- Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) - -## Main cons and pros - -### Cons - -It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) -Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - -### Pros +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. -In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' -I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) -Documentation is at the world-class standard! -The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. - - -### Neutral -Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. - -## Basics on ansible - -Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) -But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! ## Ansible naming and basic concept @@ -56,42 +29,54 @@ Example: Module:file - performs file operations (stat, link, dir, ...) ##### Task Execution of a single module is called a `task` +The simplest module is called `ping`. +Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + Example of a Task run in CLI: ###### Run a ansible module -``` -ansible -m shell -a 'date; whoami' +```bash +$ ansible -m ping hostname_or_a_group_name +$ ansible -m shell -a 'date; whoami' hostname_or_a_group_name ``` -as a contrast - please note a module `command` that allows to execute a single command only +another module - `command` that allows to execute a single command only with a simple shell #JM +We should also mention a module `raw` -``` -ansible -m command -a 'date; whoami' # FAILURE +```bash +$ ansible -m command -a 'date; whoami' # FAILURE -ansible -m command -a 'date' -ansible -m command -a 'whoami' +$ ansible -m command -a 'date' +$ ansible -m command -a 'whoami' ``` ##### Playbook -A list of tasks written in a file of proper structure is called a `playbook` -Playbook must have a list (or group) of hosts that is executed against, some task(s) or role(s) that are going to be executed, and multiple optional settings. +A common way to execute tasks is called `playbook`. +You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). + +You can think that it is very advanced CLI script that you are executing. Example of the playbook: -``` +```yml hosts: all tasks: - - name: "ping all" - ping: - - name: "execute a shell command" - shell: "date; whoami; df -h;" + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" +``` + +You can execute a playbook with a command: +```bash +$ ansible-playbook path/name_of_the_playbook.yml ``` ### Basic ansible commands -There are few binaries you should know +There are few commands you should know about `ansible` (to run modules in CLI) `ansible-playbook` (to run playbooks) @@ -106,16 +91,16 @@ and other! There are tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -For parts of the code, that is reusable, a concept called `role` was introduced +For parts of the code, that should be reusable, a concept called `role` was introduced -Role in a way is just a structured way to keep your set of tasks, your variables, handlers, default settings, and way more (meta, files, templates). -Rele allows to reuse the same parts of code in multiple plybooks (usually with some parametisation). +Role is a structured way to keep your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). +Role allows to reuse the same parts of code in multiple plybooks (you can parametrize this). It is a great way to introduce `object oriented` management for your applications. Role can be included in your playbook (executed in your playbook). -``` +```yml hosts: all tasks: @@ -126,10 +111,28 @@ tasks: role: - some_role + - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } pre_tasks: - name: some pre-task shell: echo 'this task is the last, but would be executed before roles, and before tasks' +``` + +``` +roles/ + some_role/ + defaults/ + files/ + templates/ + tasks/ + handlers/ + vars/ + meta/ +``` + +#### Role Handlers +Handlers are a task that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. +It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's @@ -174,6 +177,41 @@ tags meta no_logs + +## Main cons and pros + +### Cons + +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. + +### Pros + +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. + + +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. + +## Basics on ansible + +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. + +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! + + + + --- Github template placeholder - to be removed -- cgit v1.2.3 From 32b2f01d3652274f27dee4cf3d5957ac6aa7e95b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:34:29 +0200 Subject: continue --- ansible.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 3234fe5c..c1cddd35 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -54,6 +54,7 @@ $ ansible -m command -a 'whoami' A common way to execute tasks is called `playbook`. You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). +Playbook script language is YAML You can think that it is very advanced CLI script that you are executing. @@ -118,6 +119,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` +Role directory structure: ``` roles/ some_role/ -- cgit v1.2.3 From 60ae84cf4123473a5685de21d1f1e5b09b52aaa5 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:40:18 +0200 Subject: continue --- ansible.html.markdown | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c1cddd35..cd619cc3 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -15,7 +15,15 @@ Ansible have great integration with multiple operating systems (even Windows) an ## Ansible naming and basic concept -### Naming +### Basic ansible commands + +There are few commands you should know about + +`ansible` (to run modules in CLI) +`ansible-playbook` (to run playbooks) +`ansible-vault` (to manage secrets) +`ansible-galaxy` (to install roles from github/galaxy) +and other! #### Inventory Inventory is a set of objects/hosts against which we are executing our playbooks @@ -23,6 +31,7 @@ For this few minutes, lets asume that we are using default ansible inventory (wh #### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). +The simplest module is called `ping` - it just returns a JSON with `pong` message and ansible variables. Example: Module:shell - a module that executes shell command on a delegated host(s). Example: Module:file - performs file operations (stat, link, dir, ...) @@ -75,17 +84,7 @@ You can execute a playbook with a command: $ ansible-playbook path/name_of_the_playbook.yml ``` -### Basic ansible commands - -There are few commands you should know about - -`ansible` (to run modules in CLI) -`ansible-playbook` (to run playbooks) -`ansible-vault` (to manage secrets) -`ansible-galaxy` (to install roles from github/galaxy) -and other! - -### More on ansible concept +## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -163,6 +162,8 @@ virtualenv ### create env in AWS +### Naming + ## Bonus ### writing own module -- cgit v1.2.3 From 4076cc53c0fcb1f8b85a71e0e395407ab43a05ab Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:21:42 +0200 Subject: change the concept of paragraphs --- ansible.html.markdown | 109 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 77 insertions(+), 32 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index cd619cc3..2eb6df2e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,17 +6,38 @@ contributors: filename: LearnAnsible.txt --- -Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) -Of course the rabit hole is way deeper.' +```yaml +--- +Ansible - the easiest orchestration tool -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) +Why Ansible and Intro - in the second part of document +``` -## Ansible naming and basic concept +## Installation +```bash +# Universal way +$ pip install ansible -### Basic ansible commands +# Debian, Ubuntu +$ apt-get install ansible +``` +* Appendix A - How do I install ansible +[Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) + +### Basic ansible commands (shell execution) +```bash +# This command ping the localhost (defined in default inventory /etc/ansible/hosts) + +$ ansible -m ping localhost +localhost | SUCCESS => { + "changed": false, + "ping": "pong" +} + +``` +### Commands There are few commands you should know about `ansible` (to run modules in CLI) @@ -25,16 +46,37 @@ There are few commands you should know about `ansible-galaxy` (to install roles from github/galaxy) and other! +```bash +$ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name +``` + +The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) +We should also mention a module `raw` that sometimes can save the day. + +```bash +$ ansible -m command -a 'date; whoami' # FAILURE + +$ ansible -m command -a 'date' +$ ansible -m command -a 'whoami' +``` + + +#### Module - program (usaly python) that execute, do some work and return proper output :) +This program perform specialized task/action (like manage instances in the cloud, execute shell command). +The simplest module is called `ping` - it just returns a JSON with `pong` message. + +Example of modules: +Module: `shell` - a module that executes shell command on a specified host(s). +Module: `file` - performs file operations (stat, link, dir, ...) + + +```yaml +``` + #### Inventory Inventory is a set of objects/hosts against which we are executing our playbooks For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ -#### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) -This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). -The simplest module is called `ping` - it just returns a JSON with `pong` message and ansible variables. -Example: Module:shell - a module that executes shell command on a delegated host(s). -Example: Module:file - performs file operations (stat, link, dir, ...) - ##### Task Execution of a single module is called a `task` @@ -44,30 +86,22 @@ Another example of the module that allow you to execute command remotly on multi Example of a Task run in CLI: ###### Run a ansible module -```bash -$ ansible -m ping hostname_or_a_group_name -$ ansible -m shell -a 'date; whoami' hostname_or_a_group_name -``` - -another module - `command` that allows to execute a single command only with a simple shell #JM -We should also mention a module `raw` - -```bash -$ ansible -m command -a 'date; whoami' # FAILURE - -$ ansible -m command -a 'date' -$ ansible -m command -a 'whoami' -``` ##### Playbook - -A common way to execute tasks is called `playbook`. -You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). +Execution plan written in a form of script file(s) is called `playbook`. +Playbook consist of multiple elements +* a list (or group) of hosts that 'the play' is executed against +* `task(s)` or `role(s)` that are going to be executed +* multiple optional settings (like default variables, and way more) Playbook script language is YAML -You can think that it is very advanced CLI script that you are executing. +You can think that playbook is very advanced CLI script that you are executing. + -Example of the playbook: +##### Example of the playbook: +This playbook would execute (on all hosts defined in the inventory) two tasks +*`ping` that would return message *pong* +* `shell` that execute three commands and return the output to our terminal ```yml hosts: all @@ -83,7 +117,7 @@ You can execute a playbook with a command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` - +It is also possible to become a user other than root using --become-user: ## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -138,6 +172,9 @@ It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's +#### templates +JINJA2 + ### ansible-vault ### inventory @@ -180,6 +217,14 @@ tags meta no_logs +## Introduction +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' + +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) + + ## Main cons and pros -- cgit v1.2.3 From c7fbf44dd595d621fb1140d58e53c34be7494a20 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:23:09 +0200 Subject: test markdown --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 2eb6df2e..36d95532 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -8,7 +8,7 @@ filename: LearnAnsible.txt ```yaml --- -Ansible - the easiest orchestration tool +Ansible: 'the easiest orchestration tool' Why Ansible and Intro - in the second part of document -- cgit v1.2.3 From fdb26e4870ee45f9edb1e9df7abce7bf9edac878 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:24:22 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 36d95532..94fa20a0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -8,9 +8,9 @@ filename: LearnAnsible.txt ```yaml --- -Ansible: 'the easiest orchestration tool' +Ansible: "the easiest orchestration tool" -Why Ansible and Intro - in the second part of document +"{{ Why Ansible and Intro }}" in the second part of document ``` -- cgit v1.2.3 From 6ba6076dea7bf3b6633cdb8e0005362f4619deaa Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:25:47 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 94fa20a0..b8d7eb70 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,10 +6,10 @@ contributors: filename: LearnAnsible.txt --- +## Ansible: the easiest orchestration tool + ```yaml --- -Ansible: "the easiest orchestration tool" - "{{ Why Ansible and Intro }}" in the second part of document ``` -- cgit v1.2.3 From 0601badf4f6557ead604e693a273726c282fce46 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:27:32 +0200 Subject: test markdown --- ansible.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b8d7eb70..12aefe5f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -24,17 +24,16 @@ $ apt-get install ansible ``` * Appendix A - How do I install ansible -[Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) ### Basic ansible commands (shell execution) ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) - $ ansible -m ping localhost -localhost | SUCCESS => { +localhost | SUCCESS => { "changed": false, "ping": "pong" -} +} ``` ### Commands -- cgit v1.2.3 From 6ade03b92abfdc30917aa0f5188e7a0ed9a70ca9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:29:12 +0200 Subject: test markdown --- ansible.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 12aefe5f..4409422b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -39,10 +39,10 @@ localhost | SUCCESS => { ### Commands There are few commands you should know about -`ansible` (to run modules in CLI) -`ansible-playbook` (to run playbooks) -`ansible-vault` (to manage secrets) -`ansible-galaxy` (to install roles from github/galaxy) +* `ansible` (to run modules in CLI) +* `ansible-playbook` (to run playbooks) +* `ansible-vault` (to manage secrets) +* `ansible-galaxy` (to install roles from github/galaxy) and other! ```bash @@ -50,6 +50,7 @@ $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) + We should also mention a module `raw` that sometimes can save the day. ```bash -- cgit v1.2.3 From e7e43b01e66c158053acfd00d5317743f137abb4 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:30:27 +0200 Subject: test markdown --- ansible.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 4409422b..9408db18 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -43,7 +43,9 @@ There are few commands you should know about * `ansible-playbook` (to run playbooks) * `ansible-vault` (to manage secrets) * `ansible-galaxy` (to install roles from github/galaxy) -and other! +* and other! + +Example of usage - `shell` ```bash $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name -- cgit v1.2.3 From 688f9b686f70c7a0763e7e0e550b18f12bc1b7fb Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:41:27 +0200 Subject: test markdown --- ansible.html.markdown | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 9408db18..fff85563 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -45,15 +45,24 @@ There are few commands you should know about * `ansible-galaxy` (to install roles from github/galaxy) * and other! -Example of usage - `shell` + +#### Module - program (usaly python) that execute, do some work and return proper output :) +This program perform specialized task/action (like manage instances in the cloud, execute shell command). +The simplest module is called `ping` - it just returns a JSON with `pong` message. + +Example of modules: +* Module: `ping` - the simplest module that is usefull to verify host connectivity +* Module: `shell` - a module that executes shell command on a specified host(s). + +Example of usage - `ping`, `shell` ```bash +$ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME will not work -We should also mention a module `raw` that sometimes can save the day. ```bash $ ansible -m command -a 'date; whoami' # FAILURE @@ -62,14 +71,8 @@ $ ansible -m command -a 'date' $ ansible -m command -a 'whoami' ``` - -#### Module - program (usaly python) that execute, do some work and return proper output :) -This program perform specialized task/action (like manage instances in the cloud, execute shell command). -The simplest module is called `ping` - it just returns a JSON with `pong` message. - -Example of modules: -Module: `shell` - a module that executes shell command on a specified host(s). -Module: `file` - performs file operations (stat, link, dir, ...) +* Module: `file` - performs file operations (stat, link, dir, ...) +* Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) ```yaml -- cgit v1.2.3 From 2baed7cd96532f90ec7619e828e58a0115b34f20 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:42:18 +0200 Subject: test markdown --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index fff85563..389eaaa1 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -46,7 +46,8 @@ There are few commands you should know about * and other! -#### Module - program (usaly python) that execute, do some work and return proper output :) +#### Module +*program (usaly python) that execute, do some work and return proper output :)* This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. -- cgit v1.2.3 From 6f0799d6078c117a59da7cc2ada0cee583d6db56 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:42:43 +0200 Subject: test markdown --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 389eaaa1..5fc103b7 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,8 @@ There are few commands you should know about #### Module -*program (usaly python) that execute, do some work and return proper output :)* +_*program (usaly python) that execute, do some work and return proper output :)*_ + This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. -- cgit v1.2.3 From 7ba7ab471e340803e078a6cae0e24c7615dde0a2 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:43:50 +0200 Subject: test markdown --- ansible.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 5fc103b7..ea7bb47a 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,9 +47,10 @@ There are few commands you should know about #### Module -_*program (usaly python) that execute, do some work and return proper output :)*_ +_*program (usaly python) that execute, do some work and return proper JSON output :)*_ + +This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). -This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. Example of modules: -- cgit v1.2.3 From 8a1139dee670362ab4186cb9866d746f36d2d7e4 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:48:55 +0200 Subject: test markdown --- ansible.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ea7bb47a..13afeb3b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -26,7 +26,7 @@ $ apt-get install ansible * Appendix A - How do I install ansible * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) -### Basic ansible commands (shell execution) +### Your first ansible command (shell execution) ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) $ ansible -m ping localhost @@ -36,7 +36,7 @@ localhost | SUCCESS => { } ``` -### Commands +### Shell Commands There are few commands you should know about * `ansible` (to run modules in CLI) @@ -45,8 +45,7 @@ There are few commands you should know about * `ansible-galaxy` (to install roles from github/galaxy) * and other! - -#### Module +### Module _*program (usaly python) that execute, do some work and return proper JSON output :)*_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -57,7 +56,7 @@ Example of modules: * Module: `ping` - the simplest module that is usefull to verify host connectivity * Module: `shell` - a module that executes shell command on a specified host(s). -Example of usage - `ping`, `shell` +Example of execution - `ping`, `shell` ```bash $ ansible -m ping -- cgit v1.2.3 From 7abd3b5017df4c698b8bd33a6e472483decf73a2 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:49:43 +0200 Subject: test markdown --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 13afeb3b..6ef7bab7 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -30,6 +30,7 @@ $ apt-get install ansible ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) $ ansible -m ping localhost +# you should see this output localhost | SUCCESS => { "changed": false, "ping": "pong" -- cgit v1.2.3 From 21fb697b8899ea62bf83f11928d6f91c98c62ad1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 23:00:10 +0200 Subject: test markdown --- ansible.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 6ef7bab7..72a91a5c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usaly python) that execute, do some work and return proper JSON output :)*_ +_*program (usally python) that execute, do some work and return proper JSON output :)*_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -64,7 +64,7 @@ $ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME will not work +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` will not work ```bash @@ -72,6 +72,7 @@ $ ansible -m command -a 'date; whoami' # FAILURE $ ansible -m command -a 'date' $ ansible -m command -a 'whoami' +$ ansible -m command -a 'echo $HOME' ``` * Module: `file` - performs file operations (stat, link, dir, ...) -- cgit v1.2.3 From 7b6f0757c23b2339692c9194e4e5c95614b145f1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:43:25 +0200 Subject: test markdown --- ansible.html.markdown | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 72a91a5c..255715bd 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -64,7 +64,7 @@ $ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` will not work +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work ```bash @@ -79,17 +79,27 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -```yaml -``` +### Ansible - naming and basic concept #### Inventory -Inventory is a set of objects/hosts against which we are executing our playbooks -For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ +Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) -##### Task +`/etc/ansible/hosts` +``` +localhost + +[some_group] +hostA.mydomain.com +hostB.localdomain +``` +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) + +#### Task Execution of a single module is called a `task` -The simplest module is called `ping`. +The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: @@ -180,6 +190,8 @@ It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's +```yaml +``` #### templates JINJA2 -- cgit v1.2.3 From 69c40ee1a2659ba9f150e04adb2822d66f18570f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:50:05 +0200 Subject: test markdown --- ansible.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 255715bd..a09c8b34 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -79,7 +79,7 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -### Ansible - naming and basic concept +### Ansible - naming and quick intro #### Inventory Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands @@ -96,11 +96,10 @@ hostB.localdomain * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### Task -Execution of a single module is called a `task` +Execution of a single Ansible **module** is called a **task** -The simplest module is called `ping` as you could see above - -Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: ###### Run a ansible module -- cgit v1.2.3 From e946c383fde705d20aa3342c372cc8ad22793d90 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:52:10 +0200 Subject: test markdown --- ansible.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index a09c8b34..02ee8694 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -106,12 +106,14 @@ Example of a Task run in CLI: ##### Playbook -Execution plan written in a form of script file(s) is called `playbook`. +Execution plan written in a form of script file(s) is called `playbook`.-- + Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML +Playbook script language is YAML-- + You can think that playbook is very advanced CLI script that you are executing. -- cgit v1.2.3 From a6ea9118be2fe266ea89661b360707294b854725 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:53:10 +0200 Subject: test markdown --- ansible.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 02ee8694..44bce5b0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -99,6 +99,7 @@ hostB.localdomain Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: @@ -106,14 +107,12 @@ Example of a Task run in CLI: ##### Playbook -Execution plan written in a form of script file(s) is called `playbook`.-- - +Execution plan written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML-- - +Playbook script language is YAML You can think that playbook is very advanced CLI script that you are executing. -- cgit v1.2.3 From a5bec9b8efecbbda3415289325db37c911a0969e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:54:26 +0200 Subject: test markdown --- ansible.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 44bce5b0..1e3fc138 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -96,10 +96,9 @@ hostB.localdomain * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### Task -Execution of a single Ansible **module** is called a **task** + Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: -- cgit v1.2.3 From eaf3e9c46154842509e58bdcadb1a863178bb976 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:56:13 +0200 Subject: test markdown --- ansible.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1e3fc138..744f6394 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -98,11 +98,8 @@ hostB.localdomain #### Task Execution of a single Ansible **module** is called a **task** - The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. - -Example of a Task run in CLI: -###### Run a ansible module + The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. ##### Playbook -- cgit v1.2.3 From 656516a2b9c0951779b2450de24f46e8effad81c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:56:50 +0200 Subject: test markdown --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 744f6394..27a467cc 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -99,6 +99,7 @@ hostB.localdomain Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. -- cgit v1.2.3 From 27c3e82f12f40c75bdd08e97aead14048a080505 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 16:47:10 +0200 Subject: test markdown --- ansible.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 27a467cc..14565057 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -79,9 +79,9 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -### Ansible - naming and quick intro +## Ansible - naming and quick intro -#### Inventory +### Inventory Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) @@ -95,15 +95,15 @@ hostB.localdomain ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) -#### Task +### Task Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + Another example of the module that allow you to execute command remotly on multiple resources is called `shell`. See above how you were using them already. -##### Playbook +### Playbook Execution plan written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against @@ -114,7 +114,7 @@ Playbook script language is YAML You can think that playbook is very advanced CLI script that you are executing. -##### Example of the playbook: +#### Example of the playbook: This playbook would execute (on all hosts defined in the inventory) two tasks *`ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal -- cgit v1.2.3 From bb3e71c52957561c425999a542c0fb9f47a3c4f7 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:00:23 +0200 Subject: test markdown --- ansible.html.markdown | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 14565057..b5de971c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -10,7 +10,7 @@ filename: LearnAnsible.txt ```yaml --- -"{{ Why Ansible and Intro }}" in the second part of document +"{{ Why Ansible and detailed Intro }}" written in the second part of document ``` @@ -60,19 +60,19 @@ Example of modules: Example of execution - `ping`, `shell` ```bash -$ ansible -m ping +$ ansible -m ping all $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` * Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work +#JM ```bash $ ansible -m command -a 'date; whoami' # FAILURE -$ ansible -m command -a 'date' -$ ansible -m command -a 'whoami' -$ ansible -m command -a 'echo $HOME' +$ ansible -m command -a 'date' all +$ ansible -m command -a 'whoami' all ``` * Module: `file` - performs file operations (stat, link, dir, ...) @@ -92,6 +92,11 @@ localhost [some_group] hostA.mydomain.com hostB.localdomain + +[a_group_of_a_groups:children] +some_group +some_other_group + ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) @@ -104,7 +109,7 @@ hostB.localdomain ### Playbook -Execution plan written in a form of script file(s) is called `playbook`. +**Execution plan** written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed @@ -116,7 +121,7 @@ You can think that playbook is very advanced CLI script that you are executing. #### Example of the playbook: This playbook would execute (on all hosts defined in the inventory) two tasks -*`ping` that would return message *pong* +* `ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal ```yml -- cgit v1.2.3 From c62c527f82cd6addd38fec966efed5390bf15bdc Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:06:17 +0200 Subject: test markdown --- ansible.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b5de971c..2b997340 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -109,18 +109,19 @@ some_other_group ### Playbook -**Execution plan** written in a form of script file(s) is called `playbook`. +**Execution plan** written in a form of script file(s) is called **playbook**. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML + +Playbook script language is YAML. You can think that playbook is very advanced CLI script that you are executing. #### Example of the playbook: -This playbook would execute (on all hosts defined in the inventory) two tasks +This example-playbook would execute (on all hosts defined in the inventory) two tasks: * `ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal @@ -134,11 +135,10 @@ tasks: shell: "date; whoami; df -h;" ``` -You can execute a playbook with a command: +You can run the playbook with the command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` -It is also possible to become a user other than root using --become-user: ## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -232,6 +232,7 @@ virtualenv ### Web-UI: Ansible Tower, Jenkins, Rundeck +#become-user, become ### Tips and tricks AND,XOR -- cgit v1.2.3 From cbc9b5b2a5af550926f3232458432984951b5b53 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:52:48 +0200 Subject: test markdown --- ansible.html.markdown | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 2b997340..460faf82 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -139,20 +139,20 @@ You can run the playbook with the command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` -## More on ansible concept +### More on ansible concept -### ansible-roles (a 'template-playbooks in right structure') +#### ansible-roles (a 'template-playbooks' with right structure) -There are tasks (modules) that can be run via CLI +You already know the tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -For parts of the code, that should be reusable, a concept called `role` was introduced +A concept called `role` was introduced for parts of the code that should be reusable. -Role is a structured way to keep your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). -Role allows to reuse the same parts of code in multiple plybooks (you can parametrize this). +**Role** is a structured way to manage your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). +Role allows to reuse the same parts of code in multiple plybooks (you can parametrize the role 'further' during it's execution). It is a great way to introduce `object oriented` management for your applications. -Role can be included in your playbook (executed in your playbook). +Role can be included in your playbook (executed via your playbook). ```yml @@ -173,6 +173,16 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` +Example-role + +We would clone the ready-to-use examples from additional repository +```bash +$ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git +$ cd ansible-for-learnXinYminutes +$ source environment +$(venv) ansible-playbook playbooks/role_example.yml +``` + Role directory structure: ``` roles/ -- cgit v1.2.3 From 04a88249c9ee8f1e611d67b782267289208ab310 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:53:42 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 460faf82..1f04b520 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -143,8 +143,8 @@ $ ansible-playbook path/name_of_the_playbook.yml #### ansible-roles (a 'template-playbooks' with right structure) -You already know the tasks (modules) that can be run via CLI -The execution plans of multiple tasks (with variables and logic) are called playbooks. + You already know the tasks (modules) that can be run via CLI. + The execution plans of multiple tasks (with variables and logic) are called playbooks. A concept called `role` was introduced for parts of the code that should be reusable. -- cgit v1.2.3 From da0ca8fcbda3b035fa725e7746c9ee4f084b08cc Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 18:11:20 +0200 Subject: test markdown --- ansible.html.markdown | 64 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1f04b520..25a38283 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,4 +1,4 @@ ---- +o-- category: tool tool: ansible contributors: @@ -143,10 +143,9 @@ $ ansible-playbook path/name_of_the_playbook.yml #### ansible-roles (a 'template-playbooks' with right structure) - You already know the tasks (modules) that can be run via CLI. - The execution plans of multiple tasks (with variables and logic) are called playbooks. + You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). -A concept called `role` was introduced for parts of the code that should be reusable. +A concept called `role` was introduced for parts of the code (playbooks) that should be reusable. **Role** is a structured way to manage your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). Role allows to reuse the same parts of code in multiple plybooks (you can parametrize the role 'further' during it's execution). @@ -173,7 +172,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -Example-role +Example->role We would clone the ready-to-use examples from additional repository ```bash @@ -183,30 +182,59 @@ $ source environment $(venv) ansible-playbook playbooks/role_example.yml ``` -Role directory structure: +#### Role directory structure: ``` roles/ some_role/ - defaults/ - files/ - templates/ - tasks/ - handlers/ - vars/ - meta/ + defaults/ # contains default variables + files/ # for static files + templates/ # for jinja templates + tasks/ # tasks + handlers/ # handlers + vars/ # more variables (higher priority) + meta/ # meta - package (role) info ``` #### Role Handlers -Handlers are a task that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. -It is a best way to restart a service, check if application port is open, etc. +Handlers are a tasks that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. +It is a best way to restart a service, check if application port is active (successfull deployment criteria), etc. ### ansible - variables -lookup's + +Ansible is flexible - it has 21 levels of variable precedence + +[read more] + +For now you might like to know, that CLI variables has the top priority. + +You should also know, that a nice way to pool some data is a **lookup** + +##### Lookups + +* pipe +* file +* stream +* etcd + +You can use them in CLI too ```yaml +ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" + ``` -#### templates -JINJA2 +#### Templates + +Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. + +```jinja2 +Some static content + +{{ a_variable }} + +{% for item in loop_items %} + this line item is {{ item }} +{% endfor %} +``` ### ansible-vault -- cgit v1.2.3 From 05892ff7ddd69e5f01e9da6d9d602dd318d0485e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 18:34:38 +0200 Subject: test markdown --- ansible.html.markdown | 63 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 25a38283..cadf6301 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,4 +1,8 @@ -o-- +# JM inventory dynamic aws ec2 +# vault +# roles + +--- category: tool tool: ansible contributors: @@ -218,7 +222,7 @@ You should also know, that a nice way to pool some data is a **lookup** You can use them in CLI too ```yaml -ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" +ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" localhost ``` @@ -235,16 +239,63 @@ Some static content this line item is {{ item }} {% endfor %} ``` +Jinja may have some limitations, but it is a powerfull tool that you might like. -### ansible-vault - -### inventory +#### Jinja2 CLI +You can use the jinja in the CLI too +```bash +ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost +``` -### dynamic inventory ### Jinja2 and templates jinja filters + +#### ansible-vault +To maintain **ifrastructure as a code** you need to store secrets. + Ansible provides a way to encrypt the poufne files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. + +The best way to use the **ansible-vault** is to store the secret in some secure location, and configure ansible to use during runtime. + +```bash +$ echo some_very_very_long_secret > ~/.ssh/secure_located_file + +$ vi ansible.cfg + ansible_vault_password_file = ~/.ssh/secure_located_file + +#or to use env +export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file + +$ ansible-playbook playbooks/vault_example.yml + + # decrypt the file +$ ansible-vault encrypt path/somefile + + # view the file +$ ansible-vault view path/somefile + + # check the file content: +$ cat path/somefile + + # decrypt the file +$ ansible-vault decrypt path/somefile +``` + +#### dynamic inventory +You might like to know, that you can build your inventory dynamically. + +(For Ansible) inventory is just a JSON with proper structure - if you can deliver that to ansible - anything is possible. + +You do not need to invent the wheel - there are plenty ready to use inventory script for most popular Cloud provicers and a lot of in-house popular usecaseses. + +```bash +$ etc/inv/ec2.py --refresh + +$ ansible -m ping all -i etc/inv/ec2.py +``` + + ### ansible profiling - callback ### facts-cache and ansible-cmdb -- cgit v1.2.3 From 3c7153633842717cb9de7a96f5cd3da5982ffe50 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 23:57:45 +0200 Subject: test markdown --- ansible.html.markdown | 713 +++++++++----------------------------------------- 1 file changed, 119 insertions(+), 594 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index cadf6301..0023a718 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,7 +1,3 @@ -# JM inventory dynamic aws ec2 -# vault -# roles - --- category: tool tool: ansible @@ -247,10 +243,14 @@ You can use the jinja in the CLI too ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost ``` - -### Jinja2 and templates -jinja filters - +### Jinja2 filters +Junja is powerfull. It has built-in many usefull functions. +```jinja +# get first item of the list +{{ some_list | first() }} +# if variable is undefined - use default value +{{ some_variable | default('default_value') }} +``` #### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. @@ -295,655 +295,180 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` +#### ansible profiling - callback +It is ok that your playbook executes some time. Sometimes you may like to speed things up :) -### ansible profiling - callback - -### facts-cache and ansible-cmdb - -### debugging ansible - -### Infrastructure as a code - what about Ansible -virtualenv - -### ansible - dynamic in AWS - -### create instance in AWS - -### create env in AWS - -### Naming - -## Bonus - -### writing own module - -### Python API - -### Web-UI: Ansible Tower, Jenkins, Rundeck - -#become-user, become - -### Tips and tricks -AND,XOR ---check --diff -tags -meta -no_logs - -## Introduction -Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) -Of course the rabit hole is way deeper.' - -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) - - - -## Main cons and pros - -### Cons - -It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) -Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - -### Pros - -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. -In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' -I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) -Documentation is at the world-class standard! -The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. - - -### Neutral -Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. - -## Basics on ansible - -Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. - -But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! - - - - ---- -Github template placeholder - to be removed - -### Centralized Versioning VS Distributed Versioning - -* Centralized version control focuses on synchronizing, tracking, and backing -up files. -* Distributed version control focuses on sharing changes. Every change has a -unique id. -* Distributed systems have no defined structure. You could easily have a SVN -style, centralized system, with git. - -[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) - -### Why Use Git? - -* Can work offline. -* Collaborating with others is easy! -* Branching is easy! -* Branching is fast! -* Merging is easy! -* Git is fast. -* Git is flexible. - -## Git Architecture - -### Repository - -A set of files, directories, historical records, commits, and heads. Imagine it -as a source code data structure, with the attribute that each source code -"element" gives you access to its revision history, among other things. - -A git repository is comprised of the .git directory & working tree. - -### .git Directory (component of repository) - -The .git directory contains all the configurations, logs, branches, HEAD, and -more. -[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) - -### Working Tree (component of repository) - -This is basically the directories and files in your repository. It is often -referred to as your working directory. - -### Index (component of .git dir) - -The Index is the staging area in git. It's basically a layer that separates -your working tree from the Git repository. This gives developers more power -over what gets sent to the Git repository. - -### Commit - -A git commit is a snapshot of a set of changes, or manipulations to your -Working Tree. For example, if you added 5 files, and removed 2 others, these -changes will be contained in a commit (or snapshot). This commit can then be -pushed to other repositories, or not! - -### Branch - -A branch is essentially a pointer to the last commit you made. As you go on -committing, this pointer will automatically update to point the latest commit. - -### Tag - -A tag is a mark on specific point in history. Typically people use this -functionality to mark release points (v1.0, and so on) - -### HEAD and head (component of .git dir) - -HEAD is a pointer that points to the current branch. A repository only has 1 -*active* HEAD. -head is a pointer that points to any commit. A repository can have any number -of heads. - -### Stages of Git -* Modified - Changes have been made to a file but file has not been committed -to Git Database yet -* Staged - Marks a modified file to go into your next commit snapshot -* Committed - Files have been committed to the Git Database - -### Conceptual Resources - -* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) -* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) - -## Commands - -### init - -Create an empty Git repository. The Git repository's settings, stored -information, and more is stored in a directory (a folder) named ".git". - -```bash -$ git init -``` - -### config - -To configure settings. Whether it be for the repository, the system itself, -or global configurations ( global config file is `~/.gitconfig` ). +Since ansible 2.x there is bouilt-in callback for task execution profiling -```bash -# Print & Set Some Basic Config Variables (Global) -$ git config --global user.email "MyEmail@Zoho.com" -$ git config --global user.name "My Name" ``` - -[Learn More About git config.](http://git-scm.com/docs/git-config) - -### help - -To give you quick access to an extremely detailed guide of each command. Or to -just give you a quick reminder of some semantics. - -```bash -# Quickly check available commands -$ git help - -# Check all available commands -$ git help -a - -# Command specific help - user manual -# git help -$ git help add -$ git help commit -$ git help init -# or git --help -$ git add --help -$ git commit --help -$ git init --help +vi ansible.cfg +#set this to: +callback_whitelist = profile_tasks ``` -### ignore files +#### facts-cache and ansible-cmdb +You can pool some infrmations of you environment from another hosts. +If the informations does not change - you may consider using a facts_cache to speed things up. -To intentionally untrack file(s) & folder(s) from git. Typically meant for -private & temp files which would otherwise be shared in the repository. -```bash -$ echo "temp/" >> .gitignore -$ echo "private_key" >> .gitignore ``` +vi ansible.cfg -### status - -To show differences between the index file (basically your working copy/repo) -and the current HEAD commit. - -```bash -# Will display the branch, untracked files, changes and other differences -$ git status - -# To learn other "tid bits" about git status -$ git help status +# if set to a persistent type (not 'memory', for example 'redis') fact values +# from previous runs in Ansible will be stored. This may be useful when +# wanting to use, for example, IP information from one group of servers +# without having to talk to them in the same playbook run to get their +# current IP information. +fact_caching = jsonfile +fact_caching_connection = ~/facts_cache +fact_caching_timeout = 86400 ``` -### add +I like to use `jsonfile` as my backend. It allows to use another project +`ansible-cmdb` [github] that generates a HTML page of your inventory resources. A nice 'free' addition! -To add files to the staging area/index. If you do not `git add` new files to -the staging area/index, they will not be included in commits! +#### debugging ansible +When your job fails - it is good to be effective with debugging. -```bash -# add a file in your current working directory -$ git add HelloWorld.java - -# add a file in a nested dir -$ git add /path/to/file/HelloWorld.c - -# Regular Expression support! -$ git add ./*.java -``` +1. Increase verbosiy by using multiple -v **[ -vvvvv]** +2. If variable is undefined +3. If variable (dictionary or a list) is undefined +4. Jinja template debug -This only adds a file to the staging area/index, it doesn't commit it to the -working directory/repo. - -### branch - -Manage your branches. You can view, edit, create, delete branches using this -command. +#### Infrastructure as a code - what about Ansible +You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. +See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! ```bash -# list existing branches & remotes -$ git branch -a - -# create a new branch -$ git branch myNewBranch - -# delete a branch -$ git branch -d myBranch + # recreate ansible 2.x venv +$ rm -rf venv2 +$ source environment2.sh + # execute playbook +(venv2)$ ansible-playbook playbooks/ansible1.9_playbook.yml # would fail - deprecated syntax -# rename a branch -# git branch -m -$ git branch -m myBranchName myNewBranchName + # now lets install ansible 1.9.x next to ansible 2.x +(venv2)$ deactivate +$ source environment.1.9.sh + # execute playbook +(venv1.9)$ ansible-playbook playbooks/ansible1.9_playbook.yml # works! -# edit a branch's description -$ git branch myBranchName --edit-description -``` - -### tag - -Manage your tags - -```bash -# List tags -$ git tag - -# Create a annotated tag -# The -m specifies a tagging message,which is stored with the tag. -# If you don’t specify a message for an annotated tag, -# Git launches your editor so you can type it in. -$ git tag -a v2.0 -m 'my version 2.0' - -# Show info about tag -# That shows the tagger information, the date the commit was tagged, -# and the annotation message before showing the commit information. -$ git show v2.0 - -# Push a single tag to remote -$ git push origin v2.0 - -# Push a lot of tags to remote -$ git push origin --tags -``` - -### checkout - -Updates all files in the working tree to match the version in the index, or -specified tree. - -```bash -# Checkout a repo - defaults to master branch -$ git checkout - -# Checkout a specified branch -$ git checkout branchName - -# Create a new branch & switch to it -# equivalent to "git branch ; git checkout " - -$ git checkout -b newBranch -``` - -### clone - -Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you -to push to a remote branch. - -```bash -# Clone learnxinyminutes-docs -$ git clone https://github.com/adambard/learnxinyminutes-docs.git - -# shallow clone - faster cloning that pulls only latest snapshot -$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git - -# clone only a specific branch -$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch -``` - -### commit - -Stores the current contents of the index in a new "commit." This commit -contains the changes made and a message created by the user. - -```bash -# commit with a message -$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" - -# automatically stage modified or deleted files, except new files, and then commit -$ git commit -a -m "Modified foo.php and removed bar.php" - -# change last commit (this deletes previous commit with a fresh commit) -$ git commit --amend -m "Correct message" -``` - -### diff - -Shows differences between a file in the working directory, index and commits. - -```bash -# Show difference between your working dir and the index -$ git diff - -# Show differences between the index and the most recent commit. -$ git diff --cached - -# Show differences between your working dir and the most recent commit -$ git diff HEAD -``` - -### grep - -Allows you to quickly search a repository. - -Optional Configurations: - -```bash -# Thanks to Travis Jeffery for these -# Set line numbers to be shown in grep search results -$ git config --global grep.lineNumber true - -# Make search results more readable, including grouping -$ git config --global alias.g "grep --break --heading --line-number" -``` - -```bash -# Search for "variableName" in all java files -$ git grep 'variableName' -- '*.java' - -# Search for a line that contains "arrayListName" and, "add" or "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) -``` - -Google is your friend; for more examples -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) - -### log - -Display commits to the repository. - -```bash -# Show all commits -$ git log - -# Show only commit message & ref -$ git log --oneline - -# Show merge commits only -$ git log --merges - -# Show all commits represented by an ASCII graph -$ git log --graph -``` - -### merge - -"Merge" in changes from external commits into the current branch. - -```bash -# Merge the specified branch into the current. -$ git merge branchName - -# Always generate a merge commit when merging -$ git merge --no-ff branchName -``` - -### mv - -Rename or move a file - -```bash -# Renaming a file -$ git mv HelloWorld.c HelloNewWorld.c - -# Moving a file -$ git mv HelloWorld.c ./new/path/HelloWorld.c - -# Force rename or move -# "existingFile" already exists in the directory, will be overwritten -$ git mv -f myFile existingFile -``` - -### pull - -Pulls from a repository and merges it with another branch. - -```bash -# Update your local repo, by merging in new changes -# from the remote "origin" and "master" branch. -# git pull -$ git pull origin master - -# By default, git pull will update your current branch -# by merging in new changes from its remote-tracking branch -$ git pull - -# Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git fetch , git -# rebase /" -$ git pull origin master --rebase -``` - -### push - -Push and merge changes from a branch to a remote & branch. - -```bash -# Push and merge changes from a local repo to a -# remote named "origin" and "master" branch. -# git push -$ git push origin master - -# By default, git push will push and merge changes from -# the current branch to its remote-tracking branch -$ git push - -# To link up current local branch with a remote branch, add -u flag: -$ git push -u origin master -# Now, anytime you want to push from that same local branch, use shortcut: -$ git push + # please note that you have both venv1.9 and venv2 present - you need to (de)activate one - that is all ``` +### Naming -### stash +### Bonus -Stashing takes the dirty state of your working directory and saves it on a -stack of unfinished changes that you can reapply at any time. +### writing own module -Let's say you've been doing some work in your git repo, but you want to pull -from the remote. Since you have dirty (uncommited) changes to some files, you -are not able to run `git pull`. Instead, you can run `git stash` to save your -changes onto a stack! +### Python API -```bash -$ git stash -Saved working directory and index state \ - "WIP on master: 049d078 added the index file" - HEAD is now at 049d078 added the index file - (To restore them type "git stash apply") -``` +### Web-UI: Ansible Tower, Jenkins, Rundeck -Now you can pull! +#### Ansible Tower +Ansible provides a Web User Interface called `Ansible Tower`. +It is a convienient way to run Ansible Playbooks, have proper user management, log retention, and cron (periodic jobs). -```bash -git pull -``` -`...changes apply...` +Personaly I'm not a fan of it - it's to expensive for my cases, and the trial is 10 inventory-hosts only. -Now check that everything is OK +For my usecases I hide the 'pure ansible' commands behind other projects. -```bash -$ git status -# On branch master -nothing to commit, working directory clean -``` +#### Rundeck +This is nice, secure interface, that allows you to execute a jobs of your choice (CLI, script, execution plan). +It can perform roling-deployment (without Ansible), can integrate with clouds, etc. -You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent -change will be at top. +#### Jenkins +For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into 'pipelines'. -```bash -$ git stash list -stash@{0}: WIP on master: 049d078 added the index file -stash@{1}: WIP on master: c264051 Revert "added file_size" -stash@{2}: WIP on master: 21d80a5 added number to log -``` - -Now let's apply our dirty changes back by popping them off the stack. - -```bash -$ git stash pop -# On branch master -# Changes not staged for commit: -# (use "git add ..." to update what will be committed) -# -# modified: index.html -# modified: lib/simplegit.rb -# -``` +### become-user, become +### ansible - dynamic in AWS +### create instance in AWS +### create env in AWS -`git stash apply` does the same thing +### Tips and tricks -Now you're ready to get back to work on your stuff! +##### --check -C +Always make sure that your playbook can executes in 'dry run' mode (--check), and it's execution is not declaring 'Changed' objects. -[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) +##### --diff -D +Diff is usefull to see nice detail of the files changed -### rebase (caution) +It compare 'in memory' the files like `diff -BbruN fileA fileB` -Take all changes that were committed on one branch, and replay them onto -another branch. -*Do not rebase commits that you have pushed to a public repo*. +##### Execute hosts with 'regex' ```bash -# Rebase experimentBranch onto master -# git rebase -$ git rebase master experimentBranch +ansible -m ping web* ``` -[Additional Reading.](http://git-scm.com/book/en/Git-Branching-Rebasing) - -### reset (caution) - -Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you -don't know what you are doing. +##### +Host groups can be joined, negated, etc ```bash -# Reset the staging area, to match the latest commit (leaves dir unchanged) -$ git reset - -# Reset the staging area, to match the latest commit, and overwrite working dir -$ git reset --hard - -# Moves the current branch tip to the specified commit (leaves dir unchanged) -# all changes still exist in the directory. -$ git reset 31f2bb1 - -# Moves the current branch tip backward to the specified commit -# and makes the working dir match (deletes uncommited changes and all commits -# after the specified commit). -$ git reset --hard 31f2bb1 +ansible -m ping web*:!backend:monitoring:&allow_change ``` -### reflog (caution) +##### Tagging +You should tag some (not all) objects - a task in a playbook, all tasks included form a role, etc. +It allwos you to execute the choosen parts of the playbook. -Reflog will list most of the git commands you have done for a given time period, -default 90 days. +##### no_logs: True +You may see, that some roles print a lot of output in verbose mode. There is also a debug module. +This is the place where credentials may leak. Use `no_log` to hide the output. -This give you the a change to reverse any git commands that have gone wrong -for instance if a rebase is has broken your application. +##### Debug module +allows to print a value to the screen -You can do this: +##### Register the output of a task +You can register the output (stdout), rc (return code), stderr of a task with the `register` command. -1. `git reflog` to list all of the git commands for the rebase -``` -38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog -38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators -4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown -34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) -ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) -2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d -``` -2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` -3. 'git reset --hard HEAD@{5}' this will reset your repo to that head -4. You can start the rebase again or leave it alone. +##### Conditionals: when: -[Additional Reading.](https://git-scm.com/docs/git-reflog) +##### Loop: with, with_items, with_dict, with_together -### revert -Revert can be used to undo a commit. It should not be confused with reset which -restores the state of a project to a previous point. Revert will add a new -commit which is the inverse of the specified commit, thus reverting it. +## Introduction +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' -```bash -# Revert a specified commit -$ git revert -``` +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) -### rm -The opposite of git add, git rm removes files from the current working tree. -```bash -# remove HelloWorld.c -$ git rm HelloWorld.c +## Main cons and pros -# Remove a file from a nested dir -$ git rm /pather/to/the/file/HelloWorld.c -``` +### Cons -## Further Information +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. -* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +### Pros -* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/) +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. -* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) -* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. -* [git-scm - Video Tutorials](http://git-scm.com/videos) +## Basics on ansible -* [git-scm - Documentation](http://git-scm.com/docs) +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. -* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! -* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) -* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) -* [Pro Git](http://www.git-scm.com/book/en/v2) +# JM inventory dynamic aws ec2 +# vault +# roles -* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From bb4deacd225d410e6c0b09c67cc2b889c4825ff3 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:02:01 +0200 Subject: test markdown --- ansible.html.markdown | 50 +++++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 0023a718..9c1b86e8 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usally python) that execute, do some work and return proper JSON output :)*_ +_*program (usally python) that execute, do some work and return proper JSON output *_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -78,28 +78,6 @@ $ ansible -m command -a 'whoami' all * Module: `file` - performs file operations (stat, link, dir, ...) * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) - -## Ansible - naming and quick intro - -### Inventory -Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands -For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) - -`/etc/ansible/hosts` -``` -localhost - -[some_group] -hostA.mydomain.com -hostB.localdomain - -[a_group_of_a_groups:children] -some_group -some_other_group - -``` -* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) - ### Task Execution of a single Ansible **module** is called a **task** @@ -141,6 +119,24 @@ $ ansible-playbook path/name_of_the_playbook.yml ``` ### More on ansible concept +### Inventory +Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) + +`/etc/ansible/hosts` +``` +localhost + +[some_group] +hostA.mydomain.com +hostB.localdomain + +[a_group_of_a_groups:children] +some_group +some_other_group + +``` +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### ansible-roles (a 'template-playbooks' with right structure) You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). @@ -296,7 +292,7 @@ $ ansible -m ping all -i etc/inv/ec2.py ``` #### ansible profiling - callback -It is ok that your playbook executes some time. Sometimes you may like to speed things up :) +It is ok that your playbook executes some time. Sometimes you may like to speed things up Since ansible 2.x there is bouilt-in callback for task execution profiling @@ -427,7 +423,7 @@ You can register the output (stdout), rc (return code), stderr of a task with th ## Introduction Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) +'You can think as simple as writing in bash with python API Of course the rabit hole is way deeper.' Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) @@ -444,9 +440,9 @@ Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is ### Pros -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +It is an agent-less tools In most scenarios, it use ssh as a transport layer. In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) Documentation is at the world-class standard! -- cgit v1.2.3 From 6c378a858964a5c5d656e39f8fec110b584e7bd0 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:02:50 +0200 Subject: test markdown --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 9c1b86e8..1cf77033 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usally python) that execute, do some work and return proper JSON output *_ +_program (usally python) that execute, do some work and return proper JSON output_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). -- cgit v1.2.3 From c2bcf94c80e1bfc2314014a8e7dd0858c6e4207c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:05:12 +0200 Subject: test markdown --- ansible.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1cf77033..d68eafd8 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -137,7 +137,7 @@ some_other_group ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) -#### ansible-roles (a 'template-playbooks' with right structure) +### ansible-roles (a 'template-playbooks' with right structure) You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). @@ -205,7 +205,7 @@ For now you might like to know, that CLI variables has the top priority. You should also know, that a nice way to pool some data is a **lookup** -##### Lookups +### Lookups * pipe * file @@ -218,7 +218,7 @@ ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" lo ``` -#### Templates +### Templates Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. @@ -233,7 +233,7 @@ Some static content ``` Jinja may have some limitations, but it is a powerfull tool that you might like. -#### Jinja2 CLI +### Jinja2 CLI You can use the jinja in the CLI too ```bash ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost @@ -248,7 +248,7 @@ Junja is powerfull. It has built-in many usefull functions. {{ some_variable | default('default_value') }} ``` -#### ansible-vault +### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. Ansible provides a way to encrypt the poufne files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. @@ -278,7 +278,7 @@ $ cat path/somefile $ ansible-vault decrypt path/somefile ``` -#### dynamic inventory +### dynamic inventory You might like to know, that you can build your inventory dynamically. (For Ansible) inventory is just a JSON with proper structure - if you can deliver that to ansible - anything is possible. @@ -291,7 +291,7 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` -#### ansible profiling - callback +### ansible profiling - callback It is ok that your playbook executes some time. Sometimes you may like to speed things up Since ansible 2.x there is bouilt-in callback for task execution profiling @@ -302,7 +302,7 @@ vi ansible.cfg callback_whitelist = profile_tasks ``` -#### facts-cache and ansible-cmdb +### facts-cache and ansible-cmdb You can pool some infrmations of you environment from another hosts. If the informations does not change - you may consider using a facts_cache to speed things up. @@ -322,7 +322,7 @@ fact_caching_timeout = 86400 I like to use `jsonfile` as my backend. It allows to use another project `ansible-cmdb` [github] that generates a HTML page of your inventory resources. A nice 'free' addition! -#### debugging ansible +### debugging ansible When your job fails - it is good to be effective with debugging. 1. Increase verbosiy by using multiple -v **[ -vvvvv]** @@ -330,7 +330,7 @@ When your job fails - it is good to be effective with debugging. 3. If variable (dictionary or a list) is undefined 4. Jinja template debug -#### Infrastructure as a code - what about Ansible +### Infrastructure as a code - what about Ansible You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! @@ -379,46 +379,46 @@ For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into ### create instance in AWS ### create env in AWS -### Tips and tricks +## Tips and tricks -##### --check -C +#### --check -C Always make sure that your playbook can executes in 'dry run' mode (--check), and it's execution is not declaring 'Changed' objects. -##### --diff -D +#### --diff -D Diff is usefull to see nice detail of the files changed It compare 'in memory' the files like `diff -BbruN fileA fileB` -##### Execute hosts with 'regex' +#### Execute hosts with 'regex' ```bash ansible -m ping web* ``` -##### +#### Host groups can be joined, negated, etc ```bash ansible -m ping web*:!backend:monitoring:&allow_change ``` -##### Tagging +#### Tagging You should tag some (not all) objects - a task in a playbook, all tasks included form a role, etc. It allwos you to execute the choosen parts of the playbook. -##### no_logs: True +#### no_logs: True You may see, that some roles print a lot of output in verbose mode. There is also a debug module. This is the place where credentials may leak. Use `no_log` to hide the output. -##### Debug module +#### Debug module allows to print a value to the screen -##### Register the output of a task +#### Register the output of a task You can register the output (stdout), rc (return code), stderr of a task with the `register` command. -##### Conditionals: when: +#### Conditionals: when: -##### Loop: with, with_items, with_dict, with_together +#### Loop: with, with_items, with_dict, with_together ## Introduction -- cgit v1.2.3 From a090f8fd0af03ca558d57392a60edf6aa7184f4f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:07:12 +0200 Subject: test markdown --- ansible.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index d68eafd8..699e4419 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -291,6 +291,8 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` +Read also about `dynamic inventory` below + ### ansible profiling - callback It is ok that your playbook executes some time. Sometimes you may like to speed things up -- cgit v1.2.3 From 1f035686ef8f6605d8e43c1c6138bae10c4f9b0d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 21:42:16 +0200 Subject: set -e - again --- ansible.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 699e4419..e17e543f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -376,10 +376,7 @@ It can perform roling-deployment (without Ansible), can integrate with clouds, #### Jenkins For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into 'pipelines'. -### become-user, become -### ansible - dynamic in AWS -### create instance in AWS -### create env in AWS +#### become-user, become ## Tips and tricks @@ -470,3 +467,6 @@ But ansible is way more! It provides an execution plans, an API, library, callba # vault # roles +#### ansible - dynamic in AWS +#### create instance in AWS +#### create env in AWS -- cgit v1.2.3 From 66055cf822018d1c2f38b352919c5ccdc4aeb437 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 22:31:58 +0200 Subject: set -e - again --- ansible.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index e17e543f..c495b308 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -109,6 +109,7 @@ hosts: all tasks: - name: "ping all" ping: + - name: "execute a shell command" shell: "date; whoami; df -h;" ``` @@ -174,8 +175,12 @@ We would clone the ready-to-use examples from additional repository ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes -$ source environment -$(venv) ansible-playbook playbooks/role_example.yml +$ source environment.sh +(venv) u@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml + +# First lets execute the simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminute$ ansible-playbook playbook/simple_playbook.yml + ``` #### Role directory structure: -- cgit v1.2.3 From d81ed7f3b7bfdc748b74f75debd5451cb5bbee59 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:24:45 +0200 Subject: set -e - again --- ansible.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c495b308..d134c073 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,18 +169,23 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -Example->role - -We would clone the ready-to-use examples from additional repository +#### We would use repository with *ready to use* examples +We would clone the repository ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes $ source environment.sh -(venv) u@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml +$ +$# First lets execute the simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml -# First lets execute the simple_playbook.yml -(venv) user@host:~/ansible-for-learnXinYminute$ ansible-playbook playbook/simple_playbook.yml +``` +```bash +$ source environment.sh +$ +$# Now we would run the above playbook with roles +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml ``` #### Role directory structure: -- cgit v1.2.3 From 340f30f3410602e649c224eb9804f826d2fc8e0e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:26:03 +0200 Subject: set -e - again --- ansible.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index d134c073..d3a0fb34 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -176,15 +176,14 @@ $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes $ source environment.sh $ -$# First lets execute the simple_playbook.yml +$ # First lets execute the simple_playbook.yml (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml ``` ```bash $ source environment.sh -$ -$# Now we would run the above playbook with roles +$ # Now we would run the above playbook with roles (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml ``` -- cgit v1.2.3 From 1a935188969deac50f30fe356422d8003188afbb Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:29:13 +0200 Subject: set -e - again --- ansible.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index d3a0fb34..91442dbf 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -171,10 +171,12 @@ pre_tasks: #### We would use repository with *ready to use* examples We would clone the repository +This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command + ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git -$ cd ansible-for-learnXinYminutes -$ source environment.sh +user@host:~/$ cd ansible-for-learnXinYminutes +user@host:~/ansible-for-learnXinYminutes$ source environment.sh $ $ # First lets execute the simple_playbook.yml (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml -- cgit v1.2.3 From 738f09d92596b3c9f12477d4e0ac88f9ad9c7c76 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:30:15 +0200 Subject: set -e - again --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 91442dbf..ee313f2c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -170,7 +170,7 @@ pre_tasks: ``` #### We would use repository with *ready to use* examples -We would clone the repository +For remaining examples we would clone the repository This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash -- cgit v1.2.3 From a3e6e2bb3b4ed325cd6fea0cc4f7590cb198849f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:31:14 +0200 Subject: set -e - again --- ansible.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ee313f2c..57f559ef 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,8 +169,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -#### We would use repository with *ready to use* examples -For remaining examples we would clone the repository +#### For remaining examples we would use repository with *ready to use* examples This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash -- cgit v1.2.3 From 68eae69fb5471f645265216967044905f3471a29 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:32:41 +0200 Subject: set -e - again --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 57f559ef..04862a14 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,7 +169,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -#### For remaining examples we would use repository with *ready to use* examples +#### For remaining examples we would use additional repository This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash @@ -182,6 +182,7 @@ $ # First lets execute the simple_playbook.yml ``` +Run the above playbook with roles example ```bash $ source environment.sh $ # Now we would run the above playbook with roles -- cgit v1.2.3 From ceac9628c238b8835df8d7c0154c7a91d60ac74f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:45:03 +0200 Subject: set -e - again --- ansible.html.markdown | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 04862a14..bd0200f6 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -104,14 +104,14 @@ This example-playbook would execute (on all hosts defined in the inventory) two * `shell` that execute three commands and return the output to our terminal ```yml -hosts: all - -tasks: - - name: "ping all" - ping: - - - name: "execute a shell command" - shell: "date; whoami; df -h;" +- hosts: all + + tasks: + - name: "ping all" + ping: + + - name: "execute a shell command" + shell: "date; whoami; df -h;" ``` You can run the playbook with the command: @@ -152,21 +152,21 @@ Role can be included in your playbook (executed via your playbook). ```yml -hosts: all - -tasks: - - name: "ping all" - ping: - - name: "execute a shell command" - shell: "date; whoami; df -h;" - -role: - - some_role - - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } - -pre_tasks: - - name: some pre-task - shell: echo 'this task is the last, but would be executed before roles, and before tasks' +- hosts: all + + tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" + + roles: + - some_role + - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } + + pre_tasks: + - name: some pre-task + shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` #### For remaining examples we would use additional repository -- cgit v1.2.3 From bb31a53eb2c559d327b6bc7f58735b410ae4815f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 21 Oct 2017 00:01:29 +0200 Subject: set -e - again --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index bd0200f6..e41d1a6a 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -225,7 +225,8 @@ You should also know, that a nice way to pool some data is a **lookup** You can use them in CLI too ```yaml -ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" localhost +ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "date") }}"' localhost +ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "hostname") }}"' all ``` -- cgit v1.2.3 From 5621c64a0928e939f493f6672fcb08953a581d00 Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Tue, 24 Oct 2017 02:11:49 -0400 Subject: Traslate from EN to ES --- es-es/matlab-es.html.markdown | 566 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 566 insertions(+) create mode 100644 es-es/matlab-es.html.markdown diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown new file mode 100644 index 00000000..d4b2dab1 --- /dev/null +++ b/es-es/matlab-es.html.markdown @@ -0,0 +1,566 @@ +--- +language: Matlab +filename: learnmatlab.mat +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Claudson Martins", "http://github.com/claudsonm"] +lang: es-es +--- + +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB significa MATrix LABoratory. Es un poderoso lenguaje de computacion numerica + +If you have any feedback please feel free to reach me at +[@the_ozzinator](https://twitter.com/the_ozzinator), or +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```matlab +%% Una sección de código comienza con dos símbolos de porcentaje. Los títulos de la sección van en la misma línea. +% Los comentarios comienzan con un símbolo de porcentaje. +W +%{ +Los Comentarios de multiples lineas se +ven +como +esto +%} + +% Dos símbolos de porcentaje denotan el comienzo de una nueva sección de código. +% Secciones de código individuales pueden ser ejecutadas moviendo el cursor hacia la sección, +% seguida por un clic en el botón de “Ejecutar Sección” +% o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (OS X) + +%% This is the start of a code section +% Una forma de usar las secciones es separar un código de inicio costoso que no cambia, como cargar datos +load learnmatlab.mat y + +%% Esta es otra sección de código +% Esta sección puede ser editada y ejecutada de manera repetida por sí misma, +% y es útil para la programación exploratoria y demostraciones. +A = A * 2; +plot(A); + +%% Las secciones de códigos también son conocidas como celdas de código o modo celda (no ha de ser confundido con arreglo de celdas) + + +% Los comandos pueden abarcar varias líneas, usando '...' + a = 1 + 2 + ... + + 4 + +% Los comandos se pueden pasar al sistema operativo +!ping google.com + +who % Muestra todas las variables en la memoria +whos % Muestra todas las variables en la memoria con sus tipos +clear % Borra todas tus variables de la memoria +clear('A') % Borra una variable en particular +openvar('A') % Variable abierta en editor de variables + +clc % Borra la escritura en la ventana de Comando +diary % Alterna la escritura del texto de la ventana de comandos al archivo +ctrl-c % Aborta el cálculo actual + +edit('myfunction.m') % Abrir función/script en el editor +type('myfunction.m') % Imprime la fuente de la función/script en la ventana de comandos + +profile on % Enciende el generador de perfilador de código +profile off % Apaga el generador de perfilador de código +profile viewer % Abre el perfilador de código + +help command % Muestra la documentación del comando en la ventana de comandos +doc command % Muestra la documentación del comando en la ventana de Ayuda +lookfor command % Busca el comando en la primera línea comentada de todas las funciones +lookfor command -all % busca el comando en todas las funciones + + +% Formato de salida +format short % 4 decimales en un número flotante +format long % 15 decimales +format bank % solo dos dígitos después del punto decimal - para cálculos financieros +fprintf('texto') % imprime "texto" en la pantalla +disp('texto') % imprime "text" en la pantalla + +% Variables y expresiones +myVariable = 4 % Espacio de trabajo de aviso muestra la variable recién creada +myVariable = 4; % Semi-colon suprime la salida a la Ventana de Comando +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% Llamar funciones se pueden realizar de dos maneras: +% Sintaxis de función estándar: +load('myFile.mat', 'y') % argumentos entre paréntesis, separados por comas +% Sintaxis del comando: +load myFile.mat y % sin paréntesis, y espacios en lugar de comas +% Tenga en cuenta la falta de comillas en el formulario de comandos: +% las entradas siempre se pasan como texto literal; no pueden pasar valores de variables. +% Además, no puede recibir salida: +[V,D] = eig(A); % esto no tiene equivalente en forma de comando +[~,D] = eig(A); % si solo se quiere D y no V + + + +% Operadores lógicos +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % No es igual a -> ans = 1 +3 == 3 % Es igual a -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Los operadores lógicos se pueden aplicar a matrices: +A > 5 +% para cada elemento, si la condición es verdadera, ese elemento es 1 en la matriz devuelta +A( A > 5 ) +% devuelve un vector que contiene los elementos en A para los que la condición es verdadera + +% Cadenas +a = 'MyCadena' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Celdas +a = {'uno', 'dos', 'tres'} +a(1) % ans = 'uno' - retorna una celda +char(a(1)) % ans = one - retorna una cadena + +% Estructuras +A.b = {'uno','dos'}; +A.c = [1 2]; +A.d.e = false; + +% Vectores +x = [4 32 53 7 1] +x(2) % ans = 32, índices en Matlab comienzan 1, no 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vector de columna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 +x = [1:2:10] % Incrementa por 2, i.e. x = 1 3 5 7 9 + +% Matrices +A = [1 2 3; 4 5 6; 7 8 9] +% Las filas están separadas por un punto y coma; los elementos se separan con espacio o coma +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (concatena implícitamente columnas en el vector, luego indexa en base a esto) + + +A(2,3) = 42 % Actualiza la fila 2 col 3 con 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Crea una nueva matriz a partir de la anterior +%ans = + +% 5 42 +% 8 9 + +A(:,1) % Todas las filas en la columna 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % Todas las columnas en la fila 1 +%ans = + +% 1 2 3 + +[A ; A] % Concatenación de matrices (verticalmente) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% esto es lo mismo que +vertcat(A,A); + + +[A , A] % Concatenación de matrices (horizontalmente) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% esto es lo mismo que +horzcat(A,A); + + +A(:, [3 1 2]) % Reorganiza las columnas de la matriz original +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % ans = 3 3 + +A(1, :) =[] % Elimina la primera fila de la matriz +A(:, 1) =[] % Elimina la primera columna de la matriz + +transpose(A) % Transponer la matriz, que es lo mismo que: +A one +ctranspose(A) % Hermitian transpone la matriz +% (la transposición, seguida de la toma del conjugado complejo de cada elemento) +A' % Versión concisa de transposición compleja +A.' % Versión concisa de transposición (sin tomar complejo conjugado) + + + + +% Elemento por elemento Aritmética vs. Matriz Aritmética +% Por sí solos, los operadores aritméticos actúan sobre matrices completas. Cuando preceden +% por un punto, actúan en cada elemento en su lugar. Por ejemplo: +A * B % Matrix multiplication +A .* B % Multiple each element in A by its corresponding element in B + +% There are several pairs of functions, where one acts on each element, and +% the other (whose name ends in m) acts on the whole matrix. +exp(A) % exponencializar cada elemento +expm(A) % calcular la matriz exponencial +sqrt(A) % tomar la raíz cuadrada de cada elemento +sqrtm(A) % encuentra la matriz cuyo cuadrado es A + + +% Trazando +x = 0:.10:2*pi; % Crea un vector que comienza en 0 y termina en 2 * pi con incrementos de .1 +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x rango de 0 a 2 * pi, y rango de -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Para múltiples funciones en una parcela. +legend('Line 1 label', 'Line 2 label') % Etiquetar curvas con una leyenda. + +% Método alternativo para trazar múltiples funciones en una parcela. +% mientras 'hold' está activado, los comandos se agregan al gráfico existente en lugar de reemplazarlo. +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Un diagrama de log-log. +semilogx(x, y) % Un diagrama con el eje x logarítmico. +semilogy(x, y) % Un diagrama con el eje y logarítmico. + +fplot (@(x) x^2, [2,5]) % Un diagrama con el eje y logarítmico... + +grid on % Muestra la cuadrícula; apague con 'grid off'. +axis square % Hace que la región actual de los ejes sea cuadrada. +axis equal % Establezce la relación de aspecto para que las unidades de datos sean las mismas en todas las direcciones. + +scatter(x, y); % Gráfico de dispersión +hist(x); % Histograma +stem(x); % Traza los valores como tallos, útiles para mostrar datos discretos. +bar(x); % Diagrama de barras + +z = sin(x); +plot3(x,y,z); % Trazado de línea 3D. + +pcolor(A) % Trazado de línea 3D... +contour(A) % Diagrama de contorno de la matriz. +mesh(A) % Traza una superficie de malla. + +h = figure % Crea nuevo objeto figura, con el mango h. +figure(h) % Hace que la figura correspondiente al mango h la figura actual. +close(h) % Cierra la figura con mango h. +close all % Cierra todas las ventanas con figura abierta. +close % Cierra ventana de figura actual. + +shg % Trae una ventana gráfica existente hacia adelante, o crea una nueva si es necesario. +clf clear % Borra la ventana de la figura actual y restablece la mayoría de las propiedades de la figura. + +% Las propiedades se pueden establecer y cambiar a través de un identificador de figura. +% Puede guardar un identificador de una figura cuando la crea. +% La función get devuelve un handle a la figura actual +h = plot(x, y); % Puedes guardar un control de una figura cuando la creas +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') +% '-' es línea continua, '---' discontinua, ':' punteada, '-.' dash-dot, 'ninguno' no es línea +get (h, 'LineStyle') + + +% La función gca devuelve un mango a los ejes para la figura actual +set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis + +% Para crear una figura que contenga varios ejes en posiciones de mosaico, use 'subplot' +subplot(2,3,1); % seleccione la primera posición en una grilla de subtramas de 2 por 3 +plot(x1); title('First Plot') % trazar algo en esta posición +subplot(2,3,2); % selecciona la segunda posición en la grilla +plot(x2); title('Second Plot') % trazar algo allí + + +% Para usar funciones o scripts, deben estar en su ruta o directorio actual +path % muestra la ruta actual +addpath /path/to/dir % agrega a la ruta +rmpath /path/to/dir % elimina de la ruta +cd /path/to/move/into % cambia de directorio + + +% Las variables se pueden guardar en archivos .mat +save('myFileName.mat') % Guarda las variables en su espacio de trabajo +load('myFileName.mat') % Carga las variables guardadas en Workspace + +% M-file Scripts +% Un archivo de script es un archivo externo que contiene una secuencia de instrucciones. +% Permiten evitar escribir repetidamente el mismo código en la ventana de comandos +% Tienen extensiones .m + +% M-file Functions +% Al igual que los scripts, y tienen la misma extensión .m +% Pero puede aceptar argumentos de entrada y devolver una salida +% Además, tienen su propio espacio de trabajo (es decir, diferente alcance variable). +% El nombre de la función debe coincidir con el nombre del archivo (por lo tanto, guarde este ejemplo como double_input.m). +% 'help double_input.m' devuelve los comentarios en la línea que comienza la función +function output = double_input(x) + % double_input(x) devuelve el doble del valor de x + output = 2*x; +end +double_input(6) % ans = 12 + + +% También puede tener subfunciones y funciones anidadas. +% Las subfunciones están en el mismo archivo que la función primaria, y solo pueden ser +% llamadas por funciones en el archivo. Las funciones anidadas se definen dentro de otra +% otras funciones y tienen acceso tanto a su área de trabajo como a su propio espacio de trabajo. + +% Si desea crear una función sin crear un nuevo archivo, puede usar una +% función anónima. Útil cuando se define rápidamente una función para pasar a +% otra función (por ejemplo, trazar con fplot, evaluar una integral indefinida +% con quad, encuentra roots con fzero, o encuentra mínimo con fminsearch). +% Ejemplo que devuelve el cuadrado de su entrada, asignado al identificador sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % averiguar más + +% User input +a = input('Ingrese el valor:') + +% Detiene la ejecución del archivo y le da control al teclado: el usuario puede examinar +% o cambiar las variables. Escriba 'return' para continuar la ejecución, o 'dbquit' para salir del teclado + +% Lectura de datos (también xlsread / importdata / imread para archivos de excel / CSV / image) +fopen(filename) + +% Salida +disp(a) % Imprime el valor de la variable a +disp('Hello World') % Imprime una cadena +fprintf % Imprime en la ventana de comandos con más control + +% Declaraciones condicionales (los paréntesis son opcionales, pero buen estilo) +if (a > 15) + disp('Greater than 15') +elseif (a == 23) + disp('a is 23') +else + disp('neither condition met') +end + +% Bucles +% NB. haciendo un bucle sobre los elementos de un vector / matriz es lento! +% Siempre que sea posible, use funciones que actúen en todo el vector / matriz a la vez +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Ejecución del código de tiempo: 'toc' imprime el tiempo desde que se llamó 'tic' +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Conectarse a una base de datos MySQL +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depende de la versión, descarga disponible en http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % Ejemplo de instrucción sql +a = fetch(conn, sql) %a contendrá sus datos + + +% Funciones matemáticas comunes +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) % Si x es complejo, devuelve la magnitud +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Números pseudoaleatorios distribuidos uniformemente +randi % Enteros pseudoaleatorios distribuidos uniformemente +randn % Números pseudoaleatorios distribuidos normalmente + +% Operaciones matemáticas complejas +abs(x) % Magnitud de la variable compleja x +phase(x) % Fase (o ángulo) de la variable compleja x +real(x) % Retorna la parte real de x (es decir, devuelve a si x = a + jb) +imag(x) % Retorna la parte imaginaria de x (es decir, devuelve b si x = a + jb) +conj(x) % Retorna el complejo conjugado + + +% Constantes comunes +pi +NaN +inf + +% Resolviendo ecuaciones matriciales (si no hay solución, devuelve una solución de mínimos cuadrados) +%Los operadores \ y / son equivalentes a las funciones mldivide y mrdivide +x=A\b % Resuelve Ax = b. Más rápido y más numéricamente preciso que usar inv (A) * b. +x=b/A % Resuelve xA = b + +inv(A) % calcular la matriz inversa +pinv(A) % calcular el pseudo-inverso + +% Funciones de matriz comunes +zeros(m,n) % m x n matriz de 0 +ones(m,n) % m x n matriz de 1 +diag(A) % Extrae los elementos diagonales de una matriz A +diag(x) % Construya una matriz con elementos diagonales enumerados en x, y ceros en otra parte +eye(m,n) % Matriz de identidad +linspace(x1, x2, n) % Devuelve n puntos equiespaciados, con min x1 y max x2 +inv(A) % Inverso de la matriz A +det(A) % Determinante de A +eig(A) % Valores propios y vectores propios de A +trace(A) % Traza de la matriz: equivalente a la suma (diag (A)) +isempty(A) % Determina si la matriz está vacía +all(A) % Determina si todos los elementos son distintos de cero o verdaderos +any(A) % Determina si alguno de los elementos es distinto de cero o verdadero +isequal(A, B) % Determina la igualdad de dos matrices +numel(A) % Cantidad de elementos en matriz +triu(x) % Devuelve la parte triangular superior de x +tril(x) % Devuelve la parte triangular inferior de x +cross(A,B) % Devuelve el producto cruzado de los vectores A y B +dot(A,B) % Devuelve un producto escalar de dos vectores (debe tener la misma longitud) +transpose(A) % Devuelve la transposición de A +fliplr(A) % Voltee la matriz de izquierda a derecha +flipud(A) % Voltear la matriz de arriba hacia abajo + +% Factorizaciones de matrices +[L, U, P] = lu(A) % Descomposición LU: PA = LU, L es triangular inferior, U es triangular superior, P es matriz de permutación +[P, D] = eig(A) % eigen-decomposition: AP = PD, las columnas de P son autovectores y las diagonales de D'son valores propios +[U,S,V] = svd(X) % SVD: XV = US, U y V son matrices unitarias, S tiene elementos diagonales no negativos en orden decreciente + +% Funciones comunes de vectores +max % componente más grande +min % componente más pequeño +length % longitud de un vector +sort % ordenar en orden ascendente +sum % suma de elementos +prod % product of elements +mode % valor modal +median % valor mediano +mean % valor medio +std % desviación estándar +perms(x) % enumera todas las permutaciones de elementos de x +find(x) % Encuentra todos los elementos distintos de cero de x y devuelve sus índices, puede usar operadores de comparación, + % i.e. find( x == 3 ) devuelve índices de elementos que son iguales a 3 + % i.e. find( x >= 3 ) devuelve índices de elementos mayores o iguales a 3 + + +% Clases +% Matlab puede soportar programación orientada a objetos. +% Las clases deben colocarse en un archivo del nombre de la clase con una extensión .m. +% Para comenzar, creamos una clase simple para almacenar puntos de referencia de GPS. +% Comience WaypointClass.m +classdef WaypointClass % El nombre de la clase. + properties % Las propiedades de la clase se comportan como Estructuras + latitude + longitude + end + methods + % Este método que tiene el mismo nombre de la clase es el constructor. + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Otras funciones que usan el objeto Waypoint + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % Si queremos agregar dos objetos Waypoint juntos sin llamar + % a una función especial, podemos sobrecargar la aritmética de Matlab así: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% Fin WaypointClass.m + +% Podemos crear un objeto de la clase usando el constructor +a = WaypointClass(45.0, 45.0) + +% Las propiedades de clase se comportan exactamente como Matlab Structures. +a.latitude = 70.0 +a.longitude = 25.0 + +% Los métodos se pueden llamar de la misma manera que las funciones +ans = multiplyLatBy(a,3) + +% El método también se puede llamar usando notación de puntos. En este caso, el objeto +% no necesita ser pasado al método. +ans = a.multiplyLatBy(a,1/3) + +% Las funciones de Matlab pueden sobrecargarse para manejar objetos. +% En el método anterior, hemos sobrecargado cómo maneja Matlab +% la adición de dos objetos Waypoint. +b = WaypointClass(15.0, 32.0) +c = a + b + +``` + +## Más sobre Matlab + +* [The official website (EN)](http://www.mathworks.com/products/matlab/) +* [The official MATLAB Answers forum (EN)](http://www.mathworks.com/matlabcentral/answers/) +* [Loren on the Art of MATLAB (EN)](http://blogs.mathworks.com/loren/) +* [Cleve's Corner (EN)](http://blogs.mathworks.com/cleve/) \ No newline at end of file -- cgit v1.2.3 From ce615ac9a27870abe2cba34f3f65721695504aec Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Tue, 24 Oct 2017 02:19:48 -0400 Subject: Add translator to header --- es-es/matlab-es.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index d4b2dab1..99bee475 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -1,16 +1,17 @@ --- language: Matlab -filename: learnmatlab.mat +filename: learnmatlab-es.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - ["Colton Kohnke", "http://github.com/voltnor"] - ["Claudson Martins", "http://github.com/claudsonm"] +translators: + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] lang: es-es --- -MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. -MATLAB significa MATrix LABoratory. Es un poderoso lenguaje de computacion numerica +MATLAB significa 'MATrix LABoratory'. Es un poderoso lenguaje de computación numérica comúnmente usado en ingeniería y matemáticas. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or @@ -314,7 +315,7 @@ set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis % Para crear una figura que contenga varios ejes en posiciones de mosaico, use 'subplot' subplot(2,3,1); % seleccione la primera posición en una grilla de subtramas de 2 por 3 -plot(x1); title('First Plot') % trazar algo en esta posición +plot(x1); title('First Plot') % traza algo en esta posición subplot(2,3,2); % selecciona la segunda posición en la grilla plot(x2); title('Second Plot') % trazar algo allí -- cgit v1.2.3 From 73b8cd9a39ab9b63dd5e2c1c123c363fd014753a Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Tue, 24 Oct 2017 02:24:04 -0400 Subject: Transale Osvaldo's note --- es-es/matlab-es.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index 99bee475..813d379c 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -13,8 +13,8 @@ lang: es-es MATLAB significa 'MATrix LABoratory'. Es un poderoso lenguaje de computación numérica comúnmente usado en ingeniería y matemáticas. -If you have any feedback please feel free to reach me at -[@the_ozzinator](https://twitter.com/the_ozzinator), or +Si tiene algún comentario, no dude en ponerse en contacto conmigo en +[@the_ozzinator](https://twitter.com/the_ozzinator), o [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). ```matlab @@ -564,4 +564,5 @@ c = a + b * [The official website (EN)](http://www.mathworks.com/products/matlab/) * [The official MATLAB Answers forum (EN)](http://www.mathworks.com/matlabcentral/answers/) * [Loren on the Art of MATLAB (EN)](http://blogs.mathworks.com/loren/) -* [Cleve's Corner (EN)](http://blogs.mathworks.com/cleve/) \ No newline at end of file +* [Cleve's Corner (EN)](http://blogs.mathworks.com/cleve/) + -- cgit v1.2.3 From 8f803122808e802b8bc0bf7b2ecb057207c5f46f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:42:44 +0200 Subject: copy into docker --- .ansible.html.markdown.swl | Bin 0 -> 36864 bytes .ansible.html.markdown.swm | Bin 0 -> 32768 bytes .ansible.html.markdown.swn | Bin 0 -> 61440 bytes ansible.html.markdown | 32 ++++++++++++++++++++++++++++++-- 4 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 .ansible.html.markdown.swl create mode 100644 .ansible.html.markdown.swm create mode 100644 .ansible.html.markdown.swn diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl new file mode 100644 index 00000000..94a17a7d Binary files /dev/null and b/.ansible.html.markdown.swl differ diff --git a/.ansible.html.markdown.swm b/.ansible.html.markdown.swm new file mode 100644 index 00000000..ff91c7a0 Binary files /dev/null and b/.ansible.html.markdown.swm differ diff --git a/.ansible.html.markdown.swn b/.ansible.html.markdown.swn new file mode 100644 index 00000000..25fce1a6 Binary files /dev/null and b/.ansible.html.markdown.swn differ diff --git a/ansible.html.markdown b/ansible.html.markdown index e41d1a6a..53ea153f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -178,7 +178,7 @@ user@host:~/$ cd ansible-for-learnXinYminutes user@host:~/ansible-for-learnXinYminutes$ source environment.sh $ $ # First lets execute the simple_playbook.yml -(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_playbook.yml ``` @@ -186,7 +186,7 @@ Run the above playbook with roles example ```bash $ source environment.sh $ # Now we would run the above playbook with roles -(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_role.yml ``` #### Role directory structure: @@ -206,6 +206,15 @@ roles/ Handlers are a tasks that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. It is a best way to restart a service, check if application port is active (successfull deployment criteria), etc. +Please get familiar how you can use role in simple_apache_role example +``` +playbooks/roles/simple_apache_role/ +├── tasks +│   └── main.yml +└── templates + └── main.yml +``` + ### ansible - variables Ansible is flexible - it has 21 levels of variable precedence @@ -223,11 +232,29 @@ You should also know, that a nice way to pool some data is a **lookup** * stream * etcd +```bash +# read playbooks/lookup.yml +# run +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/lookup.yml +``` + You can use them in CLI too ```yaml ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "date") }}"' localhost ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "hostname") }}"' all +# Or use in playbook + +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/lookup.yml + +``` + +### Register +Another way to dynamicaly generate the variable content is a `register` command +`Register` is also useful to store an output of a task, and use it's value as a logic +for execution further tasks. +``` +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/register_and_when.yml ``` ### Templates @@ -259,6 +286,7 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` +### ansible - tags, limmit, diff, check_mode ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. -- cgit v1.2.3 From c56a644fb3a9acc0687746f3dfd34be0dc1408d9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:55:16 +0200 Subject: copy into docker --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 55 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 94a17a7d..4664ca70 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 53ea153f..ae5ca01e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -249,7 +249,9 @@ ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe" ``` -### Register +### Register and Conditional + +#### Register Another way to dynamicaly generate the variable content is a `register` command `Register` is also useful to store an output of a task, and use it's value as a logic for execution further tasks. @@ -257,6 +259,56 @@ for execution further tasks. (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/register_and_when.yml ``` +```yaml +#file content +--- +- hosts: localhost + tasks: + - name: check the system capacity + shell: df -h / + register: root_size + + - name: debug root_size + debug: + msg: "{{ root_size }}" + + - name: debug root_size return code + debug: + msg: "{{ root_size.rc }}" + + + - name: Print this message when return code of 'check the system capacity' was ok + debug: + msg: "{{ root_size.rc }}" + when: root_size.rc == 0 + +``` +#### Conditionals + +You can define complex logic with ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) + + + +### ansible - tags, limmit + +You should know about a way to increase efficiency by this simple functionality + +#### TAGS + You can tag a task, role (and its tasks), include, etc... + You can then limit an execution by using + --tags tagA, other_tag,... + + There are special tags: always + + --skip-tags can be used to exclude a block of code + +#### LIMMIT + You can limmit an execution of your tasks to defined hosts + --limit my_hostname + --limit groupname + --limit some_prefix* + --limit hostname:group #JM + ### Templates Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. @@ -286,7 +338,6 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` -### ansible - tags, limmit, diff, check_mode ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. -- cgit v1.2.3 From 75379d6b672ed34b5f593c9aea60564e90a0cc3d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:56:38 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4664ca70..607a08ba 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index ae5ca01e..155a3b0e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -285,7 +285,7 @@ for execution further tasks. ``` #### Conditionals -You can define complex logic with ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) +You can define complex logic with Ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) -- cgit v1.2.3 From a3bbb085b06d640b4807c296358f4569599fcd5b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:57:54 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 607a08ba..8916354d 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 155a3b0e..236fca99 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -276,7 +276,8 @@ for execution further tasks. debug: msg: "{{ root_size.rc }}" - +# when: example + - name: Print this message when return code of 'check the system capacity' was ok debug: msg: "{{ root_size.rc }}" -- cgit v1.2.3 From 6c6dfb1884d216983b685ebb2683df7d53779f5a Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:58:23 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 8916354d..4bc70c7b 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 236fca99..b076c11f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -284,7 +284,7 @@ for execution further tasks. when: root_size.rc == 0 ``` -#### Conditionals +#### Conditionals - when: You can define complex logic with Ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) -- cgit v1.2.3 From 41b345c69be430a535345b5dac0a972f85493b0c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:59:23 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 5 +++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4bc70c7b..57301145 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index b076c11f..a6ce656b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -295,7 +295,8 @@ You can define complex logic with Ansible and Jinja functions. Most common is us You should know about a way to increase efficiency by this simple functionality #### TAGS - You can tag a task, role (and its tasks), include, etc... +You can tag a task, role (and its tasks), include, etc... + You can then limit an execution by using --tags tagA, other_tag,... @@ -304,7 +305,7 @@ You should know about a way to increase efficiency by this simple functionality --skip-tags can be used to exclude a block of code #### LIMMIT - You can limmit an execution of your tasks to defined hosts +You can limmit an execution of your tasks to defined hosts --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From 8fc4b38c1010e7e85ef396ff045becc8a998c459 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:59:51 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 1 + 2 files changed, 1 insertion(+) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 57301145..4ffb166f 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index a6ce656b..41d9d62f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -306,6 +306,7 @@ You can tag a task, role (and its tasks), include, etc... #### LIMMIT You can limmit an execution of your tasks to defined hosts + --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From 844e24899e022a948c52cc68b8af33e2d8b28208 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:00:25 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4ffb166f..6f152625 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 41d9d62f..a10540d3 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -290,7 +290,7 @@ You can define complex logic with Ansible and Jinja functions. Most common is us -### ansible - tags, limmit +### ansible - tags, limit You should know about a way to increase efficiency by this simple functionality @@ -304,8 +304,8 @@ You can tag a task, role (and its tasks), include, etc... --skip-tags can be used to exclude a block of code -#### LIMMIT -You can limmit an execution of your tasks to defined hosts +#### LIMIT +You can limit an execution of your tasks to defined hosts --limit my_hostname --limit groupname -- cgit v1.2.3 From 147533c849733dadc2c3db31e9365ff4b4943cbe Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:05:56 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 4 +++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 6f152625..d3239470 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index a10540d3..95735e21 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -298,7 +298,7 @@ You should know about a way to increase efficiency by this simple functionality You can tag a task, role (and its tasks), include, etc... You can then limit an execution by using - --tags tagA, other_tag,... + ansible-playbook playbooks/simple_playbook.yml --tags tagA, tag_other There are special tags: always @@ -307,6 +307,8 @@ You can tag a task, role (and its tasks), include, etc... #### LIMIT You can limit an execution of your tasks to defined hosts + ansible-playbook playbooks/simple_playbook.yml --limmit localhost + --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From c8ef9d6d874da784b3e1de7bce300f37f92292c1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:08:30 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 10 ++++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index d3239470..259fc5a0 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 95735e21..0ad58d45 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -295,14 +295,16 @@ You can define complex logic with Ansible and Jinja functions. Most common is us You should know about a way to increase efficiency by this simple functionality #### TAGS -You can tag a task, role (and its tasks), include, etc... +You can tag a task, role (and its tasks), include, etc, and then run only the tagged resources - You can then limit an execution by using - ansible-playbook playbooks/simple_playbook.yml --tags tagA, tag_other + ansible-playbook playbooks/simple_playbook.yml --tags=tagA,tag_other + ansible-playbook playbooks/simple_playbook.yml -t tagA,tag_other - There are special tags: always + There are special tags: + always --skip-tags can be used to exclude a block of code + --list-tags to list available tags #### LIMIT You can limit an execution of your tasks to defined hosts -- cgit v1.2.3 From d3fdfa1260f7f0f46823dd2df15d50e5c472e41b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 20:54:32 +0100 Subject: update --- ansible.html.markdown | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 0ad58d45..61ff6cff 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -10,7 +10,7 @@ filename: LearnAnsible.txt ```yaml --- -"{{ Why Ansible and detailed Intro }}" written in the second part of document +"{{ Explanation: Why Ansible and detailed Intro }}" written in the second part of document ``` @@ -64,8 +64,7 @@ $ ansible -m ping all $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work -#JM +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work. The command module is more secure, because it will not be affected by the user’s environment. For more complex command - use shell module. ```bash @@ -114,10 +113,11 @@ This example-playbook would execute (on all hosts defined in the inventory) two shell: "date; whoami; df -h;" ``` -You can run the playbook with the command: +Run the playbook with the command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` +_Note: Example playbook is explained in the next chapter: 'Roles' ### More on ansible concept ### Inventory @@ -131,6 +131,7 @@ localhost [some_group] hostA.mydomain.com hostB.localdomain +1.2.3.4 [a_group_of_a_groups:children] some_group @@ -140,7 +141,7 @@ some_other_group * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) ### ansible-roles (a 'template-playbooks' with right structure) - You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). + You already know that the tasks (modules) can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). A concept called `role` was introduced for parts of the code (playbooks) that should be reusable. @@ -170,7 +171,9 @@ Role can be included in your playbook (executed via your playbook). ``` #### For remaining examples we would use additional repository -This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command +This example install ansible in `virtualenv` so it is independend from a system. You need to initialize it into your shell-context with `source environment.sh` command. + +We are going to use repository with examples: sirkubax/ansible-for-learnXinYminutes.git ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git @@ -331,13 +334,13 @@ Some static content ``` Jinja may have some limitations, but it is a powerfull tool that you might like. -### Jinja2 CLI +#### Jinja2 CLI You can use the jinja in the CLI too ```bash ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost ``` -### Jinja2 filters +#### Jinja2 filters Junja is powerfull. It has built-in many usefull functions. ```jinja # get first item of the list @@ -345,6 +348,7 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` +[Read More] ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. @@ -353,13 +357,17 @@ To maintain **ifrastructure as a code** you need to store secrets. The best way to use the **ansible-vault** is to store the secret in some secure location, and configure ansible to use during runtime. ```bash +# Try (this would fail) +$ ansible-playbook playbooks/vault_example.yml + $ echo some_very_very_long_secret > ~/.ssh/secure_located_file +# in ansible.cfg set the path to your secret file $ vi ansible.cfg ansible_vault_password_file = ~/.ssh/secure_located_file -#or to use env -export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file +#or use env +$ export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file $ ansible-playbook playbooks/vault_example.yml -- cgit v1.2.3 From 22d4cadc8046fc941c99bbfed367cbe56f6831f0 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 20:55:04 +0100 Subject: update --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 61ff6cff..067ea291 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -173,7 +173,7 @@ Role can be included in your playbook (executed via your playbook). #### For remaining examples we would use additional repository This example install ansible in `virtualenv` so it is independend from a system. You need to initialize it into your shell-context with `source environment.sh` command. -We are going to use repository with examples: sirkubax/ansible-for-learnXinYminutes.git +We are going to use repository with examples: https://github.com/sirkubax/ansible-for-learnXinYminutes ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git -- cgit v1.2.3 From 493beb467cb4b1a9fd636e6e79ed1d02c86b0256 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 20:57:43 +0100 Subject: update --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 067ea291..9661fdf4 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -176,7 +176,8 @@ This example install ansible in `virtualenv` so it is independend from a system. We are going to use repository with examples: https://github.com/sirkubax/ansible-for-learnXinYminutes ```bash -$ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git +$ # The folowing example contain a shell-prompt to indicate the venv and relative path +$ git clone git@github.com:sirkubax/ansible-for-learnXinYminutes.git user@host:~/$ cd ansible-for-learnXinYminutes user@host:~/ansible-for-learnXinYminutes$ source environment.sh $ -- cgit v1.2.3 From 0d9aad8f71a7246088389735e6a8f73111d14407 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:03:34 +0100 Subject: update --- ansible.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 9661fdf4..1329f7e7 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -176,7 +176,7 @@ This example install ansible in `virtualenv` so it is independend from a system. We are going to use repository with examples: https://github.com/sirkubax/ansible-for-learnXinYminutes ```bash -$ # The folowing example contain a shell-prompt to indicate the venv and relative path +$ # The folowing example contains a shell-prompt to indicate the venv and relative path $ git clone git@github.com:sirkubax/ansible-for-learnXinYminutes.git user@host:~/$ cd ansible-for-learnXinYminutes user@host:~/ansible-for-learnXinYminutes$ source environment.sh @@ -186,7 +186,7 @@ $ # First lets execute the simple_playbook.yml ``` -Run the above playbook with roles example +Run the playbook with roles example ```bash $ source environment.sh $ # Now we would run the above playbook with roles @@ -223,9 +223,9 @@ playbooks/roles/simple_apache_role/ Ansible is flexible - it has 21 levels of variable precedence -[read more] +[read more](http://docs.ansible.com/ansible/latest/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) -For now you might like to know, that CLI variables has the top priority. +For now you should know that CLI variables have the top priority. You should also know, that a nice way to pool some data is a **lookup** -- cgit v1.2.3 From 4041b4c45db1796c3a8410211c6a355728b71c6a Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:05:16 +0100 Subject: update --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1329f7e7..4462cbbb 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -230,6 +230,7 @@ For now you should know that CLI variables have the top priority. You should also know, that a nice way to pool some data is a **lookup** ### Lookups +query from: * pipe * file -- cgit v1.2.3 From 91a81abb7de572b5fb595f641688b75144de5b75 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:21:39 +0100 Subject: update --- ansible.html.markdown | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 4462cbbb..e4023e5a 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -239,7 +239,7 @@ query from: ```bash # read playbooks/lookup.yml -# run +# then run (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/lookup.yml ``` @@ -257,7 +257,7 @@ ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe" ### Register and Conditional #### Register -Another way to dynamicaly generate the variable content is a `register` command +Another way to dynamicaly generate the variable content is a `register` command. `Register` is also useful to store an output of a task, and use it's value as a logic for execution further tasks. ``` @@ -265,7 +265,6 @@ for execution further tasks. ``` ```yaml -#file content --- - hosts: localhost tasks: @@ -293,6 +292,16 @@ for execution further tasks. You can define complex logic with Ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) +```yaml +--- +- hosts: localhost + tasks: + - name: check the system capacity + shell: df -h / + when: some_variable in 'a string' + roles: + - { role: mid_nagios_probe, when: allow_nagios_probes } +``` ### ansible - tags, limit -- cgit v1.2.3 From ca0e3475a019cfbe4532ddee6b1d9e5c1191c93c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:31:22 +0100 Subject: update --- ansible.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index e4023e5a..bca1331c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -320,6 +320,8 @@ You can tag a task, role (and its tasks), include, etc, and then run only the ta --skip-tags can be used to exclude a block of code --list-tags to list available tags +[Read more](http://docs.ansible.com/ansible/latest/playbooks_tags.html) + #### LIMIT You can limit an execution of your tasks to defined hosts @@ -350,6 +352,20 @@ You can use the jinja in the CLI too ```bash ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost ``` +In fact - jinja is used to template parts of the playbooks too +```yml +#check part of this playbook: playbooks/roles/sys_debug/tasks/debug_time.yml +- local_action: shell date +'%F %T' + register: ts + become: False + changed_when: False + +- name: Timestamp + debug: msg="{{ ts.stdout }}" + when: ts is defined and ts.stdout is defined + become: False + +``` #### Jinja2 filters Junja is powerfull. It has built-in many usefull functions. -- cgit v1.2.3 From 71ce506fc95d1aa8ed0b20f5a8b3687235639c0d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:39:09 +0100 Subject: update --- ansible.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index bca1331c..a35bcf82 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -347,6 +347,16 @@ Some static content ``` Jinja may have some limitations, but it is a powerfull tool that you might like. +Please examine this simple example that install apache2 and generate index.html from the template +"playbooks/roles/simple_apache_role/templates/index.html" + +```bash +$ source environment.sh +$ # Now we would run the above playbook with roles +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_role.yml --tags apache2 +``` + + #### Jinja2 CLI You can use the jinja in the CLI too ```bash -- cgit v1.2.3 From 986813057bf9cee39100a0ca71fcebf82079aab9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:40:25 +0100 Subject: update --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index a35bcf82..b6eeb8a6 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -385,7 +385,7 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` -[Read More] +[Read More](http://docs.ansible.com/ansible/latest/playbooks_filters.html) ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. -- cgit v1.2.3 From 7c5e5e67f60c1d8a450339e2477d66999762828d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:47:54 +0100 Subject: update --- ansible.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b6eeb8a6..f4f504ec 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -408,7 +408,7 @@ $ export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file $ ansible-playbook playbooks/vault_example.yml - # decrypt the file + # encrypt the file $ ansible-vault encrypt path/somefile # view the file @@ -428,13 +428,15 @@ You might like to know, that you can build your inventory dynamically. You do not need to invent the wheel - there are plenty ready to use inventory script for most popular Cloud provicers and a lot of in-house popular usecaseses. +[AWS example](http://docs.ansible.com/ansible/latest/intro_dynamic_inventory.html#example-aws-ec2-external-inventory-script) + ```bash -$ etc/inv/ec2.py --refresh +$ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` -Read also about `dynamic inventory` below +[Read more](http://docs.ansible.com/ansible/latest/intro_dynamic_inventory.html) ### ansible profiling - callback It is ok that your playbook executes some time. Sometimes you may like to speed things up -- cgit v1.2.3 From 0c6ac5e17b26978fff44fd79457b41d1482c4b45 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:49:37 +0100 Subject: update --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index f4f504ec..3134bf83 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -439,7 +439,7 @@ $ ansible -m ping all -i etc/inv/ec2.py [Read more](http://docs.ansible.com/ansible/latest/intro_dynamic_inventory.html) ### ansible profiling - callback -It is ok that your playbook executes some time. Sometimes you may like to speed things up +Playbook execution takes some time. It is OK. First make it run, then you may like to speed things up Since ansible 2.x there is bouilt-in callback for task execution profiling -- cgit v1.2.3 From 275c6eb59f3af0993314bfd2d090cfef724da569 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:51:14 +0100 Subject: update --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 3134bf83..82e3f946 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -441,7 +441,7 @@ $ ansible -m ping all -i etc/inv/ec2.py ### ansible profiling - callback Playbook execution takes some time. It is OK. First make it run, then you may like to speed things up -Since ansible 2.x there is bouilt-in callback for task execution profiling +Since ansible 2.x there is built-in callback for task execution profiling ``` vi ansible.cfg @@ -467,7 +467,7 @@ fact_caching_timeout = 86400 ``` I like to use `jsonfile` as my backend. It allows to use another project -`ansible-cmdb` [github] that generates a HTML page of your inventory resources. A nice 'free' addition! +`ansible-cmdb` [github](https://github.com/fboender/ansible-cmdb) that generates a HTML page of your inventory resources. A nice 'free' addition! ### debugging ansible When your job fails - it is good to be effective with debugging. -- cgit v1.2.3 From 2e7311c4252ff13e4c604c28110418e92ab0ee75 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:54:39 +0100 Subject: update --- ansible.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 82e3f946..0f349c30 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -467,15 +467,18 @@ fact_caching_timeout = 86400 ``` I like to use `jsonfile` as my backend. It allows to use another project -`ansible-cmdb` [github](https://github.com/fboender/ansible-cmdb) that generates a HTML page of your inventory resources. A nice 'free' addition! +`ansible-cmdb` [(project on github)](https://github.com/fboender/ansible-cmdb) that generates a HTML page of your inventory resources. A nice 'free' addition! -### debugging ansible +### debugging ansible [chapter in progres] When your job fails - it is good to be effective with debugging. 1. Increase verbosiy by using multiple -v **[ -vvvvv]** -2. If variable is undefined +2. If variable is undefined + - grep -R path_of_your_inventory -e missing_variable 3. If variable (dictionary or a list) is undefined + - grep -R path_of_your_inventory -e missing_variable 4. Jinja template debug +5. Strange behaviour - try to run the code 'at the destination' ### Infrastructure as a code - what about Ansible You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. -- cgit v1.2.3 From 4cb6d9179414541ddcdba04044f38851ac4c4fba Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:58:35 +0100 Subject: update --- ansible.html.markdown | 38 ++------------------------------------ 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 0f349c30..ab77e5f4 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -23,7 +23,7 @@ $ pip install ansible $ apt-get install ansible ``` -* Appendix A - How do I install ansible +* [Appendix A - How do I install ansible](#infrastructure-as-a-code) * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) ### Your first ansible command (shell execution) @@ -480,7 +480,7 @@ When your job fails - it is good to be effective with debugging. 4. Jinja template debug 5. Strange behaviour - try to run the code 'at the destination' -### Infrastructure as a code - what about Ansible +### Infrastructure as a code You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! @@ -499,30 +499,6 @@ $ source environment.1.9.sh # please note that you have both venv1.9 and venv2 present - you need to (de)activate one - that is all ``` -### Naming - -### Bonus - -### writing own module - -### Python API - -### Web-UI: Ansible Tower, Jenkins, Rundeck - -#### Ansible Tower -Ansible provides a Web User Interface called `Ansible Tower`. -It is a convienient way to run Ansible Playbooks, have proper user management, log retention, and cron (periodic jobs). - -Personaly I'm not a fan of it - it's to expensive for my cases, and the trial is 10 inventory-hosts only. - -For my usecases I hide the 'pure ansible' commands behind other projects. - -#### Rundeck -This is nice, secure interface, that allows you to execute a jobs of your choice (CLI, script, execution plan). -It can perform roling-deployment (without Ansible), can integrate with clouds, etc. - -#### Jenkins -For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into 'pipelines'. #### become-user, become @@ -608,13 +584,3 @@ On the other hand - in advanced scope - you can use python anible code as a libr But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! - - - -# JM inventory dynamic aws ec2 -# vault -# roles - -#### ansible - dynamic in AWS -#### create instance in AWS -#### create env in AWS -- cgit v1.2.3 From 9a524f4cd1d2df67a727b0599504fd852d12c4a6 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 21:59:42 +0100 Subject: update --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ab77e5f4..8a48076e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -389,7 +389,7 @@ Junja is powerfull. It has built-in many usefull functions. ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. - Ansible provides a way to encrypt the poufne files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. + Ansible provides a way to encrypt the confidential files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. The best way to use the **ansible-vault** is to store the secret in some secure location, and configure ansible to use during runtime. @@ -481,7 +481,7 @@ When your job fails - it is good to be effective with debugging. 5. Strange behaviour - try to run the code 'at the destination' ### Infrastructure as a code -You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. +You already know, that ansible-vault allow you to store your confidential data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! ```bash -- cgit v1.2.3 From 485db56931ea13d7be17a08aa0e97ba32228afb9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:03:48 +0100 Subject: update --- ansible.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 8a48076e..76d03ede 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -482,7 +482,7 @@ When your job fails - it is good to be effective with debugging. ### Infrastructure as a code You already know, that ansible-vault allow you to store your confidential data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. -See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! +See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additional benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. What is more, you can have multiple versions of Ansible present in the same time. This is very helpfull! ```bash # recreate ansible 2.x venv @@ -501,6 +501,9 @@ $ source environment.1.9.sh ``` #### become-user, become +In Ansible - to become `sudo` - use the `become` parameter. Use `become_user` to specify the username. + +[Read more](http://docs.ansible.com/ansible/latest/become.html) ## Tips and tricks -- cgit v1.2.3 From 2d596b6c4f1eda1bdf906c84110da5c84ce69e39 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:07:51 +0100 Subject: update --- ansible.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 76d03ede..b83fb0c1 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -502,6 +502,14 @@ $ source environment.1.9.sh #### become-user, become In Ansible - to become `sudo` - use the `become` parameter. Use `become_user` to specify the username. +``` +- name: Ensure the httpd service is running + service: + name: httpd + state: started + become: true +``` +Note: You may like to execute Ansible with `--ask-sudo-pass` or add the user to sudoers file in order to allow non-supervised execution if you require 'admin' privilages. [Read more](http://docs.ansible.com/ansible/latest/become.html) -- cgit v1.2.3 From 03060af4f717a4ebdd80236329d24da3a439c223 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:10:59 +0100 Subject: update --- ansible.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b83fb0c1..891f20ac 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -538,14 +538,14 @@ ansible -m ping web*:!backend:monitoring:&allow_change #### Tagging You should tag some (not all) objects - a task in a playbook, all tasks included form a role, etc. -It allwos you to execute the choosen parts of the playbook. +It allows you to execute the choosen parts of the playbook. #### no_logs: True You may see, that some roles print a lot of output in verbose mode. There is also a debug module. This is the place where credentials may leak. Use `no_log` to hide the output. #### Debug module -allows to print a value to the screen +allows to print a value to the screen - use it! #### Register the output of a task You can register the output (stdout), rc (return code), stderr of a task with the `register` command. @@ -554,6 +554,8 @@ You can register the output (stdout), rc (return code), stderr of a task with th #### Loop: with, with_items, with_dict, with_together +[Read more](http://docs.ansible.com/ansible/latest/playbooks_conditionals.html) + ## Introduction Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -- cgit v1.2.3 From 8c681ba025b9b3b68ef802a3a85c7d7a082e1b99 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:14:27 +0100 Subject: update --- ansible.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 891f20ac..ece6087e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -570,20 +570,20 @@ Ansible have great integration with multiple operating systems (even Windows) an ### Cons -It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) -Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - + It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. + It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) + Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. + ### Pros -It is an agent-less tools In most scenarios, it use ssh as a transport layer. -In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' -I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) -Documentation is at the world-class standard! -The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. + It is an agent-less tools In most scenarios, it use ssh as a transport layer. + In some way you can use it as 'bash on steroids'. + It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' + I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! + It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) + Documentation is at the world-class standard! + The comunity (github, stackOverflow) would help you very fast. + Writing own modules and extension is fairly easy. ### Neutral -- cgit v1.2.3 From 2ba076f0b0e33b8e5520a28a3a66ea623e1f2034 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:18:10 +0100 Subject: update --- ansible.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ece6087e..421b5b59 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -570,20 +570,20 @@ Ansible have great integration with multiple operating systems (even Windows) an ### Cons - It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. - It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) - Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. + ### Pros - It is an agent-less tools In most scenarios, it use ssh as a transport layer. - In some way you can use it as 'bash on steroids'. - It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' - I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! - It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) - Documentation is at the world-class standard! - The comunity (github, stackOverflow) would help you very fast. - Writing own modules and extension is fairly easy. +It is an agent-less tools In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. ### Neutral @@ -591,9 +591,9 @@ Migration Ansible<->Salt is failrly easy - so if you would need an event-driven ## Basics on ansible -Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! -- cgit v1.2.3 From e6036b20527c96e0db5a78d17a8e9029bd76a656 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:21:33 +0100 Subject: update --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 421b5b59..ffd7f244 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -14,6 +14,7 @@ filename: LearnAnsible.txt ``` + ## Installation ```bash # Universal way @@ -571,7 +572,7 @@ Ansible have great integration with multiple operating systems (even Windows) an ### Cons It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism that would warn you about some change automatically (this can be achieved with reasonable effort) Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. ### Pros -- cgit v1.2.3 From 487db1817eead3fe38887e96038606980ad671e8 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Mon, 1 Jan 2018 22:29:17 +0100 Subject: update --- ansible.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ffd7f244..74195222 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -566,35 +566,35 @@ Of course the rabit hole is way deeper.' Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMMUNITY! and great support by developers! -## Main cons and pros -### Cons +### Main cons and pros + +#### Cons It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism that would warn you about some change automatically (this can be achieved with reasonable effort) Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. -### Pros +#### Pros It is an agent-less tools In most scenarios, it use ssh as a transport layer. In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +It is very-very-very easy to start. If you are familiar with ssh concept - you already know Ansible (ALMOST). My personal record is: 'I did show "how to install and use ansible" (for simple raspberry pi cluster management) - it took me 30 seconds to deliver a complete working example !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +It executes 'as is' - other tools (salt, puppet, chef - might execute in different scenario than you would expect) Documentation is at the world-class standard! The comunity (github, stackOverflow) would help you very fast. Writing own modules and extension is fairly easy. - -### Neutral +#### Neutral Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. -## Basics on ansible +#### Some concepts Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +The simplest way is to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can wrap Ansible (use python Ansible code as a library) with your own Python scrips! This is awesome! It would act a bit like Fabric then. -But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! -- cgit v1.2.3 From f39df1da097f8718b375127ad04f2114c5c4e48d Mon Sep 17 00:00:00 2001 From: Martin Nicholson Date: Tue, 16 Jan 2018 15:27:30 +0000 Subject: Added second substring example --- bash.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 0c097c27..ed4fa54f 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -16,6 +16,7 @@ contributors: - ["Betsy Lorton", "https://github.com/schbetsy"] - ["John Detter", "https://github.com/jdetter"] - ["Harry Mumford-Turner", "https://github.com/harrymt"] + - ["Martin Nicholson", "https://github.com/mn113"] filename: LearnBash.sh --- @@ -76,6 +77,8 @@ echo ${Variable/Some/A} # => A string Length=7 echo ${Variable:0:Length} # => Some st # This will return only the first 7 characters of the value +echo ${Variable: -Length} +# This will return the last 7 characters (note the space before -Length) # Default value for variable echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} -- cgit v1.2.3 From 462f94b967d4814e57bb6836cfd9d13abd8f9ab7 Mon Sep 17 00:00:00 2001 From: Martin Nicholson Date: Tue, 16 Jan 2018 15:31:32 +0000 Subject: Added string length example --- bash.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index ed4fa54f..fa3c5ebe 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -77,8 +77,11 @@ echo ${Variable/Some/A} # => A string Length=7 echo ${Variable:0:Length} # => Some st # This will return only the first 7 characters of the value -echo ${Variable: -Length} -# This will return the last 7 characters (note the space before -Length) +echo ${Variable: -5} # => tring +# This will return the last 5 characters (note the space before -5) + +# String length +echo ${#Variable} # => 11 # Default value for variable echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} -- cgit v1.2.3 From 8d2055483e8c0a8147414f4695a7cf3e5ede819e Mon Sep 17 00:00:00 2001 From: Martin Nicholson Date: Tue, 16 Jan 2018 16:03:13 +0000 Subject: Added section for =~ operator --- bash.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index fa3c5ebe..354042ec 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -161,6 +161,16 @@ then echo "This will run if $Name is Daniya OR Zach." fi +# There is also the =~ operator, which tests a string against a Regex pattern: +Email=me@example.com +if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]] +then + echo "Valid email!" +fi +# Note that =~ only works within double [[ ]] square brackets, +# which are subtly different from single [ ]. +# See the appropriate [manual section](http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs) for more on this. + # Expressions are denoted with the following format: echo $(( 10 + 5 )) # => 15 -- cgit v1.2.3 From e2949649f054ca069e95a05b04d99bccc30ba45d Mon Sep 17 00:00:00 2001 From: Martin Nicholson Date: Tue, 16 Jan 2018 16:09:49 +0000 Subject: Un-markdown-ify link --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index 354042ec..8f141673 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -169,7 +169,7 @@ then fi # Note that =~ only works within double [[ ]] square brackets, # which are subtly different from single [ ]. -# See the appropriate [manual section](http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs) for more on this. +# See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this. # Expressions are denoted with the following format: echo $(( 10 + 5 )) # => 15 -- cgit v1.2.3 From df4f61476c19ee35721ea078954618ed519a713a Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 1 Mar 2018 22:56:33 +0100 Subject: Delete .ansible.html.markdown.swl --- .ansible.html.markdown.swl | Bin 36864 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .ansible.html.markdown.swl diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl deleted file mode 100644 index 259fc5a0..00000000 Binary files a/.ansible.html.markdown.swl and /dev/null differ -- cgit v1.2.3 From 4427b4a70b43d1fd7e902ffe54eaf6cf752ab82a Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 1 Mar 2018 22:56:43 +0100 Subject: Delete .ansible.html.markdown.swm --- .ansible.html.markdown.swm | Bin 32768 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .ansible.html.markdown.swm diff --git a/.ansible.html.markdown.swm b/.ansible.html.markdown.swm deleted file mode 100644 index ff91c7a0..00000000 Binary files a/.ansible.html.markdown.swm and /dev/null differ -- cgit v1.2.3 From 81666159b4358be0a4c9e767256725529a0e3b35 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 1 Mar 2018 22:56:54 +0100 Subject: Delete .ansible.html.markdown.swn --- .ansible.html.markdown.swn | Bin 61440 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .ansible.html.markdown.swn diff --git a/.ansible.html.markdown.swn b/.ansible.html.markdown.swn deleted file mode 100644 index 25fce1a6..00000000 Binary files a/.ansible.html.markdown.swn and /dev/null differ -- cgit v1.2.3 From 3743c596d8a6519d21e11dfa161aed4a92a742bc Mon Sep 17 00:00:00 2001 From: Thales Mello Date: Thu, 8 Mar 2018 18:03:32 -0300 Subject: Improvements to syntax and comments Improve code by using context managers to handle closing of files. Also, replace the flame-war indexing comment for one with some explanations to why things are as they are. --- pythonstatcomp.html.markdown | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 6dde1cf0..0e6f1f87 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -38,18 +38,16 @@ r.text # raw page source print(r.text) # prettily formatted # save the page source in a file: os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html", "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open("learnxinyminutes.html", "wb") as f: + f.write(r.text.encode("UTF-8")) # downloading a csv fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" fn = "pets.csv" r = requests.get(fp + fn) print(r.text) -f = open(fn, "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open(fn, "wb") as f: + f.write(r.text.encode("UTF-8")) """ for more on the requests module, including APIs, see http://docs.python-requests.org/en/latest/user/quickstart/ @@ -71,8 +69,8 @@ pets # 1 vesuvius 6 23 fish # 2 rex 5 34 dog -""" R users: note that Python, like most normal programming languages, starts - indexing from 0. R is the unusual one for starting from 1. +""" R users: note that Python, like most C-influenced programming languages, starts + indexing from 0. R starts indexing at 1 due to Fortran influnce. """ # two different ways to print out a column -- cgit v1.2.3 From bb18dc81548a68b25227306bead977d55da23c66 Mon Sep 17 00:00:00 2001 From: Thales Mello Date: Fri, 9 Mar 2018 14:29:43 -0300 Subject: Update pythonstatcomp.html.markdown --- pythonstatcomp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 0e6f1f87..082c7025 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -70,7 +70,7 @@ pets # 2 rex 5 34 dog """ R users: note that Python, like most C-influenced programming languages, starts - indexing from 0. R starts indexing at 1 due to Fortran influnce. + indexing from 0. R starts indexing at 1 due to Fortran influence. """ # two different ways to print out a column -- cgit v1.2.3 From 6be6c9ba7eaa4fb97d4eb72ccff56fc81f53c998 Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Fri, 6 Apr 2018 13:14:31 +0800 Subject: Added Malay translation for clojure macros --- ms-my/clojure-macros-my.html.markdown | 154 ++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 ms-my/clojure-macros-my.html.markdown diff --git a/ms-my/clojure-macros-my.html.markdown b/ms-my/clojure-macros-my.html.markdown new file mode 100644 index 00000000..099f376e --- /dev/null +++ b/ms-my/clojure-macros-my.html.markdown @@ -0,0 +1,154 @@ +--- +language: "clojure macros" +filename: learnclojuremacros-ms.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +--- + +Sama seperti Lisp yang lain, sifat Clojure yang mempunyai [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +membolehkan anda untuk menggunakan sepenuhnya language ini untuk menulis code yang boleh generate code sendiri yang +dipanggil "macro". Macro memberi cara yang sangat menarik untuk mengubahsuai language mengikut kehendak anda. + +Jaga-jaga. Penggunaan macro boleh dikatakan tidak elok jika digunakan secara berlebihan jika function sahaja sudah mencukupi. +Gunakan macro hanya apabila anda mahu lebih kawalan terhadap sesuatu form. + +Biasakan diri dengan Clojure terlebih dahulu. Pastikan anda memahami semuanya di +[Clojure in Y Minutes](/docs/ms-my/clojure-my/). + +```clojure +;; Define macro menggunakan defmacro. Macro anda akan output list yang boleh +;; dijalankan sebagai code clojure. +;; +;; Macro ini adalah sama seperti (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Lihat hasil macro tersebut menggunakan macroexpand atau macroexpand-1. +;; +;; Pastikan panggilan kepada macro tersebut mempunyai tanda petikan +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; Anda boleh menggunakan eval terus kepada macroexpand untuk mendapatkan hasil: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Tetapi anda sepatutnya menggunakan cara yang lebih ringkas, sama seperti panggilan kepada function: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Anda boleh memudahkan cara untuk membuat macro dengan mengguna tanda petikan +;; untuk membuat list untuk macro: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Perhatikan yang reverse bukan lagi function tetapi adalah simbol. + +;; Macro boleh mengambil argument. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Tetapi jika anda membuat cara yang sama menggunakan tanda petikan, anda akan mendapat error sebab +;; argument tersebut juga akan mempunyai tanda petikan. Untuk mengatasi masalah ini, Clojure memberi +;; cara untuk meletak tanda petikan untuk macro: `. Di dalam `, anda boleh menggunakan ~ untuk mendapatkan scope luaran +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Anda boleh menggunakan destructuring untuk argument seperti biasa. Gunakan ~@ untuk mengembangkan variable +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Jangan lupa do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) mengembalikan body jika argument yang pertama adalah false. +;; Jika tidak, (unless) akan memulangkan nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Jika tidak berhati-hati, macro boleh memeningkan anda dengan mencampuradukkan nama variable +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; Untuk mengelakkan masalah ini, gunakan gensym untuk mendapatkan identifier yang berbeza +(gensym 'x) ; -> x1281 (atau yang sama waktu dengannya) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Anda boleh menggunakan # di dalam ` untuk menghasilkan gensym untuk setiap simbol secara automatik +(defmacro define-x-hygienically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygienically) ; -> (2) +(list x) ; -> (4) + +;; Kebiasaannya helper function digunakan untuk membuat macro. Jom buat beberapa function untuk +;; membuatkan program boleh memahami inline arithmetic. Saja suka-suka. +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Diberi argument [x (+ y)], pulangkan (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Kita boleh test terlebih dahulu tanpa membuat macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Tetapi, kita perlu membuat macro jika kita mahu jalankan code tersebut +(defmacro inline-2 [form] + (inline-2-helper form)) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (sepatutnya, 3N, sebab nombor tersebut ditukarkan kepada pecahan rasional menggunakan /) +``` + +### Bacaaan Lanjut + +Writing Macros daripada [Clojure for the Brave and True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Dokumen rasmi +[http://clojure.org/macros](http://clojure.org/macros) + +Bila perlu guna macro? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) -- cgit v1.2.3 From baf637514363d208cb2eddf159135a51ca3ae33c Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Fri, 6 Apr 2018 19:17:07 +0800 Subject: Added Malay translation for Common Lisp --- ms-my/common-lisp-my.html.markdown | 692 +++++++++++++++++++++++++++++++++++++ 1 file changed, 692 insertions(+) create mode 100644 ms-my/common-lisp-my.html.markdown diff --git a/ms-my/common-lisp-my.html.markdown b/ms-my/common-lisp-my.html.markdown new file mode 100644 index 00000000..f5914aae --- /dev/null +++ b/ms-my/common-lisp-my.html.markdown @@ -0,0 +1,692 @@ +--- + +language: "Common Lisp" +filename: commonlisp-ms.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +--- + +Common Lisp ialah programming language yang general-purpose (boleh digunakan untuk semua benda) dan multi-paradigm (konsep yang pelbagai) sesuai untuk pelbagai kegunaan di dalam +industri aplikasi. Common Lisp biasa digelar sebagai programmable programming language (programming language yang boleh di-program-kan). + +Sumber bacaan yang klasik ialah [Practical Common Lisp](http://www.gigamonkeys.com/book/). Sumber bacaan yang lain dan +yang terbaru ialah [Land of Lisp](http://landoflisp.com/). Buku baru mengenai best practices (amalan terbaik), +[Common Lisp Recipes](http://weitz.de/cl-recipes/), baru sahaja diterbitkan. + + + +```common-lisp + +;;;----------------------------------------------------------------------------- +;;; 0. Syntax +;;;----------------------------------------------------------------------------- + +;;; General form (Bentuk umum) + +;;; Ada dua asas dalam syntax CL: ATOM dan S-EXPRESSION. +;;; Kebiasaannya, gabungan S-expression dipanggil sebagai `forms`. + +10 ; atom; bermaksud seperti yang ditulis iaitu nombor 10 +:thing ; juga atom; bermaksud simbol :thing +t ; juga atom, bermaksud true (ya/betul/benar) +(+ 1 2 3 4) ; s-expression +'(4 :foo t) ; juga s-expression + + +;;; Comment (Komen) + +;;; Comment satu baris bermula dengan semicolon; gunakan empat untuk comment +;;; mengenai file, tiga untuk seksyen penghuraian, dua untuk yang dalam definition, +;;; dan satu untuk satu baris. Sebagai contoh, + +;;;; life.lisp + +;;; Foo bar baz, disebabkan quu quux. Sangat optimum untuk krakaboom dan umph. +;;; Diperlukan oleh function LINULUKO. Ini merepek sahaja kebaboom. + +(defun meaning (life) + "Memulangkan hasil pengiraan makna KEHIDUPAN" + (let ((meh "abc")) + ;; Jalankan krakaboom + (loop :for x :across meh + :collect x))) ; Simpan hasil ke x, kemudian pulangkan + +;;; Komen berbentuk blok, sebaliknya, membenarkan komen untuk bentuk bebas. Komen +;;; tersebut berada di antara #| dan |# + +#| Ini adalah komen berbentuk blok di mana + tulisan boleh ditulis dalam beberapa baris dan + #| + juga boleh dalam bentuk nested (berlapis-lapis)! + |# +|# + + +;;; Environment (benda-benda yang diperlukan untuk program menggunakan Common Lisp) + +;;; Common Lisp ada banyak jenis; kebanyakannya mengikut standard. SBCL +;;; ialah titik permulaan yang baik. Quicklisp boleh digunakan untuk install +;;; library third party. + +;;; CL kebiasaannya digunakan dengan text editor dan Real Eval Print +;;; Loop (REPL) yang dilancarkan dengan serentak. REPL membolehkan kita menjelajah +;;; program secara interaktif semasa program tersebut sedang berjalan secara "live". + + +;;;----------------------------------------------------------------------------- +;;; 1. Datatype primitif dan operator +;;;----------------------------------------------------------------------------- + +;;; Simbol + +'foo ; => FOO Perhatikan simbol menjadi huruf besar secara automatik. + +;;; INTERN menjadikan string sebagai simbol secara manual. + +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + +;;; Nombor + +9999999999999999999999 ; integer +#b111 ; binary => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; ratio +#C(1 2) ; complex number + +;;; Function ditulis sebagai (f x y z ...) di mana f ialah function dan +;;; x, y, z, ... adalah argument. + +(+ 1 2) ; => 3 + +;;; Jika anda ingin membuat data sebagai data bukannya function, gunakan QUOTE +;;; untuk mengelakkan data tersebut daripada dikira oleh program + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; Singkatan untuk QUOTE ialah ' (tanda petikan) + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; Operasi arithmetic asas + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Boolean + +t ; true; semua nilai yang bukan NIL ialah true +nil ; false; termasuklah list yang kosong: () +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; Character + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; String ialah array character yang tidak berubah panjang + +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; backslash ialah escape character + +;;; String boleh digabungkan + +(concatenate 'string "Hello, " "world!") ; => "Hello, world!" + +;;; String boleh diperlakukan seperti urutan character + +(elt "Apple" 0) ; => #\A + +;;; FORMAT digunakan untuk output mengikut format, daripada penggubahan string +;;; yang simple sehinggalah loop dan conditional. Argument pertama untuk FORMAT +;;; menentukan ke mana string akan pergi. Jika NIL, FORMAT +;;; akan pulangkan string sebagai data string; jika T, FORMAT akan output +;;; ke standard output, biasanya di screen, kemudian pulangkan NIL. + +(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!" +(format t "~A, ~A!" "Hello" "world") ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 2. Variable +;;;----------------------------------------------------------------------------- + +;;; Anda boleh membuat variable global (dynamically scoped) menggunakan DEFVAR dan +;;; DEFPARAMETER. Nama variable boleh guna mana-mana character kecuali: ()",'`;#|\ + +;;; Beza antara DEFVAR dengan DEFPARAMETER ialah DEFVAR tidak akan ubah nilai +;;; variable jika dijalankan semula. Manakala DEFPARAMETER, akan mengubah nilai +;;; jika dijalankan semula. + +;;; Kebiasaannya, variable global diletakkan earmuff (asterisk) pada nama. + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;;; Anda juga boleh menggunakan character unicode. +(defparameter *AΛB* nil) + +;;; Variable yang tidak wujud boleh diakses tetapi akan menyebabkan undefined +;;; behavior. Jangan buat. + +;;; Anda boleh membuat local binding menggunakan LET. Dalam snippet berikut, `me` +;;; terikat dengan "dance with you" hanya dalam (let ...). LET mesti akan pulangkan +;;; nilai `form` yang paling terakhir. + +(let ((me "dance with you")) me) ; => "dance with you" + + +;;;-----------------------------------------------------------------------------; +;;; 3. Struct dan collection +;;;-----------------------------------------------------------------------------; + + +;;; Struct + +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T +(dog-name *rover*) ; => "rover" + +;;; DOG-P, MAKE-DOG, dan DOG-NAME semuanya dibuat oleh DEFSTRUCT secara automatik + + +;;; Pair + +;;; CONS membuat pair. CAR dan CDR pulangkan head (kepala) dan tail (ekor) CONS-pair. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + + +;;; List + +;;; List ialah data structure linked-list, dihasilkan daripada pair CONS dan +;;; berakhir dengan NIL (atau '()) menandakan akhirnya list tersebut + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; LIST ialah constructor untuk memudahkan penghasilan list + +(list 1 2 3) ; => '(1 2 3) + +;;; Apabila argument pertama untuk CONS ialah atom dan argument kedua ialah +;;; list, CONS akan pulangkan CONS-pair baru dengan argument pertama sebagai +;;; item pertama dan argument kedua sebagai CONS-pair yang lain + +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;;; Gunakan APPEND untuk menggabungkan list + +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Atau CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; List ialah type utama, jadi ada pelbagai function untuk mengendalikan +;;; list, contohnya: + +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => NIL +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vector + +;;; Vector ialah array yang tidak berubah panjang + +#(1 2 3) ; => #(1 2 3) + +;;; Gunakan CONCATENATE untuk menggabungkan vector + +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + + +;;; Array + +;;; Vector dan string adalah sejenis array. + +;;; 2D array + +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;;; Perhatian: nilai awal MAKE-ARRAY adalah bergantung kepada jenis Common Lisp. +;;; Untuk meletakkan nilai awal secara manual: + +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) + +;;; Untuk mengakses element di kedudukan 1, 1, 1: + +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 + + +;;; Adjustable vector (vector yang boleh berubah) + +;;; Adjustable vector mempunyai rupa yang sama dengan +;;; vector yang tidak berubah panjang. + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) + +;;; Tambah element baru + +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) + + +;;; Set hanyalah list: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; Tetapi, anda perlukan data structure yang lebih baik untuk digunakan dengan +;;; data set yang sangat banyak + +;;; Kamus dibuat menggunakan hash table. + +;;; Bina hash table + +(defparameter *m* (make-hash-table)) + +;;; Tetapkan nilai + +(setf (gethash 'a *m*) 1) + +;;; Baca nilai + +(gethash 'a *m*) ; => 1, T + +;;; CL boleh memulangkan beberapa nilai (multiple value). + +(values 1 2) ; => 1, 2 + +;;; dan boleh digunakan dengan MULTIPLE-VALUE-BIND untuk bind setiap nilai + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) + +;;; GETHASH antara contoh function yang memulangkan multiple value. Value +;;; pertama ialah nilai untuk key dalam hash table; jika key tidak +;;; jumpa GETHASH akan pulangkan NIL. + +;;; Value kedua menentukan sama ada key tersebut betul-betul wujud dalam hash +;;; table. Jika key tidak jumpa dalam table value tersebut ialah NIL. Cara ini +;;; membolehkan kita untuk periksa sama ada value untuk key ialah NIL. + +;;; Dapatkan value yang tidak wujud akan pulangkan nil + +(gethash 'd *m*) ;=> NIL, NIL + +;;; Anda boleh menentukan value default untuk key yang tidak wujud + +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;;; Jom lihat penggunaan multiple return value di dalam code. + +(multiple-value-bind (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + + +;;;----------------------------------------------------------------------------- +;;; 3. Function +;;;----------------------------------------------------------------------------- + +;;; Gunakan LAMBDA untuk membuat anonymous function. Function sentiasa memulangkan +;;; value untuk expression terakhir. + +(lambda () "Hello World") ; => # + +;;; Gunakan FUNCALL untuk memanggil anonymous function + +(funcall (lambda () "Hello World")) ; => "Hello World" +(funcall #'+ 1 2 3) ; => 6 + +;;; Panggilan kepada FUNCALL juga boleh terjadi apabila lambda tersebut ialah CAR +;;; (yang pertama) untuk list (yang tidak mempunyai tanda petikan) + +((lambda () "Hello World")) ; => "Hello World" +((lambda (val) val) "Hello World") ; => "Hello World" + +;;; FUNCALL digunakan apabila argument sudah diketahui. Jika tidak, gunakan APPLY + +(apply #'+ '(1 2 3)) ; => 6 +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;;; Untuk menamakan sebuah function, guna DEFUN + +(defun hello-world () "Hello World") +(hello-world) ; => "Hello World" + +;;; Simbol () di atas bermaksud list kepada argument + +(defun hello (name) (format nil "Hello, ~A" name)) +(hello "Steve") ; => "Hello, Steve" + +;;; Function boleh ada argument optional (tidak wajib); argument tersebut bernilai +;;; NIL secara default + +(defun hello (name &optional from) + (if from + (format t "Hello, ~A, from ~A" name from) + (format t "Hello, ~A" name))) + +(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas + +;;; Nilai default boleh ditetapkan untuk argument tersebut + +(defun hello (name &optional (from "The world")) + (format nil "Hello, ~A, from ~A" name from)) + +(hello "Steve") ; => Hello, Steve, from The world +(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas + +;;; Function juga mempunyai keyword argument untuk membolehkan argument diletakkan +;;; tidak mengikut kedudukan + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~A ~A, from ~A" honorific name from)) + +(generalized-greeter "Jim") +; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + + +;;;----------------------------------------------------------------------------- +;;; 4. Kesamaan +;;;----------------------------------------------------------------------------- + +;;; CL mempunyai sistem kesaksamaan yang canggih. Antaranya adalah seperti berikut. + +;;; Untuk nombor, guna `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL + +;;; Untuk identiti object (lebih kurang) guna EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL + +;;; untuk list, string, dan bit-vector, guna EQUAL +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 5. Control Flow +;;;----------------------------------------------------------------------------- + +;;; Conditional (syarat) + +(if t ; test expression + "this is true" ; then expression + "this is false") ; else expression +; => "this is true" + +;;; Dalam conditional, semua value yang bukan NIL ialah true + +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;;; Guna COND untuk meletakkan beberapa test +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;;; TYPECASE adalah seperti switch tetapi untuk data type value tersebut +(typecase 1 + (string :string) + (integer :int)) +; => :int + + +;;; Loop + +;;; Recursion + +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) + +(fact 5) ; => 120 + +;;; Iteration + +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) + +(fact 5) ; => 120 + +(loop :for x :across "abc" :collect x) +; => (#\a #\b #\c #\d) + +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 + + +;;;----------------------------------------------------------------------------- +;;; 6. Mutation +;;;----------------------------------------------------------------------------- + +;;; Guna SETF untuk meletakkan nilai baru untuk variable yang sedia ada. Ini sama +;;; seperti contoh hash table di atas. + +(let ((variable 10)) + (setf variable 2)) +; => 2 + +;;; Sebaik-baiknya kurangkan penggunaan destructive function dan elakkan +;;; mutation jika boleh. + + +;;;----------------------------------------------------------------------------- +;;; 7. Class dan object +;;;----------------------------------------------------------------------------- + +;;; Takde dah class untuk haiwan. Jom buat Human-Powered Mechanical +;;; Conveyances (Kenderaan Mekanikal Berkuasa Manusia). + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;;; Argument untuk DEFCLASS, mengikut susunan ialah: +;;; 1. nama class +;;; 2. list untuk superclass +;;; 3. list untuk slot +;;; 4. specifier optional (tidak wajib) + +;;; Apabile list untuk superclass tidak ditetapkan, list yang kosong bermaksud +;;; class standard-object. Ini *boleh* ditukar, kalau anda tahu apa yang anda buat. +;;; Baca Art of the Metaobject Protocol untuk maklumat lebih lanjut. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;;; Panggilan DESCRIBE kepada class HUMAN-POWERED-CONVEYANCE di REPL akan memberi: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;;; Perhatikan apa yang berlaku. CL memang direka sebagai sistem interaktif. + +;;; Untuk membuat method, jom kira berapa panjang lilitan untuk +;;; roda basikal menggunakan formula: C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;;; Nilai PI memang sudah ada dalam CL + +;;; Katakanlah kita ingin ambil tahu efficiency value (nilai keberkesanan) +;;; rower (pendayung) di dalam canoe (perahu) adalah berbentuk logarithmic. Ini +;;; boleh ditetapkan di dalam constructor/initializer. + +;;; Untuk initialize instance selepas CL sudah siap construct: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;;; Kemudian untuk construct sesebuah instance dan periksa purata efficiency... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;----------------------------------------------------------------------------- +;;; 8. Macro +;;;----------------------------------------------------------------------------- + +;;; Macro membolehkan anda untuk menambah syntax language. CL tidak ada +;;; WHILE loop, tetapi, kita boleh mencipta syntax ter. Jika kita buat menggunakan +;;; naluri, kita akan dapat: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym)) (done (gensym))) + `(tagbody + ,block-name + (unless ,condition + (go ,done)) + (progn + ,@body) + (go ,block-name) + ,done))) + +;;; Jom lihat versi yang lebih high-level: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;;; Namun, dengan compiler yang modern, cara ini tidak diperlukan; form LOOP +;;; compile sama sahaja dan juga mudah dibaca. + +;;; Perhatikan ``` digunakan, sama juga `,` dan `@`. ``` ialah operator jenis quote +;;; yang dipanggil quasiquote; operator tersebut membolehkan penggunaan `,` . +;;; `,` membolehkan variable "di-unquote-kan". @ mengembangkan list. + +;;; GENSYM membuat simbol unik yang pasti tidak wujud di tempat-tempat yang +;;; lain. Ini kerana macro dikembangkan semasa compile dan +;;; nama variable di dalam macro boleh bertembung dengan nama variable yang +;;; digunakan dalam code yang biasa. + +;;; Baca Practical Common Lisp dan On Lisp untuk maklumat lebih lanjut mengenai macro. +``` + + +## Bacaan lanjut + +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) + + +## Maklumat tambahan + +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) + + +## Kredit + +Terima kasih banyak diucapkan kepada ahli Scheme yang membuat permulaan yang sangat +bagus dan mudah untuk diguna pakai untuk Common Lisp. + +- [Paul Khuong](https://github.com/pkhuong) untuk review yang bagus. -- cgit v1.2.3 From 42cda056229f30031f22210e859d95aae8e59219 Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Sat, 7 Apr 2018 15:03:47 +0800 Subject: Add Malay translation for Elisp --- ms-my/elisp-my.html.markdown | 347 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 347 insertions(+) create mode 100644 ms-my/elisp-my.html.markdown diff --git a/ms-my/elisp-my.html.markdown b/ms-my/elisp-my.html.markdown new file mode 100644 index 00000000..73dff0f4 --- /dev/null +++ b/ms-my/elisp-my.html.markdown @@ -0,0 +1,347 @@ +--- +language: elisp +contributors: + - ["Bastien Guerry", "https://bzg.fr"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +filename: learn-emacs-lisp-ms.el +--- + +```scheme +;; Ini adalah pengenalan kepada Emacs Lisp dalam masa 15 minit (v0.2d) +;; +;; Mula-mula pastikan anda sudah membaca artikel daripada Peter Norvig ini: +;; http://norvig.com/21-days.html +;; +;; Kemudian install GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs (atau lihat arahan untuk distro anda) +;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; Maklumat lanjut boleh didapati di: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; Amaran penting: +;; +;; Tutorial ini tidak akan merosakkan komputer anda melainkan jika anda berasa +;; terlalu marah sehingga anda menghempap komputer anda ke lantai. Kalau begitu, +;; saya dengan ini tidak akan bertanggungjawab terhadap apa-apa. Berseronoklah ya! + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Buka Emacs. +;; +;; Tekan `q' untuk tutup mesej selamat datang. +;; +;; Sekarang lihat garis kelabu di bahagian bawah window: +;; +;; "*scratch*" ialah nama ruangan untuk anda edit. +;; Ruangan ini disebut sebagai "buffer". +;; +;; Buffer scratch ialah buffer yang default setiap kali Emacs dibuka. +;; Anda bukannya edit file: anda edit buffer yang kemudiannya +;; boleh save ke file. +;; +;; "Lisp interaction (interaksi)" merujuk kepada command yang wujud di sini. +;; +;; Emacs mempunyai beberapa command yang sedia ada dalam setiap buffer, +;; dan sesetengah command yang lain boleh didapati jika sesetengah mode +;; diaktifkan. Di sini kita menggunakan `lisp-interaction-mode', yang +;; mempunyai command untuk menjalankan dan mengendalikan code Elisp. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Semicolon akan menjadikan comment sepanjang baris tersebut. +;; +;; Program Elisp mengandungi symbolic expressions ("sexps"): +(+ 2 2) + +;; Symbolic expression di atas dibaca begini "Tambah 2 pada 2". + +;; Sexps dilitupi oleh parentheses, dan boleh dalam bentuk nested (parentheses +;; dalam parentheses): +(+ 2 (+ 1 1)) + +;; Symbolic expression mengandungi atom atau symbolic expression +;; yang lain. Untuk contoh di atas, 1 dan 2 ialah atom, +;; (+ 2 (+ 1 1)) dan (+ 1 1) ialah symbolic expression. + +;; Dengan menggunakan `lisp-interaction-mode', anda boleh evaluate +;; (mendapatkan hasil pengiraan) sexps. Letak cursor selepas parenthesis penutup +;; kemudian tekan control dan j ("C-j"). + +(+ 3 (+ 1 2)) +;; ^ cursor di sini +;; `C-j' => 6 + +;; `C-j' memasukkan jawapan pengiraan ke dalam buffer. + +;; `C-xC-e' memaparkan jawapan yang sama di bahagian bawah Emacs, +;; yang dipanggil "minibuffer". Secara umumnya kita akan menggunakan `C-xC-e', +;; sebab kita tidak mahu memenuhi buffer dengan teks yang tidak penting. + +;; `setq' menyimpan value ke dalam variable: +(setq my-name "Bastien") +;; `C-xC-e' => "Bastien" (terpapar di mini-buffer) + +;; `insert' akan memasukkan "Hello!" di tempat di mana cursor berada: +(insert "Hello!") +;; `C-xC-e' => "Hello!" + +;; Di atas, kita menggunakan `insert' dengan satu argument "Hello!", tetapi +;; kita boleh meletakkan beberapa argument -- di sini kita letak dua: + +(insert "Hello" " world!") +;; `C-xC-e' => "Hello world!" + +;; Anda boleh menggunakan variable selain string: +(insert "Hello, I am " my-name) +;; `C-xC-e' => "Hello, I am Bastien" + +;; Anda boleh menggabungkan sexps untuk membuat function: +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' => hello + +;; Anda boleh evaluate function: +(hello) +;; `C-xC-e' => Hello, I am Bastien + +;; Parentheses kosong di dalam function bermaksud function tersebut tidak +;; terima argument. Sekarang kita tukar function untuk menerima satu argument. +;; Di sini, argument tersebut dinamakan "name": + +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' => hello + +;; Sekarang panggil function tersebut dengan string "you" sebagai value +;; untuk argument: +(hello "you") +;; `C-xC-e' => "Hello you" + +;; Yay! + +;; Tarik nafas. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Sekarang tukar ke buffer baru dengan nama "*test*" di window yang lain: + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' +;; => [The screen has two windows and cursor is in the *test* buffer] + +;; Gerakkan mouse ke window atas dan klik kiri untuk pergi balik ke buffer scratch. +;; Cara lain adalah dengan menggunakan `C-xo' (i.e. tekan control-x kemudian +;; tekan o) untuk pergi ke window yang lain. + +;; Anda boleh menggabungkan beberapa sexps menggunakan `progn': +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' +;; => [The screen has two windows and cursor is in the *test* buffer] + +;; Mulai dari sekarang saya tidak akan beritahu anda untuk tekan `C-xC-e' lagi: +;; buat untuk setiap sexp yang akan datang. + +;; Pergi balik ke buffer *scratch* menggunakan mouse atau `C-xo'. + +;; Seelok-eloknya padam buffer tersebut: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; Atau pergi balik ke window lain: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; Anda boleh menetapkan value dengan local variable menggunakan `let': +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; Tidak perlu menggunakan `progn', sebab `let' juga menggabungkan +;; beberapa sexps. + +;; Jom format string: +(format "Hello %s!\n" "visitor") + +;; %s ialah tempat untuk meletakkan string, digantikan dengan "visitor". +;; \n ialah character untuk membuat baris baru. + +;; Jom tukar function kita menggunakan format: +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; Jom buat function lain menggunakan `let': +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; argument untuk function + your-name ; variable "Bastien" daripada let + )))) + +;; Kemudian evaluate: +(greeting "you") + +;; Sesetengah function adalah interaktif: +(read-from-minibuffer "Enter your name: ") + +;; Function tersebut akan memulangkan kembali apa yang anda masukkan ke prompt. + +;; Jom jadikan function `greeting' untuk prompt nama anda: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; argument untuk function + your-name ; variable daripada let, yang dimasukkan dari prompt + )))) + +(greeting "Bastien") + +;; Jom siapkan function dengan memaparkan result di window yang lain: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; Test function tersebut: +(greeting "Bastien") + +;; Tarik nafas. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Jom simpan senarai nama: +;; Jika anda ingin membuat list(senarai) data, guna ' untuk elak +;; daripada list tersebut evaluate. +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; Dapatkan elemen pertama daripada list menggunakan `car': +(car list-of-names) + +;; Dapatkan semua elemen kecuali yang pertama menggunakan `cdr': +(cdr list-of-names) + +;; Tambah elemen di awal list menggunakan `push': +(push "Stephanie" list-of-names) + +;; NOTA: `car' dan `cdr' tidak ubah suai list, tetapi `push' ya. +;; Perbezaan ini penting: sesetengah function tiada side-effects (kesan sampingan) +;; (seperti `car') dan yang lain ada side-effect (seperti `push'). + +;; Jom panggil `hello' untuk setiap elemen dalam `list-of-names': +(mapcar 'hello list-of-names) + +;; Tukar `greeting' supaya ucapkan hello kepada semua orang dalam `list-of-names': +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; Ingat lagi function `hello' di atas? Function tersebut mengambil satu +;; argument, iaitu nama. `mapcar' memanggil `hello', kemudian menggunakan setiap +;; nama dalam `list-of-names' sebagai argument untuk function `hello'. + +;; Sekarang kita susun sedikit untuk apa yang terpapar di buffer: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) akan pergi ke permulaan buffer. +;; (search-forward "Hello") akan mencari string "Hello". +;; (while x y) evaluate sexp(s) y selagi x masih pulangkan sesuatu. +;; Jika x pulangkan `nil', kita akan keluar daripada while loop. + +(replace-hello-by-bonjour) + +;; Anda akan dapat melihat semua "Hello" dalam buffer *test* +;; ditukarkan dengan "Bonjour". + +;; Anda juga akan dapat error: "Search failed: Hello". +;; +;; Bagi mengelakkan error tersebut, anda perlu beritahu `search-forward' sama ada +;; perlu berhenti mencari pada suatu ketika, dan sama ada perlu diam jika +;; tidak jumpa apa yang dicari: + +;; (search-forward "Hello" nil 't) selesai masalah: + +;; Argument `nil' cakap: carian tidak mengikut kedudukan. +;; Argument `'t' cakap: diam saja jika tidak jumpa apa yang dicari. + +;; Kita guna sexp ini di function berikut, barulah tidak keluar error: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; Ucap hello pada nama-nama dalam `list-of-names' + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; Ganti "Hello" dengan "Bonjour" + (while (search-forward "Hello" nil 't) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; Jom jadikan nama-nama tersebut bold: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil 't) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; Function ini memperkenalkan `re-search-forward': anda mencari menggunakan +;; pattern iaitu "regular expression", bukannya mencari string "Bonjour". + +;; Regular expression tersebut ialah "Bonjour \\(.+\\)!" dan dibaca begini: +;; string "Bonjour ", dan +;; kumpulan | ini ialah \\( ... \\) +;; mana-mana character | ini ialah . +;; yang boleh berulang | ini ialah + +;; dan string "!". + +;; Dah sedia? Test function tersebut! + +(boldify-names) + +;; `add-text-properties' tambah... ciri-ciri teks, seperti face. + +;; OK, kita sudah selesai. Selamat ber-hacking! + +;; Jika anda ingin tahu lebih mengenai variable atau function: +;; +;; C-h v a-variable RET +;; C-h f a-function RET +;; +;; Jika anda ingin membaca manual Emacs Lisp menggunakan Emacs: +;; +;; C-h i m elisp RET +;; +;; Jika ingin membaca pengenalan kepada Emacs Lisp secara online: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html +``` -- cgit v1.2.3 From 3f02799903c104631ccf778dabb30ba8b116b7bc Mon Sep 17 00:00:00 2001 From: Ben Quigley Date: Sun, 8 Apr 2018 13:44:35 -0400 Subject: Removed semicolons No semicolons needed in Python --- pythonstatcomp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 6dde1cf0..66eeb7ad 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -205,7 +205,7 @@ hre["DeathY"] = extractYear(hre.Death) hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) # simple scatterplot, no trend line, color represents dynasty -sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False) # use scipy to run a linear regression from scipy import stats @@ -222,7 +222,7 @@ rval**2 # 0.020363950027333586 pval # 0.34971812581498452 # use seaborn to make a scatterplot and plot the linear regression trend line -sns.lmplot("BirthY", "EstAge", data=hre); +sns.lmplot("BirthY", "EstAge", data=hre) """ For more information on seaborn, see - http://web.stanford.edu/~mwaskom/software/seaborn/ -- cgit v1.2.3 From 47f49bc28b4546ecbb114e43cdd7ab3378bc1913 Mon Sep 17 00:00:00 2001 From: Anton Alekseev Date: Tue, 10 Apr 2018 21:12:03 +0300 Subject: Fix dead link to style guide, mention Emacs mode --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a0f8cd40..6174286c 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -829,7 +829,6 @@ someContractAddress.callcode('function_name'); ## Additional resources - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices) -- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/) - [Browser-based Solidity Editor](https://remix.ethereum.org/) - [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) @@ -850,9 +849,10 @@ someContractAddress.callcode('function_name'); - [Hacking Distributed Blog](http://hackingdistributed.com/) ## Style -- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy +- [Solidity Style Guide](http://solidity.readthedocs.io/en/latest/style-guide.html): Ethereum's style guide is heavily derived from Python's [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide. ## Editors +- [Emacs Solidity Mode](https://github.com/ethereum/emacs-solidity) - [Vim Solidity](https://github.com/tomlion/vim-solidity) - Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) -- cgit v1.2.3 From a80844cac53e372b0f8b423dca90151d5adb0417 Mon Sep 17 00:00:00 2001 From: "Shawn M. Hanes" Date: Wed, 11 Apr 2018 17:55:04 -0400 Subject: [Java/en] Added Lambdas section. --- java.html.markdown | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index ab2be4a2..18a3b21a 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] + - ["Shawn M. Hanes", "https://github.com/smhanes15"] filename: LearnJava.java --- @@ -858,6 +859,108 @@ public class EnumTest { // The enum body can include methods and other fields. // You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// Getting Started with Lambda Expressions +// +// New to Java version 8 are lambda expressions. Lambdas are more commonly found +// in functional programming languages, which means they are methods which can +// be created without belonging to a class, passed around as if it were itself +// an object, and executed on demand. +// +// Final note, lambdas must implement a functional interface. A functional +// interface is one which has only a single abstract method declared. It can +// have any number of default methods. Lambda expressions can be used as an +// instance of that functional interface. Any interface meeting the requirements +// is treated as a functional interface. You can read more about interfaces +// above. +// +import java.util.Map; +import java.util.HashMap; +import java.util.function.*; +import java.security.SecureRandom; + +public class Lambdas { + public static void main(String[] args) { + // Lambda declaration syntax: + // -> + + // We will use this hashmap in our examples below. + Map planets = new HashMap<>(); + planets.put("Mercury", "87.969"); + planets.put("Venus", "224.7"); + planets.put("Earth", "365.2564"); + planets.put("Mars", "687"); + planets.put("Jupiter", "4,332.59"); + planets.put("Saturn", "10,759"); + planets.put("Uranus", "30,688.5"); + planets.put("Neptune", "60,182"); + + // Lambda with zero parameters using the Supplier functional interface + // from java.util.function.Supplier. The actual lambda expression is + // what comes after numPlanets =. + Supplier numPlanets = () -> Integer.toString(planets.size()); + System.out.format("Number of Planets: %s\n\n", numPlanets.get()); + + // Lambda with one parameter and using the Consumer functional interface + // from java.util.function.Consumer. This is because planets is a Map, + // which implements both Collection and Iterable. The forEach used here, + // found in Iterable, applies the lambda expression to each member of + // the Collection. The default implementation of forEach behaves as if: + /* + for (T t : this) + action.accept(t); + */ + + // The actual lambda expression is the parameter passed to forEach. + planets.keySet().forEach((p) -> System.out.format("%s\n", p)); + + // If you are only passing a single argument, then the above can also be + // written as (note absent parentheses around p): + planets.keySet().forEach(p -> System.out.format("%s\n", p)); + + // Tracing the above, we see that planets is a HashMap, keySet() returns + // a Set of its keys, forEach applies each element as the lambda + // expression of: (parameter p) -> System.out.format("%s\n", p). Each + // time, the element is said to be "consumed" and the statement(s) + // referred to in the lambda body is applied. Remember the lambda body + // is what comes after the ->. + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format("%s\n", planet); + } + + // This example differs from the above in that a different forEach + // implementation is used: the forEach found in the HashMap class + // implementing the Map interface. This forEach accepts a BiConsumer, + // which generically speaking is a fancy way of saying it handles + // the Set of each Key -> Value pairs. This default implementation + // behaves as if: + /* + for (Map.Entry entry : map.entrySet()) + action.accept(entry.getKey(), entry.getValue()); + */ + + // The actual lambda expression is the parameter passed to forEach. + String orbits = "%s orbits the Sun in %s Earth days.\n"; + planets.forEach((K, V) -> System.out.format(orbits, K, V)); + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format(orbits, planet, planets.get(planet)); + } + + // Or, if following more closely the specification provided by the + // default implementation: + for (Map.Entry planet : planets.entrySet()) { + System.out.format(orbits, planet.getKey(), planet.getValue()); + } + + // These examples cover only the very basic use of lambdas. It might not + // seem like much or even very useful, but remember that a lambda can be + // created as an object that can later be passed as parameters to other + // methods. + } +} ``` ## Further Reading -- cgit v1.2.3 From cc0329efbb5fb9330e6c79a40f8dd2967bda5931 Mon Sep 17 00:00:00 2001 From: "Shawn M. Hanes" Date: Wed, 11 Apr 2018 18:12:59 -0400 Subject: [Java/en] Added Lambdas section. --- java.html.markdown | 164 ++++++++++++++++++++++++++--------------------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 18a3b21a..ca0b04c2 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -11,7 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] - - ["Shawn M. Hanes", "https://github.com/smhanes15"] + - ["Shawn M. Hanes", "https://github.com/smhanes15"] filename: LearnJava.java --- @@ -879,87 +879,87 @@ import java.util.function.*; import java.security.SecureRandom; public class Lambdas { - public static void main(String[] args) { - // Lambda declaration syntax: - // -> - - // We will use this hashmap in our examples below. - Map planets = new HashMap<>(); - planets.put("Mercury", "87.969"); - planets.put("Venus", "224.7"); - planets.put("Earth", "365.2564"); - planets.put("Mars", "687"); - planets.put("Jupiter", "4,332.59"); - planets.put("Saturn", "10,759"); - planets.put("Uranus", "30,688.5"); - planets.put("Neptune", "60,182"); - - // Lambda with zero parameters using the Supplier functional interface - // from java.util.function.Supplier. The actual lambda expression is - // what comes after numPlanets =. - Supplier numPlanets = () -> Integer.toString(planets.size()); - System.out.format("Number of Planets: %s\n\n", numPlanets.get()); - - // Lambda with one parameter and using the Consumer functional interface - // from java.util.function.Consumer. This is because planets is a Map, - // which implements both Collection and Iterable. The forEach used here, - // found in Iterable, applies the lambda expression to each member of - // the Collection. The default implementation of forEach behaves as if: - /* - for (T t : this) - action.accept(t); - */ - - // The actual lambda expression is the parameter passed to forEach. - planets.keySet().forEach((p) -> System.out.format("%s\n", p)); - - // If you are only passing a single argument, then the above can also be - // written as (note absent parentheses around p): - planets.keySet().forEach(p -> System.out.format("%s\n", p)); - - // Tracing the above, we see that planets is a HashMap, keySet() returns - // a Set of its keys, forEach applies each element as the lambda - // expression of: (parameter p) -> System.out.format("%s\n", p). Each - // time, the element is said to be "consumed" and the statement(s) - // referred to in the lambda body is applied. Remember the lambda body - // is what comes after the ->. - - // The above without use of lambdas would look more traditionally like: - for (String planet : planets.keySet()) { - System.out.format("%s\n", planet); - } - - // This example differs from the above in that a different forEach - // implementation is used: the forEach found in the HashMap class - // implementing the Map interface. This forEach accepts a BiConsumer, - // which generically speaking is a fancy way of saying it handles - // the Set of each Key -> Value pairs. This default implementation - // behaves as if: - /* - for (Map.Entry entry : map.entrySet()) - action.accept(entry.getKey(), entry.getValue()); - */ - - // The actual lambda expression is the parameter passed to forEach. - String orbits = "%s orbits the Sun in %s Earth days.\n"; - planets.forEach((K, V) -> System.out.format(orbits, K, V)); - - // The above without use of lambdas would look more traditionally like: - for (String planet : planets.keySet()) { - System.out.format(orbits, planet, planets.get(planet)); - } - - // Or, if following more closely the specification provided by the - // default implementation: - for (Map.Entry planet : planets.entrySet()) { - System.out.format(orbits, planet.getKey(), planet.getValue()); - } - - // These examples cover only the very basic use of lambdas. It might not - // seem like much or even very useful, but remember that a lambda can be - // created as an object that can later be passed as parameters to other - // methods. - } + public static void main(String[] args) { + // Lambda declaration syntax: + // -> + + // We will use this hashmap in our examples below. + Map planets = new HashMap<>(); + planets.put("Mercury", "87.969"); + planets.put("Venus", "224.7"); + planets.put("Earth", "365.2564"); + planets.put("Mars", "687"); + planets.put("Jupiter", "4,332.59"); + planets.put("Saturn", "10,759"); + planets.put("Uranus", "30,688.5"); + planets.put("Neptune", "60,182"); + + // Lambda with zero parameters using the Supplier functional interface + // from java.util.function.Supplier. The actual lambda expression is + // what comes after numPlanets =. + Supplier numPlanets = () -> Integer.toString(planets.size()); + System.out.format("Number of Planets: %s\n\n", numPlanets.get()); + + // Lambda with one parameter and using the Consumer functional interface + // from java.util.function.Consumer. This is because planets is a Map, + // which implements both Collection and Iterable. The forEach used here, + // found in Iterable, applies the lambda expression to each member of + // the Collection. The default implementation of forEach behaves as if: + /* + for (T t : this) + action.accept(t); + */ + + // The actual lambda expression is the parameter passed to forEach. + planets.keySet().forEach((p) -> System.out.format("%s\n", p)); + + // If you are only passing a single argument, then the above can also be + // written as (note absent parentheses around p): + planets.keySet().forEach(p -> System.out.format("%s\n", p)); + + // Tracing the above, we see that planets is a HashMap, keySet() returns + // a Set of its keys, forEach applies each element as the lambda + // expression of: (parameter p) -> System.out.format("%s\n", p). Each + // time, the element is said to be "consumed" and the statement(s) + // referred to in the lambda body is applied. Remember the lambda body + // is what comes after the ->. + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format("%s\n", planet); + } + + // This example differs from the above in that a different forEach + // implementation is used: the forEach found in the HashMap class + // implementing the Map interface. This forEach accepts a BiConsumer, + // which generically speaking is a fancy way of saying it handles + // the Set of each Key -> Value pairs. This default implementation + // behaves as if: + /* + for (Map.Entry entry : map.entrySet()) + action.accept(entry.getKey(), entry.getValue()); + */ + + // The actual lambda expression is the parameter passed to forEach. + String orbits = "%s orbits the Sun in %s Earth days.\n"; + planets.forEach((K, V) -> System.out.format(orbits, K, V)); + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format(orbits, planet, planets.get(planet)); + } + + // Or, if following more closely the specification provided by the + // default implementation: + for (Map.Entry planet : planets.entrySet()) { + System.out.format(orbits, planet.getKey(), planet.getValue()); + } + + // These examples cover only the very basic use of lambdas. It might not + // seem like much or even very useful, but remember that a lambda can be + // created as an object that can later be passed as parameters to other + // methods. + } } ``` -- cgit v1.2.3 From 3fd6697c5eba4cb4fd6aff8ac58109d2cd79dbbb Mon Sep 17 00:00:00 2001 From: Michael Filonenko Date: Sun, 15 Apr 2018 20:46:42 +0300 Subject: Common Lisp: ru-ru --- ru-ru/common-lisp-ru.html.markdown | 704 +++++++++++++++++++++++++++++++++++++ 1 file changed, 704 insertions(+) create mode 100644 ru-ru/common-lisp-ru.html.markdown diff --git a/ru-ru/common-lisp-ru.html.markdown b/ru-ru/common-lisp-ru.html.markdown new file mode 100644 index 00000000..d5f9bf0e --- /dev/null +++ b/ru-ru/common-lisp-ru.html.markdown @@ -0,0 +1,704 @@ +--- + +language: "Common Lisp" +filename: commonlisp.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Michael Filonenko", "https://github.com/filonenko-mikhail"] +lang: ru-ru +--- + +Common Lisp - мультипарадигменный язык программирования общего назначения, подходящий для широкого +спектра задач. +Его частенько называют программируемым языком программирования. + +Идеальная отправная точка - книга [Common Lisp на практике (перевод)](http://lisper.ru/pcl/). +Ещё одна популярная книга [Land of Lisp](http://landoflisp.com/). +И одна из последних книг [Common Lisp Recipes](http://weitz.de/cl-recipes/) вобрала в себя лучшие +архитектурные решения на основе опыта коммерческой работки автора. + + + +```common-lisp + +;;;----------------------------------------------------------------------------- +;;; 0. Синтаксис +;;;----------------------------------------------------------------------------- + +;;; Основные формы + +;;; Существует два фундамента CL: АТОМ и S-выражение. +;;; Как правило, сгруппированные S-выражения называют `формами`. + +10 ; атом; вычисляется в самого себя +:thing ; другой атом; вычисляется в символ :thing +t ; ещё один атом, обозначает `истину` (true) +(+ 1 2 3 4) ; s-выражение +'(4 :foo t) ; ещё одно s-выражение + +;;; Комментарии + +;;; Однострочные комментарии начинаются точкой с запятой. Четыре знака подряд +;;; используют для комментария всего файла, три для раздела, два для текущего +;;; определения; один для текущей строки. Например: + +;;;; life.lisp + +;;; То-сё - пятое-десятое. Оптимизировано для максимального бадабума и ччччч. +;;; Требуется для функции PoschitatBenzinIsRossiiVBelarus + +(defun meaning (life) + "Возвращает смысл Жизни" + (let ((meh "abc")) + ;; Вызывает бадабум + (loop :for x :across meh + :collect x))) ; сохранить значения в x, и потом вернуть + +;;; А вот целый блок комментария можно использовать как угодно. +;;; Для него используются #| и |# + +#| Целый блок комментария, который размазан + на несколько строк + #| + которые могут быть вложенными! + |# +|# + +;;; Чем пользоваться + +;;; Существует несколько реализаций: и коммерческих, и открытых. +;;; Все они максимально соответствуют стандарту языка. +;;; SBCL, например, добротен. А за дополнительными библиотеками +;;; нужно ходить в Quicklisp + +;;; Обычно разработка ведется в текстовом редакторе с запущенным в цикле +;;; интерпретатором (в CL это Read Eval Print Loop). Этот цикл (REPL) +;;; позволяет интерактивно выполнять части программы вживую сразу наблюдая +;;; результат. + +;;;----------------------------------------------------------------------------- +;;; 1. Базовые типы и операторы +;;;----------------------------------------------------------------------------- + +;;; Символы + +'foo ; => FOO Символы автоматически приводятся к верхнему регистру. + +;;; INTERN создаёт символ из строки. + +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + +;;; Числа + +9999999999999999999999 ; целые +#b111 ; двоичные => 7 +#o111 ; восьмеричные => 73 +#x111 ; шестнадцатиричные => 273 +3.14159s0 ; с плавающей точкой +3.14159d0 ; с плавающей точкой с двойной точностью +1/2 ; рациональные) +#C(1 2) ; комплексные + +;;; Вызов функции пишется как s-выражение (f x y z ....), где f это функция, +;;; x, y, z, ... аругменты. + +(+ 1 2) ; => 3 + +;;; Если вы хотите просто представить код как данные, воспользуйтесь формой QUOTE +;;; Она не вычисляет аргументы, а возвращает их как есть. +;;; Она даёт начало метапрограммированию + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; QUOTE можно сокращенно записать знаком ' + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; Арифметические операции + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Булевые + +t ; истина; любое не-NIL значение `истинно` +nil ; ложь; а ещё пустой список () тоже `ложь` +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; Строковые символы + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; Строки это фиксированные массивы символов + +"Hello, world!" +"Тимур \"Каштан\" Бадтрудинов" ; экранировать двойную кавычку обратным слешом + +;;; Строки можно соединять + +(concatenate 'string "ПРивет, " "мир!") ; => "ПРивет, мир!" + +;;; Можно пройтись по строке как по массиву символов + +(elt "Apple" 0) ; => #\A + +;;; Для форматированного вывода используется FORMAT. Он умеет выводить, как просто значения, +;;; так и производить циклы и учитывать условия. Первый агрумент указывает куда отправить +;;; результат. Если NIL, FORMAT вернет результат как строку, если T результат отправиться +;;; консоль вывода а форма вернет NIL. + +(format nil "~A, ~A!" "Привет" "мир") ; => "Привет, мир!" +(format t "~A, ~A!" "Привет" "мир") ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 2. Переменные +;;;----------------------------------------------------------------------------- + +;;; С помощью DEFVAR и DEFPARAMETER вы можете создать глобальную (динамческой видимости) +;;; переменную. +;;; Имя переменной может состоять из любых символов кроме: ()",'`;#|\ + +;;; Разница между DEFVAR и DEFPARAMETER в том, что повторное выполнение DEFVAR +;;; переменную не поменяет. А вот DEFPARAMETER меняет переменную при каждом вызове. + +;;; Обычно глобальные (динамически видимые) переменные содержат звездочки в имени. + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;;; Можете использовать unicode. +(defparameter *КУКУ* nil) + +;;; Доступ к необъявленной переменной - это непредсказуемое поведение. Не делайте так. + +;;; С помощью LET можете сделать локальное связывание. +;;; В следующем куске кода, `я` связывается с "танцую с тобой" только +;;; внутри формы (let ...). LET всегда возвращает значение последней формы. + +(let ((я "танцую с тобой")) я) ; => "танцую с тобой" + + +;;;-----------------------------------------------------------------------------; +;;; 3. Структуры и коллекции +;;;-----------------------------------------------------------------------------; + + +;;; Структуры + +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T +(dog-name *rover*) ; => "rover" + +;;; DEFSTRUCT автоматически создала DOG-P, MAKE-DOG, и DOG-NAME + + +;;; Пары (cons-ячейки) + +;;; CONS создаёт пары. CAR и CDR возвращают начало и конец CONS-пары. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + + +;;; Списки + +;;; Списки это связанные CONS-пары, в конце самой последней из которых стоит NIL +;;; (или '() ). + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; Списки с произвольным количеством элементов удобно создавать с помощью LIST + +(list 1 2 3) ; => '(1 2 3) + +;;; Если первый аргумент для CONS это атом и второй аргумент список, CONS +;;; возвращает новую CONS-пару, которая представляет собой список + +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;;; Чтобы объединить списки, используйте APPEND + +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Или CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Списки это самый используемый элемент языка. Поэтому с ними можно делать +;;; многие вещи. Вот несколько примеров: + +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => NIL +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Вектора + +;;; Вектора заданные прямо в коде - это массивы с фиксированной длинной. + +#(1 2 3) ; => #(1 2 3) + +;;; Для соединения векторов используйте CONCATENATE + +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + + +;;; Массивы + +;;; И вектора и строки это подмножества массивов. + +;;; Двухмерные массивы + +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;;; Внимание: значение по-умолчанию элемента массива зависит от реализации. +;;; Лучше явно указывайте: + +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) + +;;; Для доступа к элементу в позиции 1, 1, 1: + +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 + + +;;; Вектора с изменяемой длиной + +;;; Вектора с изменяемой длиной при выводе на консоль выглядят также, +;;; как и вектора, с константной длиной + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) + +;;; Добавление новых элементов + +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) + + +;;; Множества, это просто списки: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; Несмотря на все, для действительно больших объемов данных, вам нужно что-то +;;; лучше, чем просто связанные списки + +;;; Словари представлены хеш таблицами. + +;;; Создание хеш таблицы: + +(defparameter *m* (make-hash-table)) + +;;; Установка пары ключ-значение + +(setf (gethash 'a *m*) 1) + +;;; Возврат значения по ключу + +(gethash 'a *m*) ; => 1, T + +;;; CL выражения умеют возвращать сразу несколько значений. + +(values 1 2) ; => 1, 2 + +;;; которые могут быть распределены по переменным с помощью MULTIPLE-VALUE-BIND + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) + +;;; GETHASH как раз та функция, которая возвращает несколько значений. Первое +;;; значение - это значение по ключу в хеш таблицу. Если ключ не был найден, +;;; возвращает NIL. + +;;; Второе возвращаемое значение, указывает был ли ключ в хеш таблице. Если ключа +;;; не было, то возвращает NIL. Таким образом можно проверить, это значение +;;; NIL, или ключа просто не было. + +;;; Вот возврат значений, в случае когда ключа в хеш таблице не было: + +(gethash 'd *m*) ;=> NIL, NIL + +;;; Можете задать значение по умолчанию. + +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;;; Давайте обработаем возврат несколько значений. + +(multiple-value-bind (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + + +;;;----------------------------------------------------------------------------- +;;; 3. Функции +;;;----------------------------------------------------------------------------- + +;;; Для создания анонимных функций используйте LAMBDA. Функций всегда возвращают +;;; значение последнего своего выражения. Как выглядит функция при выводе в консоль +;;; зависит от реализации. + +(lambda () "Привет Мир") ; => # + +;;; Для вызова анонимной функции пользуйтесь FUNCALL + +(funcall (lambda () "Привет Мир")) ; => "Привет мир" +(funcall #'+ 1 2 3) ; => 6 + +;;; FUNCALL сработает и тогда, когда анонимная функция стоит в начале +;;; неэкранированного списка + +((lambda () "Привет Мир")) ; => "Привет Мир" +((lambda (val) val) "Привет Мир") ; => "Привет Мир" + +;;; FUNCALL используется, когда аргументы заранее известны. +;;; В противном случае используйте APPLY + +(apply #'+ '(1 2 3)) ; => 6 +(apply (lambda () "Привет Мир") nil) ; => "Привет Мир" + +;;; Для обычной функции с именем используйте DEFUN + +(defun hello-world () "Привет Мир") +(hello-world) ; => "Привет Мир" + +;;; Выше видно пустой список (), это место для определения аргументов + +(defun hello (name) (format nil "Hello, ~A" name)) +(hello "Григорий") ; => "Привет, Григорий" + +;;; Можно указать необязательные аргументы. По умолчанию они будут NIL + +(defun hello (name &optional from) + (if from + (format t "Приветствие для ~A от ~A" name from) + (format t "Привет, ~A" name))) + +(hello "Георгия" "Василия") ; => Приветствие для Георгия от Василия + +;;; Можно явно задать значения по умолчанию + +(defun hello (name &optional (from "Мира")) + (format nil "Приветствие для ~A от ~A" name from)) + +(hello "Жоры") ; => Приветствие для Жоры от Мира +(hello "Жоры" "альпаки") ; => Приветствие для Жоры от альпаки + +;;; Можно также задать именованные параметры + +(defun generalized-greeter (name &key (from "Мира") (honorific "Господин")) + (format t "Здравствуйте, ~A ~A, от ~A" honorific name from)) + +(generalized-greeter "Григорий") +; => Здравствуйте, Господин Григорий, от Мира + +(generalized-greeter "Григорий" :from "альпаки" :honorific "гражданин") +; => Здравствуйте, Гражданин Григорий, от альпаки + + +;;;----------------------------------------------------------------------------- +;;; 4. Равенство или эквивалентность +;;;----------------------------------------------------------------------------- + +;;; У CL сложная система эквивалентности. Взглянем одним глазом. + +;;; Для чисел используйте `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL + +;;; Для идентичености объектов используйте EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL + +;;; Для списков, строк, и битовых векторов - EQUAL +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 5. Циклы и ветвления +;;;----------------------------------------------------------------------------- + +;;; Ветвления + +(if t ; проверямое значение + "случилась истина" ; если, оно было истинно + "случилась ложь") ; иначе, когда оно было ложно +; => "случилась истина" + +;;; В форме ветвления if, все не-NIL значения это `истина` + +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;;; COND это цепочка проверок для нахождения искомого +(cond ((> 2 2) (error "мимо!")) + ((< 2 2) (error "опять мимо!")) + (t 'ok)) ; => 'OK + +;;; TYPECASE выбирает ветку исходя из типа выражения +(typecase 1 + (string :string) + (integer :int)) +; => :int + + +;;; Циклы + +;;; С рекурсией + +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) + +(fact 5) ; => 120 + +;;; И без + +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) + +(fact 5) ; => 120 + +(loop :for x :across "abc" :collect x) +; => (#\a #\b #\c #\d) + +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 + + +;;;----------------------------------------------------------------------------- +;;; 6. Установка значений в переменные (и не только) +;;;----------------------------------------------------------------------------- + +;;; Для присвоения переменной нового значения используйте SETF. Это уже было +;;; при работе с хеш таблицами. + +(let ((variable 10)) + (setf variable 2)) +; => 2 + +;;; Для функционального подхода в программировании, старайтесь избегать измений +;;; в переменных. + +;;;----------------------------------------------------------------------------- +;;; 7. Классы и объекты +;;;----------------------------------------------------------------------------- + +;;; Никаких больше животных в примерах. Берем устройства приводимые в движение +;;; мускульной силой человека. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "Устройство движимое человеческой силой")) + +;;; Аргументы DEFCLASS: +;;; 1. Имя класса +;;; 2. Список родительских классов +;;; 3. Список полей +;;; 4. Необязательная метаинформация + +;;; Если родительские классы не заданы, используется "стандартный" класс +;;; Это можно *изменить*, но хорошенько подумайте прежде. Если все-таки +;;; решились вам поможет "Art of the Metaobject Protocol" + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;;; Если вызвать DESCRIBE для HUMAN-POWERED-CONVEYANCE то получите следующее: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;;; CL задизайнен как интерактивная система. В рантайме доступна информация о +;;; типе объектов. + +;;; Давайте посчитаем расстояние, которое пройдет велосипед за один оборот колеса +;;; по формуле C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;;; PI - это константа в CL + +;;; Предположим мы нашли, что критерий эффективности логарифмически связан +;;; с гребцами каноэ. Тогда вычисление можем сделать сразу при инициализации. + +;;; Инициализируем объект после его создания: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + + +;;; Давайте проверим что получилось с этой самой эффективностью... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;----------------------------------------------------------------------------- +;;; 8. Макросы +;;;----------------------------------------------------------------------------- + +;;; Макросы позволяют расширить синаксис языка. В CL нет например цикла WHILE, +;;; но его проще простого реализовать на макросах. Если мы отбросим наши +;;; ассемблерные (или алгольные) инстинкты, мы взлетим на крыльях: + +(defmacro while (condition &body body) + "Пока `условие` истинно, выполняется `тело`. +`Условие` проверяется перед каждым выполнением `тела`" + (let ((block-name (gensym)) (done (gensym))) + `(tagbody + ,block-name + (unless ,condition + (go ,done)) + (progn + ,@body) + (go ,block-name) + ,done))) + +;;; Взглянем на более высокоуровневую версию этого макроса: + +(defmacro while (condition &body body) + "Пока `условие` истинно, выполняется `тело`. +`Условие` проверяется перед каждым выполнением `тела`" + `(loop while ,condition + do + (progn + ,@body))) + +;;; В современных комиляторах LOOP так же эффективен как и приведенный +;;; выше код. Поэтому используйте его, его проще читать. + +;;; В макросах используются символы ```, `,` и `@`. ``` - это оператор +;;; квазиквотирования - это значит что форма исполнятся не будет, а вернется +;;; как данные. Оператаор `,` позволяет исполнить форму внутри +;;; квазиквотирования. Оператор `@` исполняет форму внутри квазиквотирования +;;; но полученный список вклеивает по месту. + +;;; GENSYM создаёт уникальный символ, который гарантировано больше нигде в +;;; системе не используется. Так надо потому, что макросы разворачиваются +;;; во время компиляции и переменные объявленные в макросе могут совпасть +;;; по имени с переменными в обычном коде. + +;;; Дальнйешую информацию о макросах ищите в книгах Practical Common Lisp +;;; и On Lisp +``` + +## Для чтения + +На русском +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) + +На английском +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) + + +## Дополнительная информация + +На русском + +- [Lisper.ru](http://lisper.ru/) + +На английском + +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) + + +## Благодарности в английской версии + +Спасибо людям из Scheme за отличную статью, взятую за основу для +Common Lisp. + + +- [Paul Khuong](https://github.com/pkhuong) за хорошую вычитку. -- cgit v1.2.3 From 50021745fa4cd0d5ad5a475f2b2f126fcc662767 Mon Sep 17 00:00:00 2001 From: erikarvstedt <36110478+erikarvstedt@users.noreply.github.com> Date: Mon, 7 May 2018 12:47:20 +0200 Subject: css: add selector groups --- css.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 3b378d44..64dc097c 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -135,6 +135,10 @@ selector::after {} .parent * { } /* all descendants */ .parent > * { } /* all children */ +/* Group any number of selectors to define styles that affect all selectors + in the group */ +selector1, selector2 { } + /* #################### ## PROPERTIES #################### */ -- cgit v1.2.3 From dc7adc32e349c290d2325b81fc773a3dc900b1b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Batuhan=20Osman=20Ta=C5=9Fkaya?= Date: Sat, 12 May 2018 06:12:43 +0300 Subject: Broken OOP Example Fixed -> class Insan(obje) converted class Insan(object) -> Undefined self.name variable replaced self.isim --- tr-tr/python3-tr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index e53d5568..b78d517f 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - - ["Andre Polykanine", "https://github.com/Oire"] + - ["Batuhan Osman T.", "https://github.com/BTaskaya"] translators: - ["Eray AYDIN", "http://erayaydin.me/"] lang: tr-tr @@ -484,7 +484,7 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # Sınıf oluşturmak için objeden alt sınıf oluşturacağız. -class Insan(obje): +class Insan(object): # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir tur = "H. sapiens" @@ -499,7 +499,7 @@ class Insan(obje): # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. def soyle(self, mesaj): - return "{isim}: {mesaj}".format(isim=self.name, mesaj=mesaj) + return "{isim}: {mesaj}".format(isim=self.isim, mesaj=mesaj) # Bir sınıf metotu bütün nesnelere paylaştırılır # İlk parametre olarak sınıf alırlar -- cgit v1.2.3 From e1d76fb6f34a3391c45175667ed6d0d5f8e84910 Mon Sep 17 00:00:00 2001 From: x89k Date: Tue, 15 May 2018 10:19:34 +1000 Subject: Create montilang.html.markdown --- montilang.html.markdown | 234 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 montilang.html.markdown diff --git a/montilang.html.markdown b/montilang.html.markdown new file mode 100644 index 00000000..c7bee5a2 --- /dev/null +++ b/montilang.html.markdown @@ -0,0 +1,234 @@ +--- + +language: "MontiLang" +filename: montilang.ml +contributors: + - ["Leo Whitehead", "https://github.com/lduck11007"] +--- + +MontiLang is a Stack-Oriented concatenative imperative programming language. Its syntax +is roughly based off of forth with similar style for doing arithmetic in [reverse polish notation.](https://en.wikipedia.org/wiki/Reverse_Polish_notation) + +A good way to start with MontiLang is to read the documentation and examples at [montilang.ml](http://montilang.ml), +then download MontiLang or build from source code with the instructions provided. + +``` +/# Monti Reference sheet #/ +/# +Comments are multiline +Nested comments are not supported +#/ +/# Whitespace is all arbitrary, indentation is optional #/ +/# All programming in Monti is done by manipulating the parameter stack +arithmetic and stack operations in MontiLang are similar to FORTH +https://en.wikipedia.org/wiki/Forth_(programming_language) +#/ + +/# in Monti, everything is either a string or a number. Operations treat all numbers +similarly to floats, but anything without a remainder is treated as type int #/ + +/# numbers and strings are added to the stack from left to right #/ + +/# Arithmetic works by manipulating data on the stack #/ + +5 3 + PRINT . /# 8 #/ + +/# 5 and 3 are pushed onto the stack + '+' replaces top 2 items on stack with sum of top 2 items + 'PRINT' prints out the top item on the stack + '.' pops the top item from the stack. + #/ + +6 7 * PRINT . /# 42 #/ +1360 23 - PRINT . /# 1337 #/ +12 12 / PRINT . /# 1 #/ +13 2 % PRINT . /# 1 #/ + +37 NEG PRINT . /# -37 #/ +-12 ABS PRINT . /# 12 #/ +52 23 MAX PRINT . /# 52 #/ +52 23 MIN PRINT . /# 23 #/ + +/# 'PSTACK' command prints the entire stack, 'CLEAR' clears the entire stack #/ + +3 6 8 PSTACK CLEAR /# [3, 6, 8] #/ + +/# Monti comes with some tools for stack manipulation #/ + +2 DUP PSTACK CLEAR /# [2, 2] - Duplicate the top item on the stack#/ +2 6 SWAP PSTACK CLEAR /# [6, 2] - Swap top 2 items on stack #/ +1 2 3 ROT PSTACK CLEAR /# [2, 3, 1] - Rotate top 3 items on stack #/ +2 3 NIP PSTACK CLEAR /# [3] - delete second item from the top of the stack #/ +4 5 6 TRIM PSTACK CLEAR /# [5, 6] - Deletes first item on stack #/ +/# variables are assigned with the syntax 'VAR [name]'#/ +/# When assigned, the variable will take the value of the top item of the stack #/ + +6 VAR six . /# assigns var 'six' to be equal to 6 #/ +3 6 + VAR a . /# assigns var 'a' to be equal to 9 #/ + +/# the length of the stack can be calculated with the statement 'STKLEN' #/ +1 2 3 4 STKLEN PRINT CLEAR /# 4 #/ + +/# strings are defined with | | #/ + +|Hello World!| VAR world . /# sets variable 'world' equal to string 'Hello world! #/ + +/# variables can be called by typing its name. when called, the value of the variable is pushed +to the top of the stack #/ +world PRINT . + +/# with the OUT statement, the top item on the stack can be printed without a newline #/ + +|world!| |Hello, | OUT SWAP PRINT CLEAR + +/# Data types can be converted between strings and integers with the commands 'TOINT' and 'TOSTR'#/ +|5| TOINT PSTACK . /# [5] #/ +45 TOSTR PSTACK . /# ['45'] #/ + +/# User input is taken with INPUT and pushed to the stack. If the top item of the stack is a string, +the string is used as an input prompt #/ + +|What is your name? | INPUT NIP +|Hello, | OUT SWAP PRINT CLEAR + + +/# FOR loops have the syntax 'FOR [condition] [commands] ENDFOR' At the moment, [condition] can +only have the value of an integer. Either by using an integer, or a variable call to an integer. +[commands] will be interpereted the amount of time specified in [condition] #/ +/# E.G: this prints out 1 to 10 #/ + +1 VAR a . +FOR 10 + a PRINT 1 + VAR a +ENDFOR + +/# the syntax for while loops are similar. A number is evaluated as true if it is larger than +0. a string is true if its length > 0. Infinite loops can be used by using literals. +#/ +10 var loop . +WHILE loop + loop print + 1 - var loop +ENDWHILE +/# +this loop would count down from 10. + +IF statements are pretty much the same, but only are executed once. +#/ +IF loop + loop PRINT . +ENDIF + +/# This would only print 'loop' if it is larger than 0 #/ + +/# If you would want to use the top item on the stack as loop parameters, this can be done with the ':' character #/ + +/# eg, if you wanted to print 'hello' 7 times, instead of using #/ + +FOR 7 + |hello| PRINT . +ENDFOR + +/# this could be used #/ +7 +FOR : + |hello| PRINT . +ENDFOR + +/# Equality and inequality statements use the top 2 items on the stack as parameters, and replace the top two items with the output #/ +/# If it is true, the top 2 items are replaced with '1'. If false, with '0'. #/ + +7 3 > PRINT . /# 1 #/ +2 10 > PRINT . /# 0 #/ +5 9 <= PRINT . /# 1 #/ +5 5 == PRINT . /# 1 #/ +5 7 == PRINT . /# 0 #/ +3 8 != PRINT . /# 1 #/ + +/# User defined commands have the syntax of 'DEF [name] [commands] ENDDEF'. #/ +/# eg, if you wanted to define a function with the name of 'printseven' to print '7' 10 times, this could be used #/ + +DEF printseven + FOR 10 + 7 PRINT . + ENDFOR +ENDDEF + +/# to run the defined statement, simply type it and it will be run by the interpereter #/ + +printseven + +/# Montilang supports AND, OR and NOT statements #/ + +1 0 AND PRINT . /# 0 #/ +1 1 AND PRINT . /# 1 #/ +1 0 OR PRINT . /# 1 #/ +0 0 OR PRINT . /# 0 #/ +1 NOT PRINT . /# 0 #/ +0 NOT PRINT . /# 1 #/ + +/# Preprocessor statements are made inbetween '&' characters #/ +/# currently, preprocessor statements can be used to make c++-style constants #/ + +&DEFINE LOOPSTR 20& +/# must have & on either side with no spaces, 'DEFINE' is case sensative. #/ +/# All statements are scanned and replaced before the program is run, regardless of where the statements are placed #/ + +FOR LOOPSTR 7 PRINT . ENDFOR /# Prints '7' 20 times. At run, 'LOOPSTR' in source code is replaced with '20' #/ + +/# Multiple files can be used with the &INCLUDE & Command that operates similar to c++, where the file specified is tokenized, + and the &INCLUDE statement is replaced with the file #/ + +/# E.G, you can have a program be run through several files. If you had the file 'name.mt' with the following data: + +[name.mt] +|Hello, | OUT . name PRINT . + +a program that asks for your name and then prints it out can be defined as such: #/ + +|What is your name? | INPUT VAR name . &INCLUDE name.mt& + +/# ARRAYS: #/ + +/# arrays are defined with the statement 'ARR' +When called, everything currently in the stack is put into one +array and all items on the stack are replaced with the new array. #/ + +2 3 4 ARR PSTACK . /# [[2, 3, 4]] #/ + +/# the statement 'LEN' adds the length of the last item on the stack to the stack. +This can be used on arrays, as well as strings. #/ + +3 4 5 ARR LEN PRINT . /# 3 #/ + +/# values can be appended to an array with the statement 'APPEND' #/ + +1 2 3 ARR 5 APPEND . PRINT . /# [1, 2, 3, 5] #/ + +/# an array at the top of the stack can be wiped with the statement 'WIPE' #/ +3 4 5 ARR WIPE PRINT . /# [] #/ + +/# The last item of an array can be removed with the statement 'DROP' #/ + +3 4 5 ARR DROP PRINT . /# [3, 4] +/# arrays, like other datatypes can be stored in variables #/ +5 6 7 ARR VAR list . +list PRINT . /# [5, 6, 7] #/ + +/# Values at specific indexes can be changed with the statement 'INSERT ' #/ +4 5 6 ARR +97 INSERT 1 . PRINT /# 4, 97, 6 #/ + +/# Values at specific indexes can be deleted with the statement 'DEL ' #/ +1 2 3 ARR +DEL 1 PRINT . /# [1, 3] #/ + +/# items at certain indexes of an array can be gotten with the statement 'GET ' #/ + +1 2 3 ARR GET 2 PSTACK /# [[1, 2, 3], 3] #/ +``` + +## Extra information + +- [MontiLang.ml](http://montilang.ml/) +- [Github Page](https://github.com/lduck11007/MontiLang) -- cgit v1.2.3 From 30b7e84f2642dc4182d3c1333ffe14fdaddd6f5b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 May 2018 12:03:43 +0200 Subject: add example playbook --- ansible.html.markdown | 74 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 74195222..d02ca1ce 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,14 +6,73 @@ contributors: filename: LearnAnsible.txt --- -## Ansible: the easiest orchestration tool - -```yaml --- -"{{ Explanation: Why Ansible and detailed Intro }}" written in the second part of document +"{{ Ansible }}" is an orchestration tool written in Python. ``` +## Example +An example playbook to install apache and configure log level +```yml +--- +- hosts: apache + + vars: + apache2_log_level: "warn" + + handlers: + - name: restart apache + service: + name: apache2 + state: restarted + enabled: True + notify: + - Wait for instances to listen on port 80 + become: True + + - name: reload apache + service: + name: apache2 + state: reloaded + notify: + - Wait for instances to listen on port 80 + become: True + + - name: Wait for instances to listen on port 80 + wait_for: + state: started + host: localhost + port: 80 + timeout: 15 + delay: 5 + + tasks: + - name: Update cache + apt: + update_cache: yes + cache_valid_time: 7200 + become: True + + - name: Install packages + apt: + name={{ item }} + with_items: + - apache2 + - logrotate + notify: + - restart apache + become: True + + - name: Configure apache2 log level + lineinfile: + dest: /etc/apache2/apache2.conf + line: "LogLevel {{ apache2_log_level }}" + regexp: "^LogLevel" + notify: + - reload apache + become: True + +``` ## Installation ```bash @@ -29,7 +88,7 @@ $ apt-get install ansible ### Your first ansible command (shell execution) ```bash -# This command ping the localhost (defined in default inventory /etc/ansible/hosts) +# This command ping the localhost (defined in default inventory: /etc/ansible/hosts) $ ansible -m ping localhost # you should see this output localhost | SUCCESS => { @@ -231,12 +290,15 @@ For now you should know that CLI variables have the top priority. You should also know, that a nice way to pool some data is a **lookup** ### Lookups +Awesome tool to query data from various sources!!! Awesome! query from: -* pipe +* pipe (load shell command output into variable!) * file * stream * etcd +* password management tools +* url ```bash # read playbooks/lookup.yml -- cgit v1.2.3 From 0429074f0808ec5f369f53375bdd6580f246f81e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 May 2018 12:04:30 +0200 Subject: rm .ansible.html.markdown.swl --- .ansible.html.markdown.swl | Bin 36864 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .ansible.html.markdown.swl diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl deleted file mode 100644 index 259fc5a0..00000000 Binary files a/.ansible.html.markdown.swl and /dev/null differ -- cgit v1.2.3 From 2af6679e91bdaf055cc969e7fbf7c2585f744e43 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 May 2018 12:06:16 +0200 Subject: add example playbook --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index d02ca1ce..a319a89d 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,6 +6,7 @@ contributors: filename: LearnAnsible.txt --- +```yml --- "{{ Ansible }}" is an orchestration tool written in Python. -- cgit v1.2.3 From 198df4779beaa51e94aca69deff7ad7a572a3f06 Mon Sep 17 00:00:00 2001 From: ShuLiang Date: Fri, 25 May 2018 15:28:37 +0800 Subject: update to swift 4.1 --- zh-cn/swift-cn.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index c25b2918..18bc52ed 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -110,7 +110,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." // -// Mark: 数组与字典(关联数组) +// MARK: 数组与字典(关联数组) // /* @@ -214,9 +214,9 @@ func greet(name: String, day: String) -> String { } greet("Bob", day: "Tuesday") -// 第一个参数表示外部参数名和内部参数名使用同一个名称。 +// 第一个参数`_`表示不使用外部参数名,忽略`_`表示外部参数名和内部参数名使用同一个名称。 // 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName` -func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { +func greet2(_ requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值 @@ -250,7 +250,7 @@ var increment = makeIncrementer() increment(7) // 强制进行指针传递 (引用传递),使用 `inout` 关键字修饰函数参数 -func swapTwoInts(inout a: Int, inout b: Int) { +func swapTwoInts(a: inout Int, b: inout Int) { let tempA = a a = b b = tempA @@ -521,7 +521,7 @@ class MyShape: Rect { // 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。 // 这样就不会引起运行时错误 (runtime error) - if let reshape = self.delegate?.canReshape?() where reshape { + if let reshape = self.delegate?.canReshape?() { // 注意语句中的问号 self.delegate?.reshape?() } @@ -575,10 +575,10 @@ print(foundAtIndex == 2) // true // 自定义运算符可以以下面的字符打头: // / = - + * % < > ! & | ^ . ~ // 甚至是 Unicode 的数学运算符等 -prefix operator !!! {} +prefix operator !!! // 定义一个前缀运算符,使矩形的边长放大三倍 -prefix func !!! (inout shape: Square) -> Square { +prefix func !!! (shape: inout Square) -> Square { shape.sideLength *= 3 return shape } @@ -591,8 +591,8 @@ print(mySquare.sideLength) // 4 print(mySquare.sideLength) // 12 // 运算符也可以是泛型 -infix operator <-> {} -func <-> (inout a: T, inout b: T) { +infix operator <-> +func <-> (a: inout T, b: inout T) { let c = a a = b b = c -- cgit v1.2.3 From a462b444e06f75c9f98983e925b8f79a1092d277 Mon Sep 17 00:00:00 2001 From: Brian Stearns Date: Thu, 31 May 2018 15:53:10 -0400 Subject: Correct English a/an usage --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 016e2b4f..28424684 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -716,7 +716,7 @@ import scala.collection.immutable.{Map => _, Set => _, _} // Java classes can also be imported. Scala syntax can be used import java.swing.{JFrame, JWindow} -// Your programs entry point is defined in an scala file using an object, with a +// Your programs entry point is defined in a scala file using an object, with a // single method, main: object Application { def main(args: Array[String]): Unit = { -- cgit v1.2.3 From 8aa693c8cb1b5e7136603ce8e000d2142a6a20e6 Mon Sep 17 00:00:00 2001 From: Yvan Sraka Date: Sat, 9 Jun 2018 18:35:45 +0200 Subject: Fix typos in French version of Dynamic Programming tutorial --- fr-fr/dynamic-programming-fr.html.markdown | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index 24e8c95f..b3660ac9 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -8,7 +8,6 @@ translators: lang: fr-fr --- - # Programmation dynamique ## Introduction @@ -17,9 +16,9 @@ La programmation dynamique est une technique très efficace pour résoudre une c ## Moyens de résoudre ces problèmes -1.) *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation. +1. *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation. -2.) *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique. +2. *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique. ## Exemple de Programmation Dynamique @@ -27,7 +26,7 @@ Le problème de la plus grande sous-chaîne croissante est de trouver la plus gr Premièrement, nous avons à trouver la valeur de la plus grande sous-chaîne (LSi) à chaque index `i`, avec le dernier élément de la sous-chaîne étant ai. Alors, la plus grande sous-chaîne sera le plus gros LSi. Pour commencer, LSi est égal à 1, car ai est le seul élément de la chaîne (le dernier). Ensuite, pour chaque `j` tel que `j Date: Sat, 9 Jun 2018 19:06:33 +0200 Subject: Translate Lambda Calculus in French --- fr-fr/lambda-calculus-fr.html.markdown | 105 +++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 fr-fr/lambda-calculus-fr.html.markdown diff --git a/fr-fr/lambda-calculus-fr.html.markdown b/fr-fr/lambda-calculus-fr.html.markdown new file mode 100644 index 00000000..68868830 --- /dev/null +++ b/fr-fr/lambda-calculus-fr.html.markdown @@ -0,0 +1,105 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] +translators: + - ["Yvan Sraka", "https://github.com/yvan-sraka"] +--- + +# Lambda-calcul + +Le Lambda-calcul (λ-calcul), créé à l'origine par [Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), est le plus petit langage de programmation au monde. En dépit de ne pas avoir de nombres, de chaînes, de booléens, ou de tout type de données sans fonction, le lambda calcul peut être utilisé pour représenter n'importe quelle machine de Turing! + +Le Lambda-calcul est composé de 3 éléments : **variables**, **fonctions** et **applications**. + + +| Nom | Syntaxe | Exemple | Explication | +|-------------|------------------------------------|-----------|---------------------------------------------------| +| Variable | `` | `x` | une variable nommée "x" | +| Fonction | `λ.` | `λx.x` | une fonction avec le paramètre "x" et le corps "x"| +| Application | `` | `(λx.x)a` | appel de la fonction "λx.x" avec l'argument "a" | + +La fonction la plus fondamentale est la fonction identité: `λx.x` qui est équivalente à `f(x) = x`. Le premier "x" est l'argument de la fonction, et le second est le corps de la fonction. + +## Variables libres et liées : + +- Dans la fonction `λx.x`, "x" s'appelle une variable liée car elle est à la fois dans le corps de la fonction et l'un des paramètres. +- Dans `λx.y`, "y" est appelé une variable libre car elle n'a pas été déclarée plus tôt. + +## Évaluation : + +L'évaluation est réalisée par [β-Réduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), qui est essentiellement une substitution lexicale. + +Lors de l'évaluation de l'expression `(λx.x)a`, nous remplaçons toutes les occurrences de "x" dans le corps de la fonction par "a". + +- `(λx.x)a` vaut après évaluation: `a` +- `(λx.y)a` vaut après évaluation: `y` + +Vous pouvez même créer des fonctions d'ordre supérieur: + +- `(λx.(λy.x))a` vaut après évaluation: `λy.a` + +Bien que le lambda-calcul ne prenne traditionnellement en charge que les fonctions à un seul paramètre, nous pouvons créer des fonctions multi-paramètres en utilisant une technique appelée currying. + +- `(λx.λy.λz.xyz)` est équivalent à `f(x, y, z) = x(y(z))` + +Parfois, `λxy.` est utilisé de manière interchangeable avec: `λx.λy.` + +---- + +Il est important de reconnaître que le lambda-calcul traditionnel n'a pas de nombres, de caractères ou tout autre type de données sans fonction! + +## Logique booléenne : + +Il n'y a pas de "Vrai" ou de "Faux" dans le calcul lambda. Il n'y a même pas 1 ou 0. + +Au lieu: + +`T` est représenté par: `λx.λy.x` + +`F` est représenté par: `λx.λy.y` + +Premièrement, nous pouvons définir une fonction "if" `λbtf` qui renvoie `t` si `b` est vrai et `f` si `b` est faux + +`IF` est équivalent à: `λb.λt.λf.b t f` + +En utilisant `IF`, nous pouvons définir les opérateurs logiques de base booléens: + +`a AND b` est équivalent à: `λab.IF a b F` + +`a OR b` est équivalent à: `λab.IF a T b` + +`a NOT b` est équivalent à: `λa.IF a F T` + +*Note: `IF a b c` est equivalent à : `IF(a(b(c)))`* + +## Nombres : + +Bien qu'il n'y ait pas de nombres dans le lambda-calcul, nous pouvons encoder des nombres en utilisant les [nombres de Church](https://en.wikipedia.org/wiki/Church_encoding). + +Pour tout nombre n: n = λf.fn donc: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +Pour incrémenter un nombre de Church, nous utilisons la fonction successeur `S(n) = n + 1` qui est: + +`S = λn.λf.λx.f((n f) x)` + +En utilisant `S`, nous pouvons définir la fonction `ADD`: + +`ADD = λab.(a S)n` + +**Défi:** essayez de définir votre propre fonction de multiplication! + +## Pour aller plus loin : + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file -- cgit v1.2.3 From ee013dd2da8def229cbb219e0c6a700f150e57e8 Mon Sep 17 00:00:00 2001 From: boissonnfive Date: Tue, 26 Jun 2018 23:17:27 +0200 Subject: Several corrections + copy english markdown page format. --- fr-fr/markdown-fr.html.markdown | 253 +++++++++++++++++++++++++--------------- 1 file changed, 156 insertions(+), 97 deletions(-) diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 8518f35c..42af1b2b 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -10,48 +10,64 @@ Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" -et envoyer des pull request! +Le Markdown est implémenté de différentes manières, selon le parser. +Ce guide va alors tenter de trier les fonctionnalités universelles de celles +spécifiques à un parser. +- [HTML](#html) +- [Titres](#titres) +- [Formatage simple du texte](#formatage-simple-du-texte) +- [Les paragraphes](#les-paragraphes) +- [Les listes](#les-listes) +- [Insertion de code](#insertion-de-code) +- [Ligne Horizontale](#ligne-horizontale) +- [Liens](#liens) +- [Images](#images) +- [Divers](#divers) -```md - +le parser( analyseur syntaxique ) Markdown. - +``` - - - +## Titres + +Vous pouvez facilement créer des éléments HTML `

` à `

en précédant le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon le niveau de titre souhaité. + +```md # Ceci est un

## Ceci est un

### Ceci est un

#### Ceci est un

##### Ceci est un

###### Ceci est un
+``` - +Markdown fournit également une façon alternative de marquer les h1 et h2 +```md Ceci est un h1 ============= Ceci est un h2 ------------- +``` + +## Formatage simple du texte - - + On peut facilement rendre un texte "gras" ou "italique" en Markdown +```md *Ce texte est en italique.* _Celui-ci aussi._ @@ -61,15 +77,23 @@ __Celui-là aussi.__ ***Ce texte a les deux styles.*** **_Pareil ici_** *__Et là!__* +``` + - +Dans le Markdown de GitHub, utilisé pour interpréter le Markdown +sur GitHub, on a également le strikethrough ( texte barré ) : +```md ~~Ce texte est barré avec strikethrough.~~ +``` + - +## Les paragraphes +Les Paragraphes sont représentés par une ou plusieurs lignes de texte +séparées par une ou plusieurs lignes vides. + +```md Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. @@ -77,19 +101,21 @@ Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! +``` - +```md J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! +``` - +Les 'Blocs de Citations' sont générés aisément, grâce au caractère `>` +```md > Ceci est une superbe citation. Vous pouvez même > revenir à la ligne quand ça vous chante, et placer un `>` > devant chaque bout de ligne faisant partie @@ -99,11 +125,14 @@ Bigre, il y a un
au dessus de moi! > Vous pouvez aussi utiliser plus d'un niveau >> d'imbrication! > Classe et facile, pas vrai? +``` + - - +## Les listes +les Listes non ordonnées sont marquées par des asterisques, signes plus ou signes moins. + +```md * Item * Item * Un autre item @@ -119,171 +148,201 @@ ou - Item - Item - Un dernier item +``` - +les Listes Ordonnées sont générées via un nombre suivi d'un point +```md 1. Item un 2. Item deux 3. Item trois +``` - +Vous pouvez même vous passer de tout numéroter, et Markdown générera les bons chiffres. Ceci dit, cette variante perd en clarté. +```md 1. Item un 1. Item deux 1. Item trois - +``` + +(cette liste sera interprétée de la même façon que celle au-dessus) - +Vous pouvez également utiliser des sous-listes +```md 1. Item un 2. Item deux 3. Item trois * Sub-item * Sub-item 4. Item quatre +``` - - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. +Il y a même des "listes de Taches". Elles génèrent des champs HTML de type checkbox. Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. +```md - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. - [x] Ça ... c'est fait! +``` + - - +## Insertion de code +Pour marquer du texte comme étant du code, il suffit de commencer +chaque ligne en tapant 4 espaces (ou un Tab). + +```md echo "Ça, c'est du Code!"; var Ça = "aussi !"; +``` - +L'indentation par tab ou série de quatre espaces fonctionne aussi à l'intérieur du bloc de code. +```md my_array.each do |item| puts item end +``` - +On peut insérer du code dans le texte des paragraphes en entourant le code par des `. +```md La fonction `run()` ne vous oblige pas à aller courir! +``` + +En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques. - -\`\`\`ruby - -def foobar -puts "Hello world!" -end -\`\`\` + ```ruby + def foobar + puts "Hello world!" + end + ``` + +Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub +va utiliser une coloration syntaxique pour le langage indiqué après les ```. -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub -va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> +## Ligne Horizontale - - +Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets, +avec ou sans espaces entre chaque un. +```md *** --- - - - **************** +``` + +## Liens - - +Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ), et voilà l'travail. +```md [Clic moi!](http://test.com/) +``` - +Pour ajouter un attribut Title, collez-le entre guillemets, avec le lien. +```md [Clic moi!](http://test.com/ "Lien vers Test.com") +``` - +Les Liens Relatifs marchent aussi. +```md [En avant la musique](/music/). +``` - +Les liens façon "références" sont eux aussi disponibles en Markdown. +```md [Cliquez ici][link1] pour plus d'information! [Regardez aussi par ici][foobar] si vous voulez. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" +``` - +Le titre peut aussi être entouré de guillemets simples, entre parenthèses ou absent. Les références peuvent être placées un peu où vous voulez dans le document, et les identifiants (link1, foobar, ...) pevent être n'importe quoi tant qu'ils sont uniques. - +Il y a également le "nommage implicite" qui transforme le texte du lien en identifiant. +```md [Ceci][] est un lien. [ceci]: http://ceciestunlien.com/ +``` - +mais ce n'est pas beaucoup utilisé. - - +## Images +Pour les images, la syntaxe est identique aux liens, sauf que précédée d'un point d'exclamation! + +```md ![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") +``` - +Là aussi, on peut utiliser le mode "références". +```md ![Ceci est l'attribut ALT de l'image][monimage] [monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." +``` - - +## Divers + +### Liens Automatiques + +```md est équivalent à : [http://testwebsite.com/](http://testwebsite.com/) +``` - +### Liens Automatiques pour emails +```md +``` + +### Caractères d'échappement + +Il suffit de précéder les caractères spécifiques à ignorer par des anti slash `\`.` - -Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ +```md +Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. +``` -Pour taper *ce texte* entouré d'astérisques mais pas en italique : -Tapez \*ce texte\*. +### Tableaux - - +Les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown et c'est ce n'est pas super agréable d'utilisation. Mais si vous en avez besoin : +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Alignement Gauche | Centé | Alignement Droite | | bla | bla | bla | +``` - +ou bien, pour un résultat équivalent : +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ough que c'est moche | svp | arrêtez +``` - +*** -``` +Pour plus d'information, consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de John Gruber à propos de la syntaxe, et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. +*** + +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! \ No newline at end of file -- cgit v1.2.3 From 92022da0a6ea9417521563de9e537f337c426465 Mon Sep 17 00:00:00 2001 From: boissonnfive Date: Wed, 27 Jun 2018 14:45:10 +0200 Subject: Corrections de majuscules, sauts de lignes, guillemets, accents + reformulations. --- fr-fr/markdown-fr.html.markdown | 85 ++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 48 deletions(-) diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 42af1b2b..4a2ecedc 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -7,12 +7,13 @@ lang: fr-fr --- Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML - (et beaucoup d'autres formats aussi à présent). +facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). + +Il existe de nombreuses formes de Markdown : Markown classique, Markdown GitHub, Multi-Markdown, etc. Dans ce guide, nous signalerons quand les fonctionnalités sont spécifiques à une forme. + +_Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request!_ -Le Markdown est implémenté de différentes manières, selon le parser. -Ce guide va alors tenter de trier les fonctionnalités universelles de celles -spécifiques à un parser. - [HTML](#html) - [Titres](#titres) @@ -28,21 +29,20 @@ spécifiques à un parser. ## HTML -Markdown est une sorte de cousin du HTML, si bien que tout document HTML -est un document Markdown valide. Autrement dit, vous pouvez utiliser des -balises HTML dans un fichier Markdown, comme la balise commentaire dans -laquelle nous sommes à présent, car celle-ci ne sera pas affectée par -le parser( analyseur syntaxique ) Markdown. +Markdown est une sorte de cousin du HTML, si bien que tout document HTML est un document Markdown valide. ```md - + ``` ## Titres -Vous pouvez facilement créer des éléments HTML `

` à `

en précédant le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon le niveau de titre souhaité. +Vous pouvez facilement créer des titres HTML `

` à `

` en précédant le texte de votre futur titre par un ou plusieurs dièses (#), de un à six, selon le niveau de titre souhaité. ```md # Ceci est un

@@ -53,7 +53,7 @@ Vous pouvez facilement créer des éléments HTML `

` à `

en précédant ###### Ceci est un
``` -Markdown fournit également une façon alternative de marquer les h1 et h2 +Markdown fournit également une façon alternative de marquer les `

` et `

` ```md Ceci est un h1 @@ -65,7 +65,7 @@ Ceci est un h2 ## Formatage simple du texte - On peut facilement rendre un texte "gras" ou "italique" en Markdown + On peut facilement mettre un texte en « gras » ou en « italique » en Markdown ```md *Ce texte est en italique.* @@ -79,9 +79,7 @@ __Celui-là aussi.__ *__Et là!__* ``` - -Dans le Markdown de GitHub, utilisé pour interpréter le Markdown -sur GitHub, on a également le strikethrough ( texte barré ) : +Dans le Markdown GitHub, utilisé pour interpréter le Markdown sur le site de GitHub, on a également le texte barré : ```md ~~Ce texte est barré avec strikethrough.~~ @@ -90,8 +88,7 @@ sur GitHub, on a également le strikethrough ( texte barré ) : ## Les paragraphes -Les Paragraphes sont représentés par une ou plusieurs lignes de texte -séparées par une ou plusieurs lignes vides. +Les Paragraphes sont représentés par une ou plusieurs lignes de texte séparées par une ou plusieurs lignes vides. ```md Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? @@ -103,17 +100,17 @@ Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! ``` -Si jamais vous souhaitez insérer une balise HTML
, vous pouvez ajouter +Si jamais vous souhaitez insérer une balise HTML `
`, vous pouvez ajouter un ou plusieurs espaces à la fin de votre paragraphe, et en commencer un nouveau. ```md -J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! ``` -Les 'Blocs de Citations' sont générés aisément, grâce au caractère `>` +Les « Blocs de Citations » sont générés aisément, grâce au caractère `>` ```md > Ceci est une superbe citation. Vous pouvez même @@ -130,7 +127,7 @@ Les 'Blocs de Citations' sont générés aisément, grâce au caractère `>` ## Les listes -les Listes non ordonnées sont marquées par des asterisques, signes plus ou signes moins. +Les listes non ordonnées sont marquées par des astérisques, signes plus ou signes moins. ```md * Item @@ -150,7 +147,7 @@ ou - Un dernier item ``` -les Listes Ordonnées sont générées via un nombre suivi d'un point +Les listes ordonnées sont générées via un nombre suivi d'un point ```md 1. Item un @@ -168,7 +165,7 @@ Vous pouvez même vous passer de tout numéroter, et Markdown générera les bon (cette liste sera interprétée de la même façon que celle au-dessus) -Vous pouvez également utiliser des sous-listes +Vous pouvez également utiliser des sous-listes. ```md 1. Item un @@ -179,7 +176,7 @@ Vous pouvez également utiliser des sous-listes 4. Item quatre ``` -Il y a même des "listes de Taches". Elles génèrent des champs HTML de type checkbox. Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. +En Markdown GitHub, il y a même des « listes de tâches ». Elles génèrent des champs HTML de type checkbox. Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. ```md - [ ] Première tache à réaliser. @@ -191,15 +188,14 @@ La case suivante sera une case à cocher HTML cochée. ## Insertion de code -Pour marquer du texte comme étant du code, il suffit de commencer -chaque ligne en tapant 4 espaces (ou un Tab). +Pour marquer du texte comme étant du code, il suffit de commencer chaque ligne en tapant 4 espaces (ou un Tab). ```md echo "Ça, c'est du Code!"; var Ça = "aussi !"; ``` -L'indentation par tab ou série de quatre espaces fonctionne aussi à l'intérieur du bloc de code. +L'indentation par tab ou série de quatre espaces fonctionne aussi à 'intérieur du bloc de code. ```md my_array.each do |item| @@ -207,7 +203,7 @@ L'indentation par tab ou série de quatre espaces fonctionne aussi à l'intérie end ``` -On peut insérer du code dans le texte des paragraphes en entourant le code par des `. +On peut insérer du code à l'intérieur du texte en entourant le code par des `. ```md La fonction `run()` ne vous oblige pas à aller courir! @@ -215,20 +211,18 @@ La fonction `run()` ne vous oblige pas à aller courir! En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques. - ```ruby def foobar puts "Hello world!" end ``` -Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub +Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub va utiliser une coloration syntaxique pour le langage indiqué après les ```. ## Ligne Horizontale -Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets, -avec ou sans espaces entre chaque un. +Pour insérer une ligne horizontale, utilisez trois ou plusieurs astérisques ou tirets, avec ou sans espaces entre. ```md *** @@ -245,19 +239,19 @@ Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des [Clic moi!](http://test.com/) ``` -Pour ajouter un attribut Title, collez-le entre guillemets, avec le lien. +Pour ajouter un attribut `Title`, collez-le entre guillemets, avec le lien. ```md [Clic moi!](http://test.com/ "Lien vers Test.com") ``` -Les Liens Relatifs marchent aussi. +Les liens relatifs marchent aussi. ```md [En avant la musique](/music/). ``` -Les liens façon "références" sont eux aussi disponibles en Markdown. +Les liens façon « références » sont eux aussi disponibles en Markdown. ```md [Cliquez ici][link1] pour plus d'information! @@ -267,9 +261,9 @@ Les liens façon "références" sont eux aussi disponibles en Markdown. [foobar]: http://foobar.biz/ "Alright!" ``` -Le titre peut aussi être entouré de guillemets simples, entre parenthèses ou absent. Les références peuvent être placées un peu où vous voulez dans le document, et les identifiants (link1, foobar, ...) pevent être n'importe quoi tant qu'ils sont uniques. +Le titre peut aussi être entouré de guillemets simples, entre parenthèses ou absent. Les références peuvent être placées un peu où vous voulez dans le document, et les identifiants (link1, foobar, ...) peuvent être n'importe quoi tant qu'ils sont uniques. -Il y a également le "nommage implicite" qui transforme le texte du lien en identifiant. +Il y a également le « nommage implicite » qui transforme le texte du lien en identifiant. ```md [Ceci][] est un lien. @@ -277,7 +271,7 @@ Il y a également le "nommage implicite" qui transforme le texte du lien en iden [ceci]: http://ceciestunlien.com/ ``` -mais ce n'est pas beaucoup utilisé. +Mais ce n'est pas beaucoup utilisé. ## Images @@ -313,7 +307,7 @@ Là aussi, on peut utiliser le mode "références". ### Caractères d'échappement -Il suffit de précéder les caractères spécifiques à ignorer par des anti slash `\`.` +Il suffit de faire précéder les caractères spécifiques à ignorer par des anti slash `\`.` ```md Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. @@ -321,7 +315,7 @@ Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce ### Tableaux -Les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown et c'est ce n'est pas super agréable d'utilisation. Mais si vous en avez besoin : +Les Tableaux ne sont disponibles que dans le Markdown GitHub et ce n'est pas super agréable d'utilisation. Mais si vous en avez besoin : ```md | Col1 | Col2 | Col3 | @@ -341,8 +335,3 @@ Ough que c'est moche | svp | arrêtez *** Pour plus d'information, consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de John Gruber à propos de la syntaxe, et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. - -*** - -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" -et envoyer des pull request! \ No newline at end of file -- cgit v1.2.3 From 8f5f8d576bf248a2af9689cb88161f06e2a47e02 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 16:52:13 +0630 Subject: Initial Commit --- processing.html.markdown | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 processing.html.markdown diff --git a/processing.html.markdown b/processing.html.markdown new file mode 100644 index 00000000..707e09c9 --- /dev/null +++ b/processing.html.markdown @@ -0,0 +1,27 @@ +--- +language: "Processing" +filename: learnprocessing.pde +contributors: + - ["Phone Thant Ko", "http://github.com/phonethantko"] +--- +Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to +learn fundamentals of computer programming in a visual context. While the language is based off on Java language, +its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) +The language also comes with its official IDE to compile and run the scripts. + +```Processing +// Single-line comment starts with // + +/* + Since Processing is based on Java the syntax for its comments are the same as Java (as you may have noticed above)! + Multi-line comments are wrapped around /* */ +*/ + +// In Processing, your program's entry point is a function named setup() with a void return type. +// Note! The syntax looks strikingly similar to that of C++ +void setup() { + // This prints out the classic output "Hello World!" to the console when run. + println("Hello World!"); // Another language with a semi-column trap, aint it? +} + +``` -- cgit v1.2.3 From 45432cdc0d9ccf083d4f32be4fa175ee0fa6bbe2 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 16:59:16 +0630 Subject: Update processing.html.markdown --- processing.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 707e09c9..f4b90882 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -5,15 +5,17 @@ contributors: - ["Phone Thant Ko", "http://github.com/phonethantko"] --- Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to -learn fundamentals of computer programming in a visual context. While the language is based off on Java language, -its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) +learn fundamentals of computer programming in a visual context. +While the language is based off on Java language, +its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) The language also comes with its official IDE to compile and run the scripts. ```Processing // Single-line comment starts with // /* - Since Processing is based on Java the syntax for its comments are the same as Java (as you may have noticed above)! + Since Processing is based on Java, + the syntax for its comments are the same as Java (as you may have noticed above)! Multi-line comments are wrapped around /* */ */ -- cgit v1.2.3 From 96335abf1079668a5cbe10037de9a58ea6e98af8 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 18:02:18 +0630 Subject: 29/06/2018 - 6:02PM --- processing.html.markdown | 69 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index f4b90882..2d70e082 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -4,26 +4,83 @@ filename: learnprocessing.pde contributors: - ["Phone Thant Ko", "http://github.com/phonethantko"] --- +## Introduction + Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to learn fundamentals of computer programming in a visual context. While the language is based off on Java language, its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) The language also comes with its official IDE to compile and run the scripts. -```Processing +```processing +/* --------- + Comments + --------- +*/ + // Single-line comment starts with // /* - Since Processing is based on Java, - the syntax for its comments are the same as Java (as you may have noticed above)! - Multi-line comments are wrapped around /* */ + Since Processing is based on Java, + the syntax for its comments are the same as Java (as you may have noticed above)! + Multi-line comments are wrapped as seen here. */ +/* --------------------------------------- + Writing and Running Processing Programs + --------------------------------------- + */ + // In Processing, your program's entry point is a function named setup() with a void return type. -// Note! The syntax looks strikingly similar to that of C++ +// Note! The syntax looks strikingly similar to that of C++. void setup() { // This prints out the classic output "Hello World!" to the console when run. - println("Hello World!"); // Another language with a semi-column trap, aint it? + println("Hello World!"); // Another language with a semi-column trap, ain't it? } +// Normally, we put all the static codes inside the setup() method as the name suggests. +// It can range from setting the background colours, setting the canvas size. +// You will see more of them throughout this document. + +// Now that we know how to write the working script and how to run it, +// we will proceed to explore what data types and collections are supported in Processing. + +/* ----------------------- + Datatypes & collections + ------------------------ +*/ + +// According to Processing References, Processing supports 8 primitive datatypes as follows. + +boolean booleanValue = true; // Boolean +byte byteValueOfA = 23; // Byte +char charValueOfA = 'A'; // Char +color colourValueOfWhiteM = color(255, 255, 255); // Colour (Specified using color() method) +color colourValueOfWhiteH = #FFFFFF; // Colour (Specified using hash value) +int intValue = 5; // Integer (Number without decimals) +long longValue = 2147483648L; // "L" is added to the number to mark it as a long +float floatValue = 1.12345; // Float (32-bit floating-point numbers) +double doubleValue = 1.12345D; // Double (64-bit floating-point numbers) + +// NOTE! +// Although datatypes "long" and "double" work in the language, +// processing functions do not use these datatypes, therefore +// they need to be converted into "int" and "float" datatypes respectively, +// using (int) and (float) syntax before passing into a function. + + + + ``` +Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without +having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of +the program flow. +However, that does not apply when you introduce external libraries, packages and even your own classes. +(Trust me! Processing projects can get really large) + +## What's Next? + +Here, I have compiled some useful resources: + + - [Processing Website](http://processing.org) + - [Processing Sketches](http://openprocessing.org) -- cgit v1.2.3 From faca0e79445f90e51acc4c4345795de6ae69c9ab Mon Sep 17 00:00:00 2001 From: hra Date: Sun, 1 Jul 2018 15:05:02 -0700 Subject: add for/of to js --- javascript.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c8a52d..f2dd08c8 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -248,6 +248,13 @@ for (var x in person){ description += person[x] + " "; } // description = 'Paul Ken 18 ' +// The for/of statement allows iteration over an iterator. +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' + // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ house.contains = "bear"; -- cgit v1.2.3 From 2a3d19ef73cf273e5ab0b0a6d640172b47b6bb92 Mon Sep 17 00:00:00 2001 From: hra Date: Sun, 1 Jul 2018 15:10:13 -0700 Subject: add for/of to js (change description) --- javascript.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index f2dd08c8..35bcf988 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -248,7 +248,9 @@ for (var x in person){ description += person[x] + " "; } // description = 'Paul Ken 18 ' -// The for/of statement allows iteration over an iterator. +// The for/of statement allows iteration over iterable objects (including the built-in String, +// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set, +// and user-defined iterables). var myPets = ""; var pets = ["cat", "dog", "hamster", "hedgehog"]; for (var pet of pets){ -- cgit v1.2.3 From c258855144e5c59b8fa84730878e179fbb19807f Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:14:50 +0630 Subject: 2/7/18 11:14PM --- processing.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 2d70e082..83f774ee 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -8,9 +8,9 @@ contributors: Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to learn fundamentals of computer programming in a visual context. -While the language is based off on Java language, +While the language is based on Java language, its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) -The language also comes with its official IDE to compile and run the scripts. +The language is statically typed, and also comes with its official IDE to compile and run the scripts. ```processing /* --------- @@ -38,10 +38,19 @@ void setup() { println("Hello World!"); // Another language with a semi-column trap, ain't it? } -// Normally, we put all the static codes inside the setup() method as the name suggests. +// Normally, we put all the static codes inside the setup() method as the name suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. // You will see more of them throughout this document. +// If you want to run the codes indefinitely, it has to be placed in draw() method. +// draw() must exist if you want the code to run continuously and obviously, there can only be one draw() method. +int i = 0; +void draw() { + // This block of code loops forever until stopped + print(i); + i++; // Increment Operator! +} + // Now that we know how to write the working script and how to run it, // we will proceed to explore what data types and collections are supported in Processing. @@ -68,8 +77,73 @@ double doubleValue = 1.12345D; // Double (64-bit floating-point numbers) // they need to be converted into "int" and "float" datatypes respectively, // using (int) and (float) syntax before passing into a function. - - +// There is a whole bunch of default composite datatypes available for use in Processing. +// Primarily, I will brief through the most commonly used ones to save time. + +// String +// While char datatype uses '', String datatype uses "" - double quotes. +String sampleString = "Hello, Processing!"; +// String can be constructed from an array of char datatypes as well. We will discuss array very soon. +char source = {'H', 'E', 'L', 'L', 'O'}; +String stringFromSource = new String(source); // HELLO +// As in Java, strings can be concatenated using the "+" operator. +print("Hello " + "World!"); // Hello World! + +// Array +// Arrays in Processing can hold any datatypes including Objects themselves. +// Since arrays are similar to objects, they must be created with the keyword "new". +int[] intArray = new int[5]; +int[] intArrayWithValues = {1, 2, 3}; // You can also populate with data. + +// ArrayList +// Functions are similar to those of array; arraylists can hold any datatypes. +// The only difference is arraylists resize dynamically, +// as it is a form of resizable-array implementation of the Java "List" interface. +ArrayList intArrayList = new ArrayList(); + +// Object +// Since it is based on Java, Processing supports object-oriented programming. +// That means you can basically define any datatypes of your own and manipulate them to your needs. +// Of course, a class has to be defined before for the object you want. +// Format --> ClassName InstanceName +SomeRandomClass myObject // then instantiate later +//or +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor + +// Processing comes up with more collections (eg. - Dictionaries and Lists) by default, +// for the simplicity sake, I will leave them out of discussion here. + +/* ----------- + Maths + ------------ +*/ +// Arithmetic +1 + 1 // 2 +2 - 1 // 0 +2 * 3 // 6 +3 / 2 // 1 +3.0 / 2 // 1.5 +3.0 % 2 // 1.0 + +// Processing also comes with a set of functions that simplify mathematical operations. +float f = sq(3); // f = 9.0 +float p = pow(3, 3); // p = 27.0 +int a = abs(-13) // a = 13 +int r1 = round(3.1); // r1 = 3 +int r2 = round(3.7); // r2 = 4 +float sr = sqrt(25); // sr = 5.0 + +// Vectors +// Processing provides an easy way to implement vectors in its environment using PVector class. +// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) + +// Trigonometry +// Processing also supports trigonometric operations by supplying a set of functions. +// sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. +// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +float one = sin(PI/2); // one = 1.0 +// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From dd92983e8b2e85606c01c252e888c96fb43bb865 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:17:25 +0630 Subject: 2/7/18 11:17AM --- processing.html.markdown | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 83f774ee..f352b9c4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -108,7 +108,7 @@ ArrayList intArrayList = new ArrayList(); // Format --> ClassName InstanceName SomeRandomClass myObject // then instantiate later //or -SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. @@ -135,15 +135,18 @@ float sr = sqrt(25); // sr = 5.0 // Vectors // Processing provides an easy way to implement vectors in its environment using PVector class. -// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. -// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) +// It can describe a two or three dimensional vector and +// comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. +// (https://processing.org/reference/PVector.html) // Trigonometry // Processing also supports trigonometric operations by supplying a set of functions. // sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. -// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +// However, those functions take angle in radians as the parameter so it has to be converted beforehand. float one = sin(PI/2); // one = 1.0 -// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... +// As you may have noticed, there exists a set of constants for trigonometric uses; +// PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From e7603786a8fcb88508b1298053c2a78ad65c9ed7 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:50:32 +0630 Subject: 2/7/18 11:50AM --- processing.html.markdown | 73 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index f352b9c4..91d75cb4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -54,9 +54,9 @@ void draw() { // Now that we know how to write the working script and how to run it, // we will proceed to explore what data types and collections are supported in Processing. -/* ----------------------- - Datatypes & collections - ------------------------ +/* ------------------------ + Datatypes & collections + ------------------------ */ // According to Processing References, Processing supports 8 primitive datatypes as follows. @@ -113,10 +113,11 @@ SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. -/* ----------- - Maths - ------------ +/* ------------ + Maths + ------------ */ + // Arithmetic 1 + 1 // 2 2 - 1 // 0 @@ -148,6 +149,66 @@ float one = sin(PI/2); // one = 1.0 // As you may have noticed, there exists a set of constants for trigonometric uses; // PI, HALF_PI, QUARTER_PI and so on... +/* ------------- + Control Flow + ------------- +*/ + +// Conditional Statements +// If Statements - The same syntax as if statements in Java. +if (author.getAppearance().equals("hot")) { + print("Narcissism at its best!"); +} else { + // You can check for other conditions here. + print("Something is really wrong here!"); +} +// A shortcut for if-else statements can also be used. +int i = 3; +String value = (i > 5) ? "Big" : "Small"; // "Small" + +// Switch-case structure can be used to check multiple conditions more concisely. +int value = 2; +switch(value) { + case 0: + print("Nought!"); // This doesn't get executed. + break; // Jumps to the next statement + case 1: + print("Getting there..."); // This again doesn't get executed. + break; + case 2: + print("Bravo!"); // This line gets executed. + break; + default: + print("Not found!"); // This line gets executed if our value was some other value. + break; +} + +// Iterative statements +// For Statements - Again, the same syntax as in Java +for(int i = 0; i < 5; i ++){ + print(i); // prints from 0 to 4 +} + +// While Statements - Again, nothing new if you are familiar with Java syntax. +int j = 3; +while(j > 0) { + print(j); + j--; // This is important to prevent from the code running indefinitely. +} + +// loop()| noLoop() | redraw() | exit() +// These are more of Processing-specific functions to configure program flow. +loop(); // allows the draw() method to run forever while +noLoop(); // only allows it to run once. +redraw(); // runs the draw() method once more. +exit(); // This stops the program. It is useful for programs with draw() running continuously. +``` +Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. + +```processing + + + ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of -- cgit v1.2.3 From 90ee44541ef66d4f8d0507c1b2080cf409078064 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 12:15:25 +0630 Subject: 2/7/18 12:15PM --- processing.html.markdown | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 91d75cb4..6423baa7 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -203,9 +203,44 @@ noLoop(); // only allows it to run once. redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` +## Drawing with Processing Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. ```processing +/* ------ + Shapes + ------ +*/ + +// 2D Shapes + +// Point +point(x, y); // In 2D space +point(x, y, z); // In 3D space +// Draws a point in the coordinate space. + +// Line +line(x1, y1, x2, y2); // In 2D space +line(x1, y1, z1, x2, y2, z2); // In 3D space +// Draws a line connecting two points defined by (x1, y1) and (x2, y2) + +// Rectangle +rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners +rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +// Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. + +// Quad +quad(x,y,x2,y2,x3,y3,x4,y4) +// Draws a quadrilateral with parameters defining coordinates of each corner point. + +// Arc; +arc(x, y, width, height, start, stop, [mode]); +// While the first four parameters are self-explanatory, +// start and end defined the angles the arc starts and ends (in radians). +// Optional parameter [mode] defines the filling; +// PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes + + -- cgit v1.2.3 From fa305fc98763d4c2cd204cfe9b5f0bc59daefc14 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 14:55:22 +0630 Subject: 2/7/18 2:55PM --- processing.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 6423baa7..88c7c289 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -40,6 +40,8 @@ void setup() { // Normally, we put all the static codes inside the setup() method as the name suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. +background(color); // setting the background colour +size(width,height,[renderer]); // setting the canvas size with optional parameter defining renderer // You will see more of them throughout this document. // If you want to run the codes indefinitely, it has to be placed in draw() method. @@ -204,7 +206,7 @@ redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` ## Drawing with Processing -Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. +Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing /* ------ @@ -222,27 +224,99 @@ point(x, y, z); // In 3D space // Line line(x1, y1, x2, y2); // In 2D space line(x1, y1, z1, x2, y2, z2); // In 3D space -// Draws a line connecting two points defined by (x1, y1) and (x2, y2) +// Draws a line connecting two points defined by (x1, y1) and (x2, y2). + +// Triangle +triangle(x1, y1, x2, y2, x3, y3); +// Draws a triangle connecting three points defined by coordinate paramters. // Rectangle rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners -rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +rect(a, b, c, d, [tl, tr, br, bl]); // With optional set of parameters defining radius of each corner // Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. // Quad -quad(x,y,x2,y2,x3,y3,x4,y4) +quad(x, y, x2, y2, x3, y3, x4, y4); // Draws a quadrilateral with parameters defining coordinates of each corner point. -// Arc; +// Ellipse +ellipse(x, y, width, height); +// Draws an eclipse at point {x, y} with width and height specified. + +// Arc arc(x, y, width, height, start, stop, [mode]); // While the first four parameters are self-explanatory, // start and end defined the angles the arc starts and ends (in radians). // Optional parameter [mode] defines the filling; // PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes +// Curves +// Processing provides two implementation of curves; using curve() and bezier(). +// Since I plan to keep this simple I won't be discussing any further details. +// However, if you want to implement it in your sketch, here are the references: +// (https://processing.org/reference/curve_.html)(https://processing.org/reference/bezier_.html) + +// 3D Shapes + +// 3D space can be configured by setting "P3D" to the renderer parameter in size() method. +size(width, height, P3D); +// In 3D space, you will have to translate to the particular coordinate to render the 3D shapes. +// Box +box(size); // Cube with same length defined by size +box(w, h, d); // Box with width, height and depth separately defined +// Sphere +sphere(radius); // Its size is defined using the radius parameter +// Mechanism behind rendering spheres is implemented by tessellating triangles. +// That said, how much detail being rendered is controlled by function sphereDetail(res) +// More information here: (https://processing.org/reference/sphereDetail_.html) + +// Irregular Shapes +// What if you wanted to draw something that's not made available by Processing's functions? +// You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. +// More information here: (https://processing.org/reference/beginShape_.html) + +/* --------------- + Transformations + --------------- +*/ + +// Transformations are particularly useful to keep track of the coordinate space +// and the vertices of the shapes you have drawn. +// Particularly, matrix stack methods; pushMatrix(), popMatrix() and translate(x,y) +pushMatrix(); // Saves the current coordinate system to the stack +// ... apply all the transformations here ... +popMatrix(); // Restores the saved coordinate system +// Using them, the coordinate system can be preserved and visualized without causing any conflicts. + +// Translate +translate(x, y); // Translates to point{x, y} i.e. - setting origin to that point +translate(x, y, z); // 3D counterpart of the function + +// Rotate +rotate(angle); // Rotate the amount specified by the angle parameter +// It has 3 3D counterparts to perform rotation, each for every dimension, +// namely: rotateX(angle), rotateY(angle), rotateZ(angle) + +// Scale +scale(s); // Scale the coordinate system by either expanding or contracting it. + +/* -------------------- + Styling and Textures + -------------------- +*/ + + + +/* ------- + Imports + ------- +*/ +// The power of Processing can be further visualized when we import libraries and packages into our sketches. +// Import statement can be written as below at the top of the source code. +import processing.something.*; ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From 66c6297749cbff4272a12b852741c365bec9149a Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 15:18:30 +0630 Subject: 2/7/18 3:18PM --- processing.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 88c7c289..e3d83f80 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -209,6 +209,7 @@ exit(); // This stops the program. It is useful for programs with draw() running Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing + /* ------ Shapes ------ @@ -276,6 +277,7 @@ sphere(radius); // Its size is defined using the radius parameter // What if you wanted to draw something that's not made available by Processing's functions? // You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. // More information here: (https://processing.org/reference/beginShape_.html) +// You can also use custom made shapes using PShape class.(https://processing.org/reference/PShape.html) /* --------------- Transformations @@ -307,7 +309,30 @@ scale(s); // Scale the coordinate system by either expanding or contracting it. -------------------- */ +// Colours +// As I have discussed earlier, the background colour can be configured using background() function. +// You can define a color object beforehand and then pass it to the function as an argument. +color c = color(255, 255, 255); // WHITE! +// By default, Processing uses RGB colour scheme but it can be configured to HSB using colorMode(). +// Read here: (https://processing.org/reference/colorMode_.html) +background(color); // By now, the background colour should be white. +// You can use fill() function to select the colour for filling the shapes. +// It has to be configured before you start drawing shapes so the colours gets applied. +fill(color(0, 0, 0)); +// If you just want to colour the outlines of the shapes then you can use stroke() function. +stroke(255, 255, 255, 200); // stroke colour set to yellow with transparency set to a lower value. + +// Images +// Processing can render images and use them in several ways. Mostly stored as PImage datatype. +filter(shader); // Processing supports several filter functions for image manipulation. +texture(image); // PImage can be passed into arguments for texture-mapping the shapes. +``` +If you want to take things further, there are more things Processing is powered for. Rendering models, shaders and whatnot. +There's too much to cover in a short documentation, so I will leave them out here. Shoud you be interested, please check out the references. +```processing +// Before we move on, I will touch a little bit more on how to import libraries +// so you can extend Processing's functionality to another horizon. /* ------- Imports -- cgit v1.2.3 From fb78575d55b64860d781e651b3b958d8ba04bdf4 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 16:15:09 +0630 Subject: 2/7/18 4:14PM --- processing.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/processing.html.markdown b/processing.html.markdown index e3d83f80..84c2dee1 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -344,11 +344,76 @@ There's too much to cover in a short documentation, so I will leave them out her import processing.something.*; ``` +## DTC? + +Down To Code? Let's get our hands dirty! + +Let us see an example from openprocessing to visualize how much Processing is capable of within few lines of code. +Copy the code below into your Processing IDE and see the magic. + +```processing + +// Disclaimer: I did not write this program since I currently am occupied with internship and +// this sketch is adapted from openprocessing since it shows something cool with simple codes. +// Retrieved from: (https://www.openprocessing.org/sketch/559769) + +float theta; +float a; +float col; +float num; + +void setup() { + size(600,600); +} + +void draw() { + background(#F2F2F2); + translate(width/2, height/2); + theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6); + + float num=6; + for (int i=0; i30) { + pushMatrix(); + translate(0, -30); + rotate(theta); + branch(len); + popMatrix(); + + pushMatrix(); + translate(0, -30); + rotate(-theta); + branch(len); + popMatrix(); + + } +} + +``` + Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of the program flow. However, that does not apply when you introduce external libraries, packages and even your own classes. -(Trust me! Processing projects can get really large) +(Trust me! Processing projects can get real humongous...) ## What's Next? -- cgit v1.2.3 From e42e4b9b22d6d1e267d5c5931dd40f050401ba44 Mon Sep 17 00:00:00 2001 From: Fake4d Date: Tue, 3 Jul 2018 16:16:17 +0200 Subject: Update bash-de.html.markdown Variable was not initialised in this stage for this loop - Removed the $ --- de-de/bash-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 7928b136..7a0db157 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -180,7 +180,7 @@ esac # 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: # Der Inhalt von $Variable wird dreimal ausgedruckt. -for $Variable in {1..3} +for Variable in {1..3} do echo "$Variable" done -- cgit v1.2.3 From 626af76c4d38a705f35e0c07b877404c03fa6b1d Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 17:08:23 +0800 Subject: create learnawk-cn.awk --- zh-cn/awk-cn.html.markdown | 361 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 zh-cn/awk-cn.html.markdown diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown new file mode 100644 index 00000000..fcd17b4f --- /dev/null +++ b/zh-cn/awk-cn.html.markdown @@ -0,0 +1,361 @@ +--- +language: awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Tian Zhipeng", "https://github.com/tianzhipeng-git"] +filename: learnawk-cn.awk +lang: zh-cn +--- + +AWK is a standard tool on every POSIX-compliant UNIX system. It's like a +stripped-down Perl, perfect for text-processing tasks and other scripting +needs. It has a C-like syntax, but without semicolons, manual memory +management, or static typing. It excels at text processing. You can call to it +from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always +count on it, whereas Perl's future is in question. AWK is also easier to read +than Perl. For simple text-processing scripts, particularly ones that read +files line by line and split on delimiters, AWK is probably the right tool for +the job. + +```awk +#!/usr/bin/awk -f + +# Comments are like this + +# AWK programs consist of a collection of patterns and actions. The most +# important pattern is called BEGIN. Actions go into brace blocks. +BEGIN { + + # BEGIN will run at the beginning of the program. It's where you put all + # the preliminary set-up code, before you process any text files. If you + # have no text files, then think of BEGIN as the main entry point. + + # Variables are global. Just set them or use them, no need to declare.. + count = 0 + + # Operators just like in C and friends + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 # integer division + e = count % 1 # modulus + f = count ^ 1 # exponentiation + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementing and decrementing by one + a++ + b-- + + # As a prefix operator, it returns the incremented value + ++a + --b + + # Notice, also, no punctuation such as semicolons to terminate statements + + # Control statements + if (count == 0) + print "Starting with count of 0" + else + print "Huh?" + + # Or you could use the ternary operator + print (count == 0) ? "Starting with count of 0" : "Huh?" + + # Blocks consisting of multiple lines use braces + while (a < 10) { + print "String concatenation is done" " with a series" " of" + " space-separated strings" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Good ol' for loop" + + # As for comparisons, they're the standards: + a < b # Less than + a <= b # Less than or equal + a != b # Not equal + a == b # Equal + a > b # Greater than + a >= b # Greater than or equal + + # Logical operators as well + a && b # AND + a || b # OR + + # In addition, there's the super useful regular expression match + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Arrays + arr[0] = "foo" + arr[1] = "bar" + # Unfortunately, there is no other way to initialize an array. Ya just + # gotta chug through every value line by line like that. + + # You also have associative arrays + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # And multi-dimensional arrays, with some limitations I won't mention here + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # You can test for array membership + if ("foo" in assoc) + print "Fooey!" + + # You can also use the 'in' operator to traverse the keys of an array + for (key in assoc) + print assoc[key] + + # The command line is in a special array called ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # You can remove elements of an array + # This is particularly useful to prevent AWK from assuming the arguments + # are files for it to process + delete ARGV[1] + + # The number of command line arguments is in a variable called ARGC + print ARGC + + # AWK has several built-in functions. They fall into three categories. I'll + # demonstrate each of them in their own functions, defined later. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Here's how you define a function +function arithmetic_functions(a, b, c, d) { + + # Probably the most annoying part of AWK is that there are no local + # variables. Everything is global. For short scripts, this is fine, even + # useful, but for longer scripts, this can be a problem. + + # There is a work-around (ahem, hack). Function arguments are local to the + # function, and AWK allows you to define more function arguments than it + # needs. So just stick local variable in the function declaration, like I + # did above. As a convention, stick in some extra whitespace to distinguish + # between actual function parameters and local variables. In this example, + # a, b, and c are actual parameters, while d is merely a local variable. + + # Now, to demonstrate the arithmetic functions + + # Most AWK implementations have some standard trig functions + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arc tangent of b / a + + # And logarithmic stuff + localvar = exp(a) + localvar = log(a) + + # Square root + localvar = sqrt(a) + + # Truncate floating point to integer + localvar = int(5.34) # localvar => 5 + + # Random numbers + srand() # Supply a seed as an argument. By default, it uses the time of day + localvar = rand() # Random number between 0 and 1. + + # Here's how to return a value + return localvar +} + +function string_functions( localvar, arr) { + + # AWK, being a string-processing language, has several string-related + # functions, many of which rely heavily on regular expressions. + + # Search and replace, first instance (sub) or all instances (gsub) + # Both return number of matches replaced + 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" + + # Search for a string that matches a regular expression + # index() does the same thing, but doesn't allow a regular expression + match(localvar, "t") # => 4, since the 't' is the fourth character + + # Split on a delimiter + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Other useful stuff + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # You've already seen print + print "Hello world" + + # There's also printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # 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: + + print "foobar" >"/tmp/foobar.txt" + + # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + close("/tmp/foobar.txt") + + # Here's how you run something in the shell + system("echo foobar") # => prints foobar + + # Reads a line from standard input and stores in localvar + getline localvar + + # Reads a line from a pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Reads a line from a file and stores in localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# As I said at the beginning, AWK programs consist of a collection of patterns +# and actions. You've already seen the all-important BEGIN pattern. Other +# patterns are used only if you're processing lines from files or standard +# input. +# +# 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. + +/^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: + + print + + # Whoa, no argument! That's because print has a default argument: $0. + # $0 is the name of the current line being processed. It is created + # automatically for you. + + # You can probably guess there are other $ variables. Every line is + # implicitly split before every action is called, much like the shell + # does. And, like the shell, each field can be access with a dollar sign + + # This will print the second and fourth fields in the line + print $2, $4 + + # AWK automatically defines many other variables to help you inspect and + # process each line. The most important one is NF + + # Prints the number of fields on this line + print NF + + # Print the last field on this line + print $NF +} + +# Every pattern is actually a true/false test. The regular expression in the +# last pattern is also a true/false test, but part of it was hidden. If you +# don't give it a string to test, it will assume $0, the line that it's +# currently processing. Thus, the complete version of it is this: + +$0 ~ /^fo+bar$/ { + print "Equivalent to the last pattern" +} + +a > 0 { + # This will execute once for each line, as long as a is positive +} + +# You get the idea. Processing text files, reading in a line at a time, and +# doing something with it, particularly splitting on a delimiter, is so common +# in UNIX that AWK is a scripting language that does all of it for you, without +# you needing to ask. All you have to do is write the patterns and actions +# based on what you expect of the input, and what you want to do with it. + +# Here's a quick example of a simple script, the sort of thing AWK is perfect +# for. It will read a name from standard input and then will print the average +# age of everyone with that first name. Let's say you supply as an argument the +# name of a this data file: +# +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Here's the script: + +BEGIN { + + # First, ask the user for the name + print "What name would you like the average age for?" + + # Get a line from standard input, not from files on the command line + getline name <"/dev/stdin" +} + +# Now, match every line whose first field is the given name +$1 == name { + + # Inside here, we have access to a number of useful variables, already + # pre-loaded for us: + # $0 is the entire line + # $3 is the third field, the age, which is what we're interested in here + # NF is the number of fields, which should be 3 + # NR is the number of records (lines) seen so far + # FILENAME is the name of the file being processed + # FS is the field separator being used, which is " " here + # ...etc. There are plenty more, documented in the man page. + + # Keep track of a running total and how many lines matched + sum += $3 + nlines++ +} + +# Another special pattern is called END. It will run after processing all the +# text files. Unlike BEGIN, it will only run if you've given it input to +# process. It will run after all the files have been read and processed +# according to the rules and actions you've provided. The purpose of it is +# usually to output some kind of final report, or do something with the +# aggregate of the data you've accumulated over the course of the script. + +END { + if (nlines) + print "The average age for " name " is " sum / nlines +} + +``` +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. -- cgit v1.2.3 From 6261f85b2fea138eae3825e0c6837fc6f1d398b2 Mon Sep 17 00:00:00 2001 From: luffy_zhong Date: Wed, 4 Jul 2018 17:10:32 +0800 Subject: Update the translation The translation is outdated, so I try to update it. --- zh-cn/markdown-cn.html.markdown | 238 +++++++++++++++++++++++++++------------- 1 file changed, 164 insertions(+), 74 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index e9a8aeb2..82b7a922 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -10,39 +10,56 @@ lang: zh-cn Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。 -欢迎您多多反馈以及分支和请求合并。 - +在不同的解析器中,Markdown 的实现方法有所不同。 +此教程会指出哪些特征是通用,哪一些只对某一解析器有效。 + +- [HTML标签](#html-elements) +- [标题](#headings) +- [文本样式](#simple-text-styles) +- [段落](#paragraphs) +- [列表](#lists) +- [代码块](#code-blocks) +- [水平线分隔](#horizontal-rule) +- [链接](#links) +- [图片](#images) +- [杂项](#miscellany) + +## HTML标签 +Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。 ```md - +``` - +## 标题 - - +通过在文本前加上不同数量的hash(#), 你可以创建相对应的 `

` 到 `

` HTML元素。 +```md # 这是一个

## 这是一个

### 这是一个

#### 这是一个

##### 这是一个

###### 这是一个
+``` +对于 `

` 和 `

` 元素,Markdown 额外提供了两种添加方式。 - +```md 这是一个 h1 ============= 这是一个 h2 ------------- +``` + +## 文本样式 - - +文本的斜体,粗体在 Markdown 中可以轻易实现。 +```md *此文本为斜体。* _此文本也是。_ @@ -52,40 +69,54 @@ __此文本也是__ ***此文本是斜体加粗体。*** **_或者这样。_** *__这个也是!__* +``` - +GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以使用删除线: +```md ~~此文本为删除线效果。~~ +``` +## 段落 - +Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. +段落由一个句子或是多个中间没有空行的句子组成,每个段落由一个或是多个空行分隔开来。 +```md 这是第一段落. 这句话在同一个段落里,好玩么? 现在我是第二段落。 这句话也在第二段落! + 这句话在第三段落! +``` - +如果你插入一个 HTML中的
标签,你可以在段末加入两个以上的空格,然后另起一段。 +(译者注:试了一下,很多解析器,并不需要空两个空格,直接换行就会添加一个`
`) +```md 此段落结尾有两个空格(选中以显示)。 上文有一个
! +``` - +段落引用可由 `>` 字符轻松实现。 -> 这是一个段落引用. 你可以 -> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 -> 只要你的文字以“>” 字符开头,两种方式无异。 +```md +> 这是一个段落引用。 你可以 +> 手动断开你的句子,然后在每句句子前面添加 `>` 字符。或者让你的句子变得很长,以至于他们自动得换行。 +> 只要你的文字以 `>` 字符开头,两种方式无异。 -> 你也对文本进行 +> 你也可以对文本进行 >> 多层引用 > 这多机智啊! +``` - - +## 列表 +无序列表可由星号,加号或者减号来创建 +```md * 项目 * 项目 * 另一个项目 @@ -102,139 +133,198 @@ __此文本也是__ - 项目 - 最后一个项目 - +``` +有序序列可由数字加上点 `.` 来实现 + +```md 1. 项目一 2. 项目二 3. 项目三 +``` - +即使你的标签数字有误,Markdown 依旧会呈现出正确的序号, +不过这并不是一个好主意 +```md 1. 项目一 1. 项目二 1. 项目三 - +``` +(此段与上面一模一样) - +你也可以使用子列表 +```md 1. 项目一 2. 项目二 3. 项目三 * 子项目 * 子项目 4. 项目四 +``` + +你甚至可以使用任务列表,它将会生成 HTML 的选择框(checkboxes)标签。 + +```md +下面方框里包含 'x' 的列表,将会生成选中效果的选择框。 +- [ ] 任务一需要完成 +- [ ] 任务二需要完成 +下面这个选择框将会是选中状态 +- [x] 这个任务已经完成 +``` + +## 代码块 - - +代码块(HTML中 标签)可以由缩进四格(spaces) +或者一个制表符(tab)实现 +```md This is code So is this +``` - +在你的代码中,你仍然使用tab(或者四个空格)可以进行缩进操作 +```md my_array.each do |item| puts item end +``` - +内联代码可由反引号 ` 实现 +```md John 甚至不知道 `go_to()` 方程是干嘛的! +``` - +在GitHub的 Markdown(GitHub Flavored Markdown)解析器中,你可以使用特殊的语法表示代码块 -\`\`\`ruby +
+```ruby
 def foobar
     puts "Hello world!"
 end
-\`\`\` 
+```
+ +以上代码不需要缩进,而且 GitHub 会根据\`\`\`后指定的语言来进行语法高亮显示 - +## 水平线分隔 - - +Horizontal rules (`
`) are easily added with three or more asterisks or +hyphens, with or without spaces. +水平线可由三个或以上的星号或是减号创建,它们之间可以带或不带空格 +```md *** --- - - - **************** +``` - - +## 链接 +Markdown 最棒的地方就是便捷的书写链接。把链接文字放在中括号[]内, +在随后的括弧()内加入url就可以了。 + +```md [点我点我!](http://test.com/) - +``` +You can also add a link title using quotes inside the parentheses. +你也可以为链接加入一个标题:在括弧号内使用引号 +你也可以在小括号内使用引号,为链接加上一个标题(title) +```md [点我点我!](http://test.com/ "连接到Test.com") +``` +相对路径也可以有 - - +```md [去 music](/music/). +``` - +Markdown同样支持引用形式的链接 -[点此链接][link1]以获取更多信息! -[看一看这个链接][foobar] 如果你愿意的话. +
[点此链接][link1] 以获取更多信息!
+[看一看这个链接][foobar] 如果你愿意的话。
 
-[link1]: http://test.com/ "Cool!"
-[foobar]: http://foobar.biz/ "Alright!"
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
- +对于引用形式,链接的标题可以处于单引号中,括弧中或是忽略。引用名可以在文档的任意何处, +并且可以随意命名,只要名称不重复。 - +“隐含式命名” 的功能可以让链接文字作为引用名 -[This][] is a link. +
[This][] is a link.
 
-[this]: http://thisisalink.com/
+[this]: http://thisisalink.com/
- +但这并不常用 - - +## 图片 +图片与链接相似,只需在前添加一个感叹号 -![这是我图像的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") +```md +![这是我图片的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") +``` - +引用形式也同样起作用 -![这是我的悬停文本.][myimage] +
![这是我的悬停文本.][myimage]
 
-[myimage]: relative/urls/cool/image.jpg "在此输入标题"
+[myimage]: relative/urls/cool/image.jpg "在此输入标题"
- - +## 杂项 +### 自动链接 +```md 与 [http://testwebsite.com/](http://testwebsite.com/) 等同 +``` - +### 电子邮件的自动链接 +```md +``` - +### 转义字符 +```md 我希望 *将这段文字置于星号之间* 但是我不希望它被 -斜体化, 所以我就: \*这段置文字于星号之间\*。 +斜体化, 这么做: \*这段置文字于星号之间\*。 +``` + +### 键盘上的功能键 - - +In GitHub Flavored Markdown, you can use a `` tag to represent keyboard +keys. +在 GitHub 的 Markdown中,你可以使用 `` 标签来表示功能键。 +```md +你的电脑死机了?试试 +Ctrl+Alt+Del +``` + +### 表格 + +表格只被 GitHub 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: (译者注:其实现在大部分markdown都已经支持) + +```md | 第一列 | 第二列 | 第三列 | -| :---------- | :------: | ----------: | +| :--------- | :------: | ----------: | | 左对齐 | 居个中 | 右对齐 | | 某某某 | 某某某 | 某某某 | +``` - +或者, 同样的 +```md 第一列 | 第二列 | 第三列 :-- | :-: | --: 这太丑了 | 药不能 | 停 - - - ``` 更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 -- cgit v1.2.3 From 7bc6fc51793b14326fff89433e73da36ff2fbd90 Mon Sep 17 00:00:00 2001 From: luffy_zhong Date: Wed, 4 Jul 2018 17:16:23 +0800 Subject: Update markdown-cn.html.markdown --- zh-cn/markdown-cn.html.markdown | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 82b7a922..4ca8b0f0 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen","https://github.com/FZSS"] + - ["Luffy Zhong", "https://github.com/mengzhongshi"] filename: learnmarkdown-cn.md lang: zh-cn --- @@ -13,16 +14,16 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 在不同的解析器中,Markdown 的实现方法有所不同。 此教程会指出哪些特征是通用,哪一些只对某一解析器有效。 -- [HTML标签](#html-elements) -- [标题](#headings) -- [文本样式](#simple-text-styles) -- [段落](#paragraphs) -- [列表](#lists) -- [代码块](#code-blocks) -- [水平线分隔](#horizontal-rule) -- [链接](#links) -- [图片](#images) -- [杂项](#miscellany) +- [HTML标签](#HTML标签) +- [标题](#标题) +- [文本样式](#文本样式) +- [段落](#段落) +- [列表](#列表) +- [代码块](#代码块) +- [水平线分隔](#水平线分隔) +- [链接](#链接) +- [图片](#图片) +- [杂项](#杂项) ## HTML标签 Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。 -- cgit v1.2.3 From 5ffd3c83590aa809066567aca55bcdd5f9383baf Mon Sep 17 00:00:00 2001 From: luffy_zhong Date: Wed, 4 Jul 2018 17:45:21 +0800 Subject: Update translation Update translation --- zh-cn/markdown-cn.html.markdown | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 4ca8b0f0..e5996984 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Fangzhou Chen","https://github.com/FZSS"] - - ["Luffy Zhong", "https://github.com/mengzhongshi"] + - ["Luffy Zhong", "https://github.com/mengzhongshi"] filename: learnmarkdown-cn.md lang: zh-cn --- @@ -79,8 +79,6 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以 ``` ## 段落 -Paragraphs are a one or multiple adjacent lines of text separated by one or -multiple blank lines. 段落由一个句子或是多个中间没有空行的句子组成,每个段落由一个或是多个空行分隔开来。 ```md @@ -93,8 +91,8 @@ multiple blank lines. 这句话在第三段落! ``` -如果你插入一个 HTML中的
标签,你可以在段末加入两个以上的空格,然后另起一段。 -(译者注:试了一下,很多解析器,并不需要空两个空格,直接换行就会添加一个`
`) +如果你想插入一个 `
` 标签,你可以在段末加入两个以上的空格,然后另起一 +段。(译者注:试了一下,很多解析器,并不需要空两个空格,直接换行就会添加一个`
`) ```md 此段落结尾有两个空格(选中以显示)。 @@ -144,7 +142,7 @@ multiple blank lines. 3. 项目三 ``` -即使你的标签数字有误,Markdown 依旧会呈现出正确的序号, +即使你的数字标签有误,Markdown 依旧会呈现出正确的序号, 不过这并不是一个好主意 ```md @@ -152,7 +150,7 @@ multiple blank lines. 1. 项目二 1. 项目三 ``` -(此段与上面一模一样) +(此段与上面效果一模一样) 你也可以使用子列表 @@ -177,12 +175,12 @@ multiple blank lines. ## 代码块 -代码块(HTML中 标签)可以由缩进四格(spaces) +代码块(HTML中 `` 标签)可以由缩进四格(spaces) 或者一个制表符(tab)实现 ```md This is code - So is this + So is this ``` 在你的代码中,你仍然使用tab(或者四个空格)可以进行缩进操作 @@ -212,9 +210,7 @@ end ## 水平线分隔 -Horizontal rules (`
`) are easily added with three or more asterisks or -hyphens, with or without spaces. -水平线可由三个或以上的星号或是减号创建,它们之间可以带或不带空格 +水平线(`
`)可由三个或以上的星号或是减号创建,它们之间可以带或不带空格 ```md *** @@ -232,8 +228,7 @@ Markdown 最棒的地方就是便捷的书写链接。把链接文字放在中 [点我点我!](http://test.com/) ``` -You can also add a link title using quotes inside the parentheses. -你也可以为链接加入一个标题:在括弧号内使用引号 + 你也可以在小括号内使用引号,为链接加上一个标题(title) ```md @@ -253,8 +248,7 @@ Markdown同样支持引用形式的链接 [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!"
-对于引用形式,链接的标题可以处于单引号中,括弧中或是忽略。引用名可以在文档的任意何处, -并且可以随意命名,只要名称不重复。 +对于引用形式,链接的标题可以处于单引号中,括弧中或是忽略。引用名可以在文档的任何地方,并且可以随意命名,只要名称不重复。 “隐含式命名” 的功能可以让链接文字作为引用名 @@ -268,12 +262,12 @@ Markdown同样支持引用形式的链接 图片与链接相似,只需在前添加一个感叹号 ```md -![这是我图片的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") +![这是alt,请把鼠标放在图片上](http://imgur.com/myimage.jpg "这是title") ``` 引用形式也同样起作用 -
![这是我的悬停文本.][myimage]
+
![这是alt][myimage]
 
 [myimage]: relative/urls/cool/image.jpg "在此输入标题"
@@ -300,15 +294,13 @@ Markdown同样支持引用形式的链接 ### 键盘上的功能键 -In GitHub Flavored Markdown, you can use a `` tag to represent keyboard -keys. 在 GitHub 的 Markdown中,你可以使用 `` 标签来表示功能键。 ```md 你的电脑死机了?试试 Ctrl+Alt+Del ``` - +Ctrl+Alt+Del ### 表格 表格只被 GitHub 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: (译者注:其实现在大部分markdown都已经支持) -- cgit v1.2.3 From 72ab89ea9a2fb41ca685248e6cac89c5e153d16b Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 21:56:04 +0800 Subject: translate awk to zh-cn --- zh-cn/awk-cn.html.markdown | 277 ++++++++++++++++++++------------------------- 1 file changed, 120 insertions(+), 157 deletions(-) diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index fcd17b4f..1fafa559 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -8,41 +8,35 @@ filename: learnawk-cn.awk lang: zh-cn --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read -than Perl. For simple text-processing scripts, particularly ones that read -files line by line and split on delimiters, AWK is probably the right tool for -the job. +AWK是POSIX兼容的UNIX系统中的标准工具. 它像简化版的Perl, 非常适用于文本处理任务和其他脚本类需求. +它有着C风格的语法, 但是没有分号, 没有手动内存管理, 没有静态类型. +他擅长于文本处理, 你可以通过shell脚本调用AWK, 也可以用作独立的脚本语言. + +为什么使用AWK而不是Perl, 大概是因为AWK是UNIX的一部分, 你总能依靠它, 而Perl已经前途未卜了. +AWK比Perl更易读. 对于简单的文本处理脚本, 特别是按行读取文件, 按分隔符分隔处理, AWK极可能是正确的工具. ```awk #!/usr/bin/awk -f -# Comments are like this +# 注释使用井号 -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. +# AWK程序由一系列 模式(patterns) 和 动作(actions) 组成. +# 最重要的模式叫做 BEGIN. 动作由大括号包围. BEGIN { - # BEGIN will run at the beginning of the program. It's where you put all - # the preliminary set-up code, before you process any text files. If you - # have no text files, then think of BEGIN as the main entry point. + # BEGIN在程序最开始运行. 在这里放一些在真正处理文件之前的准备和setup的代码. + # 如果没有文本文件要处理, 那就把BEGIN作为程序的主入口吧. - # Variables are global. Just set them or use them, no need to declare.. + # 变量是全局的. 直接赋值使用即可, 无需声明. count = 0 - # Operators just like in C and friends + # 运算符和C语言系一样 a = count + 1 b = count - 1 c = count * 1 - d = count / 1 # integer division - e = count % 1 # modulus - f = count ^ 1 # exponentiation + d = count / 1 # 整数除法 + e = count % 1 # 取余 + f = count ^ 1 # 取幂 a += 1 b -= 1 @@ -51,26 +45,26 @@ BEGIN { e %= 1 f ^= 1 - # Incrementing and decrementing by one + # 自增1, 自减1 a++ b-- - # As a prefix operator, it returns the incremented value + # 前置运算, 返回增加之后的值 ++a --b - # Notice, also, no punctuation such as semicolons to terminate statements + # 注意, 不需要分号之类的标点来分隔语句 - # Control statements + # 控制语句 if (count == 0) print "Starting with count of 0" else print "Huh?" - # Or you could use the ternary operator + # 或者三目运算符 print (count == 0) ? "Starting with count of 0" : "Huh?" - # Blocks consisting of multiple lines use braces + # 多行的代码块用大括号包围 while (a < 10) { print "String concatenation is done" " with a series" " of" " space-separated strings" @@ -82,126 +76,118 @@ BEGIN { for (i = 0; i < 10; i++) print "Good ol' for loop" - # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal + # 标准的比较运算符 + a < b # 小于 + a <= b # 小于或等于 + a != b # 不等于 + a == b # 等于 + a > b # 大于 + a >= b # 大于或等于 - # Logical operators as well - a && b # AND - a || b # OR + # 也有逻辑运算符 + a && b # 且 + a || b # 或 - # In addition, there's the super useful regular expression match + # 并且有超实用的正则表达式匹配 if ("foo" ~ "^fo+$") print "Fooey!" if ("boo" !~ "^fo+$") print "Boo!" - # Arrays + # 数组 arr[0] = "foo" arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. + # 不幸的是, 没有其他方式初始化数组. 必须像这样一行一行的赋值. - # You also have associative arrays + # 关联数组, 类似map或dict的用法. assoc["foo"] = "bar" assoc["bar"] = "baz" - # And multi-dimensional arrays, with some limitations I won't mention here + # 多维数组. 但是有一些局限性这里不提了. multidim[0,0] = "foo" multidim[0,1] = "bar" multidim[1,0] = "baz" multidim[1,1] = "boo" - # You can test for array membership + # 可以检测数组包含关系 if ("foo" in assoc) print "Fooey!" - # You can also use the 'in' operator to traverse the keys of an array + # 可以使用in遍历数组 for (key in assoc) print assoc[key] - # The command line is in a special array called ARGV + # 命令行参数是一个叫ARGV的数组 for (argnum in ARGV) print ARGV[argnum] - # You can remove elements of an array - # This is particularly useful to prevent AWK from assuming the arguments - # are files for it to process + # 可以从数组中移除元素 + # 在 防止awk把文件参数当做数据来处理 时delete功能很有用. delete ARGV[1] - # The number of command line arguments is in a variable called ARGC + # 命令行参数的个数是一个叫ARGC的变量 print ARGC - # AWK has several built-in functions. They fall into three categories. I'll - # demonstrate each of them in their own functions, defined later. + # AWK有很多内置函数, 分为三类, 会在接下来定义的各个函数中介绍. return_value = arithmetic_functions(a, b, c) string_functions() io_functions() } -# Here's how you define a function +# 定义函数 function arithmetic_functions(a, b, c, d) { - # Probably the most annoying part of AWK is that there are no local - # variables. Everything is global. For short scripts, this is fine, even - # useful, but for longer scripts, this can be a problem. + # 或许AWK最让人恼火的地方是没有局部变量, 所有东西都是全局的, + # 对于短的脚本还好, 对于长一些的就会成问题. - # There is a work-around (ahem, hack). Function arguments are local to the - # function, and AWK allows you to define more function arguments than it - # needs. So just stick local variable in the function declaration, like I - # did above. As a convention, stick in some extra whitespace to distinguish - # between actual function parameters and local variables. In this example, - # a, b, and c are actual parameters, while d is merely a local variable. + # 这里有一个技巧, 函数参数是对函数局部可见的, 并且AWK允许定义多余的参数, + # 因此可以像上面那样把局部变量插入到函数声明中. + # 为了方便区分普通参数(a,b,c)和局部变量(d), 可以多键入一些空格. - # Now, to demonstrate the arithmetic functions + # 现在介绍数学类函数 - # Most AWK implementations have some standard trig functions + # 多数AWK实现中包含标准的三角函数 localvar = sin(a) localvar = cos(a) localvar = atan2(a, b) # arc tangent of b / a - # And logarithmic stuff + # 对数 localvar = exp(a) localvar = log(a) - # Square root + # 平方根 localvar = sqrt(a) - # Truncate floating point to integer + # 浮点型转为整型 localvar = int(5.34) # localvar => 5 - # Random numbers - srand() # Supply a seed as an argument. By default, it uses the time of day - localvar = rand() # Random number between 0 and 1. + # 随机数 + srand() # 接受随机种子作为参数, 默认使用当天的时间 + localvar = rand() # 0到1之间随机 - # Here's how to return a value + # 函数返回 return localvar } function string_functions( localvar, arr) { - # AWK, being a string-processing language, has several string-related - # functions, many of which rely heavily on regular expressions. + # AWK, 作为字符处理语言, 有很多字符串相关函数, 其中大多数都严重依赖正则表达式. - # Search and replace, first instance (sub) or all instances (gsub) - # Both return number of matches replaced + # 搜索并替换, 第一个出现的 (sub) or 所有的 (gsub) + # 都是返回替换的个数 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" - # Search for a string that matches a regular expression - # index() does the same thing, but doesn't allow a regular expression - match(localvar, "t") # => 4, since the 't' is the fourth character + # 搜索匹配正则的字符串 + # index() 也是搜索, 不支持正则 + match(localvar, "t") # => 4, 't'在4号位置. (译者注: awk是1开始计数的,不是常见的0-base) - # Split on a delimiter + # 按分隔符分隔 split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] - # Other useful stuff + # 其他有用的函数 sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" substr("foobar", 2, 3) # => "oob" substr("foobar", 4) # => "bar" @@ -212,99 +198,81 @@ function string_functions( localvar, arr) { function io_functions( localvar) { - # You've already seen print + # 你已经见过的print函数 print "Hello world" - # There's also printf + # 也有printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # 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: - + # AWK本身没有文件句柄, 当你使用需要文件的东西时会自动打开文件, 做文件I/O时, 字符串就是打开的文件句柄. + # 这看起来像Shell print "foobar" >"/tmp/foobar.txt" - # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + # 现在"/tmp/foobar.txt"字符串是一个文件句柄, 你可以关闭它 close("/tmp/foobar.txt") - # Here's how you run something in the shell + # 在shell里运行一些东西 system("echo foobar") # => prints foobar - # Reads a line from standard input and stores in localvar + # 从标准输入中读一行, 并存储在localvar中 getline localvar - # Reads a line from a pipe + # 从管道中读一行, 并存储在localvar中 "echo foobar" | getline localvar # localvar => "foobar" close("echo foobar") - # Reads a line from a file and stores in localvar + # 从文件中读一行, 并存储在localvar中 getline localvar <"/tmp/foobar.txt" close("/tmp/foobar.txt") } -# As I said at the beginning, AWK programs consist of a collection of patterns -# and actions. You've already seen the all-important BEGIN pattern. Other -# patterns are used only if you're processing lines from files or standard -# input. -# -# 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. +# 正如开头所说, AWK程序由一系列模式和动作组成. 你已经看见了重要的BEGIN pattern, +# 其他的pattern在你需要处理来自文件或标准输入的的数据行时才用到. +# +# 当你给AWK程序传参数时, 他们会被视为要处理文件的文件名, 按顺序全部会处理. +# 可以把这个过程看做一个隐式的循环, 遍历这些文件中的所有行. +# 然后这些模式和动作就是这个循环里的switch语句一样 /^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: - + # 这个动作会在匹配这个正则(/^fo+bar$/)的每一行上执行. 不匹配的则会跳过. + # 先让我们打印它: print - # Whoa, no argument! That's because print has a default argument: $0. - # $0 is the name of the current line being processed. It is created - # automatically for you. + # 哦, 没有参数, 那是因为print有一个默认参数 $0. + # $0 是当前正在处理的行, 自动被创建好了. - # You can probably guess there are other $ variables. Every line is - # implicitly split before every action is called, much like the shell - # does. And, like the shell, each field can be access with a dollar sign + # 你可能猜到有其他的$变量了. + # 每一行在动作执行前会被分隔符分隔. 像shell中一样, 每个字段都可以用$符访问 - # This will print the second and fourth fields in the line + # 这个会打印这行的第2和第4个字段 print $2, $4 - # AWK automatically defines many other variables to help you inspect and - # process each line. The most important one is NF - - # Prints the number of fields on this line + # AWK自动定义了许多其他的变量帮助你处理行. 最常用的是NF变量 + # 打印这一行的字段数 print NF - # Print the last field on this line + # 打印这一行的最后一个字段 print $NF } -# Every pattern is actually a true/false test. The regular expression in the -# last pattern is also a true/false test, but part of it was hidden. If you -# don't give it a string to test, it will assume $0, the line that it's -# currently processing. Thus, the complete version of it is this: +# 每一个模式其实是一个true/false判断, 上面那个正则其实也是一个true/false判断, 只不过被部分省略了. +# 没有指定时默认使用当前处理的整行($0)进行匹配. 因此, 完全版本是这样: $0 ~ /^fo+bar$/ { print "Equivalent to the last pattern" } a > 0 { - # This will execute once for each line, as long as a is positive + # 只要a是整数, 这块会在每一行上执行. } -# You get the idea. Processing text files, reading in a line at a time, and -# doing something with it, particularly splitting on a delimiter, is so common -# in UNIX that AWK is a scripting language that does all of it for you, without -# you needing to ask. All you have to do is write the patterns and actions -# based on what you expect of the input, and what you want to do with it. +# 就是这样, 处理文本文件, 一次读一行, 对行做一些操作. 按分隔符分隔, 这在UNIX中很常见, awk都帮你做好了. +# 你所需要做的是基于自己的需求写一些模式和动作. -# Here's a quick example of a simple script, the sort of thing AWK is perfect -# for. It will read a name from standard input and then will print the average -# age of everyone with that first name. Let's say you supply as an argument the -# name of a this data file: +# 这里有一个快速的例子, 展示了AWK所擅长做的事. +# 它从标准输入读一个名字, 打印这个first name下所有人的平均年龄. +# 示例数据: # # Bob Jones 32 # Jane Doe 22 @@ -312,41 +280,36 @@ a > 0 { # Bob Smith 29 # Bob Barker 72 # -# Here's the script: +# 示例脚本: BEGIN { - # First, ask the user for the name + # 首先, 问用户要一个名字 print "What name would you like the average age for?" - # Get a line from standard input, not from files on the command line + # 从标准输入获取名字 getline name <"/dev/stdin" } -# Now, match every line whose first field is the given name +# 然后, 用给定的名字匹配每一行的第一个字段. $1 == name { - # Inside here, we have access to a number of useful variables, already - # pre-loaded for us: - # $0 is the entire line - # $3 is the third field, the age, which is what we're interested in here - # NF is the number of fields, which should be 3 - # NR is the number of records (lines) seen so far - # FILENAME is the name of the file being processed - # FS is the field separator being used, which is " " here - # ...etc. There are plenty more, documented in the man page. - - # Keep track of a running total and how many lines matched + # 这里我们要使用几个有用的变量, 已经提前为我们加载好的: + # $0 是整行 + # $3 是第三个字段, 就是我们所感兴趣的年龄 + # NF 字段数, 这里是3 + # NR 至此为止的行数 + # FILENAME 在处理的文件名 + # FS 在使用的字段分隔符, 这里是空格" " + # ...等等, 还有很多, 在帮助文档中列出. + + # 跟踪 总和以及行数 sum += $3 nlines++ } -# Another special pattern is called END. It will run after processing all the -# text files. Unlike BEGIN, it will only run if you've given it input to -# process. It will run after all the files have been read and processed -# according to the rules and actions you've provided. The purpose of it is -# usually to output some kind of final report, or do something with the -# aggregate of the data you've accumulated over the course of the script. +# 另一个特殊的模式叫END. 它会在处理完所有行之后运行. 不像BEGIN, 它只会在有输入的时候运行. +# 它在所有文件依据给定的模式和动作处理完后运行, 目的通常是输出一些最终报告, 做一些数据聚合操作. END { if (nlines) @@ -354,8 +317,8 @@ 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. +* [Awk 教程](http://www.grymoire.com/Unix/Awk.html) +* [Awk 手册](https://linux.die.net/man/1/awk) +* [The GNU Awk 用户指南](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk在大多数Linux中预装 -- cgit v1.2.3 From 8c30522d58e6c006274952a75c5acd4d104c8828 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:12:23 -0700 Subject: added info about tuples, integrated wild card use into a function definition --- haskell.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 266cf11b..cad036f1 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -124,6 +124,9 @@ last [1..5] -- 5 fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 +-- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) +snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this + ---------------------------------------------------- -- 3. Functions ---------------------------------------------------- @@ -159,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples: -foo (x, y) = (x + 1, y + 2) +-- Pattern matching on tuples, using wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -203,9 +206,9 @@ foo = (4*) . (10+) foo 5 -- 60 -- fixing precedence --- Haskell has an operator called `$`. This operator applies a function --- to a given parameter. In contrast to standard function application, which --- has highest possible priority of 10 and is left-associative, the `$` operator +-- Haskell has an operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that -- the expression on its right is applied as the parameter to the function on its left. @@ -223,7 +226,7 @@ even . fib $ 7 -- false -- 5. Type signatures ---------------------------------------------------- --- Haskell has a very strong type system, and every valid expression has a type. +-- Haskell has a very strong type system, and every valid expression has a type. -- Some basic types: 5 :: Integer -- cgit v1.2.3 From 093e6b62a1aae230f965ad8d1ee2ff8a6b128055 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:15:26 -0700 Subject: moved comment on sndOfTriple --- haskell.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index cad036f1..6a48b60c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -162,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples, using wild card (_) to bypass naming an unused value -sndOfTriple (_, y, _) = y +-- Pattern matching on tuples +sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write -- cgit v1.2.3 From c421b1bd0d18ab57c88665bd14b289e75724cf37 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:34:42 -0700 Subject: trimmed loc over 80 chars --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6a48b60c..e9ddf54d 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -125,7 +125,7 @@ fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 -- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) -snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this +snd ("snd", "can't touch this", "da na na na") -- error! see function below ---------------------------------------------------- -- 3. Functions @@ -163,7 +163,7 @@ fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) -- Pattern matching on tuples -sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- use a wild card (_) to bypass naming unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -210,7 +210,7 @@ foo 5 -- 60 -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that --- the expression on its right is applied as the parameter to the function on its left. +-- the expression on its right is applied as parameter to function on its left. -- before even (fib 7) -- false -- cgit v1.2.3 From d063ea64694226c9490d5fe6da3b960449c3bfe3 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 1 Aug 2018 21:12:35 -0700 Subject: Restore lost articles I'm afraid we need these --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index e9ddf54d..90d47c27 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -210,7 +210,7 @@ foo 5 -- 60 -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that --- the expression on its right is applied as parameter to function on its left. +-- the expression on its right is applied as a parameter to the function on its left. -- before even (fib 7) -- false -- cgit v1.2.3 From 4a2fa42bd8a6caaa876e9bb0cb46a297ae7e7196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=82=D1=91=D0=BC?= Date: Thu, 2 Aug 2018 14:21:51 +0300 Subject: Update clojure-ru.html.markdown --- ru-ru/clojure-ru.html.markdown | 52 +++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 356d1cc0..19233d23 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -8,9 +8,9 @@ translators: lang: ru-ru --- -Clojure, это представитель семейства Lisp-подобных языков, разработанный +Clojure — это представитель семейства Lisp-подобных языков, разработанный для Java Virtual Machine. Язык идейно гораздо ближе к чистому -[функциональному программированию](https://ru.wikipedia.org/wiki/%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) чем его прародитель Common Lisp, но в то же время обладает набором инструментов для работы с состоянием, +[функциональному программированию](https://ru.wikipedia.org/wiki/%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B5_%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5), чем его прародитель Common Lisp, но в то же время обладает набором инструментов для работы с состоянием, таких как [STM](https://ru.wikipedia.org/wiki/Software_transactional_memory). Благодаря такому сочетанию технологий в одном языке, разработка программ, @@ -23,9 +23,9 @@ Clojure, это представитель семейства Lisp-подобн ```clojure ; Комментарии начинаются символом ";". -; Код на языке Clojure записывается в виде "форм", +; Код на языке Clojure записывается в виде «форм», ; которые представляют собой обычные списки элементов, разделенных пробелами, -; заключённые в круглые скобки +; заключённые в круглые скобки. ; ; Clojure Reader (инструмент языка, отвечающий за чтение исходного кода), ; анализируя форму, предполагает, что первым элементом формы (т.е. списка) @@ -76,32 +76,32 @@ Clojure, это представитель семейства Lisp-подобн '(+ 1 2) ; => (+ 1 2) ; ("'", это краткая запись формы (quote (+ 1 2)) -; "Квотированный" список можно вычислить, передав его функции eval +; «Квотированный» список можно вычислить, передав его функции eval (eval '(+ 1 2)) ; => 3 ; Коллекции и Последовательности ;;;;;;;;;;;;;;;;;;; -; Списки (Lists) в clojure структурно представляют собой "связанные списки", +; Списки (Lists) в clojure структурно представляют собой «связанные списки», ; тогда как Векторы (Vectors), устроены как массивы. ; Векторы и Списки тоже являются классами Java! (class [1 2 3]); => clojure.lang.PersistentVector (class '(1 2 3)); => clojure.lang.PersistentList -; Список может быть записан, как (1 2 3), но в этом случае +; Список может быть записан как (1 2 3), но в этом случае ; он будет воспринят reader`ом, как вызов функции. ; Есть два способа этого избежать: ; '(1 2 3) - квотирование, ; (list 1 2 3) - явное конструирование списка с помощью функции list. -; "Коллекции", это некие наборы данных +; «Коллекции» — это некие наборы данных. ; И списки, и векторы являются коллекциями: (coll? '(1 2 3)) ; => true (coll? [1 2 3]) ; => true -; "Последовательности" (seqs), это абстракция над наборами данных, +; «Последовательности» (seqs) — это абстракция над наборами данных, ; элементы которых "упакованы" последовательно. -; Списки - последовательности, а вектора - нет. +; Списки — последовательности, а векторы — нет. (seq? '(1 2 3)) ; => true (seq? [1 2 3]) ; => false @@ -119,7 +119,7 @@ Clojure, это представитель семейства Lisp-подобн ; Функция conj добавляет элемент в коллекцию ; максимально эффективным для неё способом. -; Для списков эффективно добавление в начло, а для векторов - в конец. +; Для списков эффективно добавление в начло, а для векторов — в конец. (conj [1 2 3] 4) ; => [1 2 3 4] (conj '(1 2 3) 4) ; => (4 1 2 3) @@ -130,7 +130,7 @@ Clojure, это представитель семейства Lisp-подобн (map inc [1 2 3]) ; => (2 3 4) (filter even? [1 2 3]) ; => (2) -; reduce поможет "свернуть" коллекцию +; reduce поможет «свернуть» коллекцию (reduce + [1 2 3 4]) ; = (+ (+ (+ 1 2) 3) 4) ; => 10 @@ -144,12 +144,12 @@ Clojure, это представитель семейства Lisp-подобн ;;;;;;;;;;;;;;;;;;;;; ; Функция создается специальной формой fn. -; "Тело" функции может состоять из нескольких форм, +; «Тело» функции может состоять из нескольких форм, ; но результатом вызова функции всегда будет результат вычисления ; последней из них. (fn [] "Hello World") ; => fn -; (Вызов функции требует "оборачивания" fn-формы в форму вызова) +; (Вызов функции требует «оборачивания» fn-формы в форму вызова) ((fn [] "Hello World")) ; => "Hello World" ; Назначить значению имя можно специальной формой def @@ -160,7 +160,7 @@ x ; => 1 (def hello-world (fn [] "Hello World")) (hello-world) ; => "Hello World" -; Поскольку именование функций - очень частая операция, +; Поскольку именование функций — очень частая операция, ; clojure позволяет, сделать это проще: (defn hello-world [] "Hello World") @@ -211,7 +211,7 @@ x ; => 1 ; Отображения могут использовать в качестве ключей любые хэшируемые значения, ; однако предпочтительными являются ключи, -; являющиеся "ключевыми словами" (keywords) +; являющиеся «ключевыми словами» (keywords) (class :a) ; => clojure.lang.Keyword (def stringmap {"a" 1, "b" 2, "c" 3}) @@ -263,7 +263,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут ; Исключаются - посредством disj (disj #{1 2 3} 1) ; => #{2 3} -; Вызов множества, как функции, позволяет проверить +; Вызов множества как функции позволяет проверить ; принадлежность элемента этому множеству: (#{1 2 3} 1) ; => 1 (#{1 2 3} 4) ; => nil @@ -274,8 +274,8 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут ; Полезные формы ;;;;;;;;;;;;;;;;; -; Конструкции ветвления в clojure, это обычные макросы -; и подобны их собратьям в других языках: +; Конструкции ветвления в clojure — это обычные макросы, +; они подобны своим собратьям в других языках: (if false "a" "b") ; => "b" (if false "a") ; => nil @@ -285,7 +285,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут (let [a 1 b 2] (> a b)) ; => false -; Несколько форм можно объединить в одну форму посредством do +; Несколько форм можно объединить в одну форму посредством do. ; Значением do-формы будет значение последней формы из списка вложенных в неё: (do (print "Hello") @@ -298,7 +298,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут (str "Hello " name)) (print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") -; Ещё один пример - let: +; Ещё один пример — let: (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") @@ -306,7 +306,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут ; Модули ;;;;;;;;; -; Форма "use" позволяет добавить в текущее пространство имен +; Форма use позволяет добавить в текущее пространство имен ; все имена (вместе со значениями) из указанного модуля: (use 'clojure.set) @@ -392,7 +392,7 @@ keymap ; => {:a 1, :b 2, :c 3} - оригинал не был затронут my-atom ;=> Atom<#...> (Возвращает объект типа Atom) @my-atom ; => {:a 1 :b 2} -; Пример реализации счётчика на атоме +; Пример реализации счётчика на атоме: (def counter (atom 0)) (defn inc-counter [] (swap! counter inc)) @@ -414,13 +414,13 @@ my-atom ;=> Atom<#...> (Возвращает объект типа Atom) Это руководство не претендует на полноту, но мы смеем надеяться, способно вызвать интерес к дальнейшему изучению языка. -Clojure.org - сайт содержит большое количество статей по языку: +Сайт Clojure.org содержит большое количество статей по языку: [http://clojure.org/](http://clojure.org/) -Clojuredocs.org - сайт документации языка с примерами использования функций: +Clojuredocs.org — сайт документации языка с примерами использования функций: [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) -4Clojure - отличный способ закрепить навыки программирования на clojure, решая задачи вместе с коллегами со всего мира: +4Clojure — отличный способ закрепить навыки программирования на clojure, решая задачи вместе с коллегами со всего мира: [http://www.4clojure.com/](http://www.4clojure.com/) Clojure-doc.org (да, именно) неплохой перечень статей для начинающих: -- cgit v1.2.3 From 62c238fc4c65678a5affdbd27c5c26e601cbb2fb Mon Sep 17 00:00:00 2001 From: Alan Russell Date: Thu, 2 Aug 2018 14:43:03 +0100 Subject: Update ruby-ecosystem.html.markdown Update info on major versions in common use Move info on versions above info on version managers --- ruby-ecosystem.html.markdown | 32 ++++++++++---------------------- 1 file changed, 10 insertions(+), 22 deletions(-) diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 50eedcd0..3c80075b 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -10,6 +10,16 @@ contributors: People using Ruby generally have a way to install different Ruby versions, manage their packages (or gems), and manage their gem dependencies. +## Ruby Versions + +Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a +[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although +that is changing recently. As a result, the reference implementation of Ruby is +called MRI (Matz' Reference Implementation), and when you hear a Ruby version, +it is referring to the release version of MRI. + +New major versions of Ruby are traditionally released on Christmas Day. The current major version (25 December 2017) is 2.5. The most popular stable versions are 2.4.4 and 2.3.7 (both released 28 March 2018). + ## Ruby Managers Some platforms have Ruby pre-installed or available as a package. Most rubyists @@ -29,28 +39,6 @@ The following are the popular Ruby environment managers: * [chruby](https://github.com/postmodern/chruby) - Only switches between rubies. Similar in spirit to rbenv. Unopinionated about how rubies are installed. -## Ruby Versions - -Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a -[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although -that is changing recently. As a result, the reference implementation of Ruby is -called MRI (Matz' Reference Implementation), and when you hear a Ruby version, -it is referring to the release version of MRI. - -The three major version of Ruby in use are: - -* 2.0.0 - Released in February 2013. Most major libraries and frameworks support - 2.0.0. -* 1.9.3 - Released in October 2011. This is the version most rubyists use - currently. Also [retired](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) -* 1.8.7 - Ruby 1.8.7 has been - [retired](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). - -The change between 1.8.7 to 1.9.x is a much larger change than 1.9.3 to 2.0.0. -For instance, the 1.9 series introduced encodings and a bytecode VM. There -are projects still on 1.8.7, but they are becoming a small minority, as most of -the community has moved to at least 1.9.2 or 1.9.3. - ## Ruby Implementations The Ruby ecosystem enjoys many different implementations of Ruby, each with -- cgit v1.2.3 From 057511f3a7cf41f7fc524504a063c261c0ddf836 Mon Sep 17 00:00:00 2001 From: Topher Date: Wed, 8 Aug 2018 19:17:43 +0300 Subject: [lua/en] Added a note about the wonky ternary Ternaries in lua only work if the value returned when the condition evaluates to `true` is not `false` or `Nil`. --- lua.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua.html.markdown b/lua.html.markdown index 1e2d4366..2139003a 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -62,6 +62,10 @@ if not aBoolValue then print('twas false') end -- in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' +-- BEWARE: this only acts as a ternary value returned when the condition is true is not `false` or Nil +ans1 = aBoolValue and false or true --> true +ans2 = aBoolValue and true or false --> true + karlSum = 0 for i = 1, 100 do -- The range includes both ends. karlSum = karlSum + i -- cgit v1.2.3 From 5e4079fa338040a6ee6951a61ace90e87a925159 Mon Sep 17 00:00:00 2001 From: Topher Date: Wed, 8 Aug 2018 19:24:40 +0300 Subject: [lua/en] Fixed formatting and variable names --- lua.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua.html.markdown b/lua.html.markdown index 2139003a..32174a81 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -62,9 +62,10 @@ if not aBoolValue then print('twas false') end -- in C/js: ans = aBoolValue and 'yes' or 'no' --> 'no' --- BEWARE: this only acts as a ternary value returned when the condition is true is not `false` or Nil -ans1 = aBoolValue and false or true --> true -ans2 = aBoolValue and true or false --> true +-- BEWARE: this only acts as a ternary if the value returned when the condition +-- evaluates to true is not `false` or Nil +iAmNotFalse = (not aBoolValue) and false or true --> true +iAmAlsoNotFalse = (not aBoolValue) and true or false --> true karlSum = 0 for i = 1, 100 do -- The range includes both ends. -- cgit v1.2.3 From 93499a09469335fda9b43d68bdf40bb87b67c071 Mon Sep 17 00:00:00 2001 From: DevHugo Date: Tue, 14 Aug 2018 19:20:36 +0200 Subject: Translate: Header + Part 1 --- fr-fr/pyqt-fr.html.markdown | 85 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 fr-fr/pyqt-fr.html.markdown diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown new file mode 100644 index 00000000..a0df8be5 --- /dev/null +++ b/fr-fr/pyqt-fr.html.markdown @@ -0,0 +1,85 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt-fr.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["DevHugo", "http://twitter.com/devhugo"] +lang: fr-fr +--- + +**Qt** est un framework très connu pour le développement de logiciel cross-platform qui peuvent être lancé sur différents systèmes avec de petit ou aucun changement dans le code, tout en ayant la puissance et la vitesse des applications natives. Bien que **Qt** ait été écrit à l'origine en *C++*. + + +Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192 +), certains exemples du code doivent avoir la même fonctionnalité, +cette version ayant juste été faite en utilisant pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Création de l'objet application + app = QtGui.QApplication(sys.argv) + # Création d'un widget où notre label sera placé + w = QtGui.QWidget() + # Ajout d'un label au widget + b = QtGui.QLabel(w) + # Assignation de texte au label + b.setText("Hello World!") + # Assignation des tailles et des informations de placement + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Assignation d'un nom à notre fenêtre + w.setWindowTitle("PyQt") + # Affichage de la fenêtre + w.show() + # Exécution de l'application + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. +Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information. + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Create a button and attach to widget w + b = QPushButton(w) + b.setText("Press me") + b.move(50, 50) + # Tell b to call this function when clicked + # notice the lack of "()" on the function call + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# This function should create a dialog window with a button +# that waits to be clicked and then exits the program +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # This modality tells the popup to block the parent whilst it's active + d.setWindowModality(Qt.ApplicationModal) + # On click I'd like the entire process to end + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` -- cgit v1.2.3 From e1ab28f4fab138e7968041190a64ef0dc0a346a4 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Wed, 29 Aug 2018 15:48:40 +0800 Subject: Keep a line 80 chars --- julia.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 891a0a00..0b28d869 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -8,7 +8,8 @@ filename: learnjulia.jl --- Julia is a new homoiconic functional language focused on technical computing. -While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. +While having the full power of homoiconic macros, first-class functions, +and low-level control, Julia is as easy to learn and use as Python. This is based on Julia 1.0.0 -- cgit v1.2.3 From 35215e4a2db7063f105eb30eb19cbf7b9d370cec Mon Sep 17 00:00:00 2001 From: 0u0 Date: Wed, 29 Aug 2018 15:55:04 +0800 Subject: Use more clearly example --- julia.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 0b28d869..dfa3103c 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -28,17 +28,17 @@ This is based on Julia 1.0.0 # Everything in Julia is an expression. # There are several basic types of numbers. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2 // 3 # => 2 // 3 (Rational{Int64}) +typeof(3) # => Int64 +typeof(3.2) # => Float64 +typeof(2 + 1im) # => Complex{Int64} +typeof(2 // 3) # => Rational{Int64} # All of the normal infix operators are available. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 -5 / 2 # => 2.5 # dividing integers always results in a Float64 +10 / 2 # => 5.0 # dividing integers always results in a Float64 div(5, 2) # => 2 # for a truncated result, use div 5 \ 35 # => 7.0 2^2 # => 4 # power, not bitwise xor -- cgit v1.2.3 From dcfb420ff896fa326fddb609c669133cf24a6e88 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:06:13 +0530 Subject: Fix build error in 'build/docs/cs-cz/markdown/index.html' --- cs-cz/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 568e4343..35becf94 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -13,7 +13,7 @@ Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce či a psatelná syntaxe, která je jednoduše převeditelná do HTML (a dnes i do mnoha dalších formátů) -```markdown +```md +``` ## Заголовки @@ -50,7 +51,7 @@ HTML-элементы от

до

размечаются очень пр текст, который должен стать заголовком, предваряется соответствующим количеством символов "#": -```markdown +```md # Это заголовок h1 ## Это заголовок h2 ### Это заголовок h3 @@ -60,7 +61,7 @@ HTML-элементы от

до

размечаются очень пр ``` Markdown позволяет размечать заголовки

и

ещё одним способом: -```markdown +```md Это заголовок h1 ================ @@ -72,7 +73,7 @@ Markdown позволяет размечать заголовки

и

Текст легко сделать полужирным и/или курсивным: -```markdown +```md *Этот текст будет выведен курсивом.* _Так же, как этот._ @@ -87,7 +88,7 @@ __И этот тоже.__ В Github Flavored Markdown, стандарте, который используется в Github, текст также можно сделать зачёркнутым: -```markdown +```md ~~Зачёркнутый текст.~~ ``` @@ -96,7 +97,7 @@ __И этот тоже.__ Абзацами являются любые строки, следующие друг за другом. Разделяются же абзацы одной или несколькими пустыми строками: -```markdown +```md Это абзац. Я печатаю в абзаце, разве это не прикольно? А тут уже абзац №2. @@ -108,7 +109,7 @@ __И этот тоже.__ Для вставки принудительных переносов можно завершить абзац двумя дополнительными пробелами: -```markdown +```md Эта строка завершается двумя пробелами (выделите, чтобы увидеть!). Над этой строкой есть
! @@ -116,7 +117,7 @@ __И этот тоже.__ Цитаты размечаются с помощью символа «>»: -```markdown +```md > Это цитата. В цитатах можно > принудительно переносить строки, вставляя «>» в начало каждой следующей строки. А можно просто оставлять их достаточно длинными, и такие длинные строки будут перенесены автоматически. > Разницы между этими двумя подходами к переносу строк нет, коль скоро @@ -133,7 +134,7 @@ __И этот тоже.__ одного из символов «*», «+» или «-»: (символ должен быть одним и тем же для всех элементов) -```markdown +```md * Список, * Размеченный * Звёздочками @@ -154,7 +155,7 @@ __И этот тоже.__ В нумерованных списках каждая строка начинается с числа и точки вслед за ним: -```markdown +```md 1. Первый элемент 2. Второй элемент 3. Третий элемент @@ -164,7 +165,7 @@ __И этот тоже.__ любое число в начале каждого элемента, и парсер пронумерует элементы сам! Правда, злоупотреблять этим не стоит :) -```markdown +```md 1. Первый элемент 1. Второй элемент 1. Третий элемент @@ -173,7 +174,7 @@ __И этот тоже.__ Списки могут быть вложенными: -```markdown +```md 1. Введение 2. Начало работы 3. Примеры использования @@ -184,7 +185,7 @@ __И этот тоже.__ Можно даже делать списки задач. Блок ниже создаёт HTML-флажки. -```markdown +```md Для отметки флажка используйте «x» - [ ] Первая задача - [ ] Вторая задача @@ -197,7 +198,7 @@ __И этот тоже.__ Фрагменты исходного кода (обычно отмечаемые тегом ``) выделяются просто: каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции. -```markdown +```md Это код, причём многострочный ``` @@ -205,7 +206,7 @@ __И этот тоже.__ Вы также можете делать дополнительные отступы, добавляя символы табуляции или по четыре пробела: -```markdown +```md my_array.each do |item| puts item end @@ -215,7 +216,7 @@ __И этот тоже.__ не выделяя код в блок. Для этого фрагменты кода нужно обрамлять символами «`»: -```markdown +```md Ваня даже не знал, что делает функция `go_to()`! ``` @@ -237,7 +238,7 @@ end Разделители (`
`) добавляются вставкой строки из трёх и более (одинаковых) символов «*» или «-», с пробелами или без них: -```markdown +```md *** --- - - - @@ -251,18 +252,18 @@ end текст ссылки, заключив его в квадратные скобки, и сразу после — URL-адрес, заключенный в круглые -```markdown +```md [Ссылка!](http://test.com/) ``` Также для ссылки можно указать всплывающую подсказку (`title`), используя кавычки внутри круглых скобок: -```markdown +```md [Ссылка!](http://test.com/ "Ссылка на Test.com") ``` Относительные пути тоже возможны: -```markdown +```md [Перейти к музыке](/music/). ``` @@ -290,7 +291,7 @@ Markdown также позволяет размечать ссылку в вид Разметка изображений очень похожа на разметку ссылок. Нужно всего лишь добавить перед ссылкой восклицательный знак! -```markdown +```md ![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка") ``` Изображения тоже могут быть оформлены, как сноски. @@ -301,20 +302,20 @@ Markdown также позволяет размечать ссылку в вид ## Разное ### Автоссылки -```markdown +```md Ссылка вида эквивалентна [http://testwebsite.com/](http://testwebsite.com/) ``` ### Автоссылки для адресов электронной почты -```markdown +```md ``` ### Экранирование символов -```markdown +```md Я хочу напечатать *текст, заключённый в звёздочки*, но я не хочу, чтобы он был курсивным. Тогда я делаю так: \*Текст, заключённый в звёздочки\* @@ -324,7 +325,7 @@ Markdown также позволяет размечать ссылку в вид В Github Flavored Markdown для представления клавиш на клавиатуре вы можете использовать тег ``. -```markdown +```md Ваш компьютер завис? Попробуйте нажать Ctrl+Alt+Del ``` @@ -334,7 +335,7 @@ Markdown также позволяет размечать ссылку в вид да и синтаксис имеют не слишком удобный. Но если очень нужно, размечайте таблицы так: -```markdown +```md | Столбец 1 | Столбец 2 | Столбец 3 | | :----------- | :----------: | -----------: | | Выравнивание | Выравнивание | Выравнивание | @@ -342,7 +343,7 @@ Markdown также позволяет размечать ссылку в вид ``` Или более компактно -```markdown +```md Столбец 1|Столбец 2|Столбец 3 :--|:-:|--: Выглядит|это|страшновато... -- cgit v1.2.3 From 150e8666b1094ee27de378496900f548167a4eec Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:19:21 +0530 Subject: Fix build error in 'build/docs/it-it/markdown/index.html' --- it-it/markdown.html.markdown | 60 ++++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index 44801747..b0a123f1 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -28,7 +28,7 @@ Markdown varia nelle sue implementazioni da un parser all'altro. Questa guida ce ## Elementi HTML Markdown è un superset di HTML, quindi ogni file HTML è a sua volta un file Markdown valido. -```markdown +```md Potete creare gli elementi HTML da `

` a `

` facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento -```markdown +```md # Questo è un

## Questo è un

### Questo è un

@@ -49,7 +49,7 @@ Potete creare gli elementi HTML da `

` a `

` facilmente, basta che inseria ``` Markdown inoltre fornisce due alternative per indicare gli elementi h1 e h2 -```markdown +```md Questo è un h1 ============== @@ -60,7 +60,7 @@ Questo è un h2 ## Stili di testo semplici Il testo può essere stilizzato in corsivo o grassetto usando markdown -```markdown +```md *Questo testo è in corsivo.* _Come pure questo._ @@ -74,12 +74,12 @@ __Come pure questo.__ In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato: -```markdown +```md ~~Questo testo è barrato.~~ ``` ## Paragrafi -```markdown +```md I paragrafi sono una o più linee di testo adiacenti separate da una o più righe vuote. Questo è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? @@ -93,7 +93,7 @@ Qui siamo nel paragrafo 3! Se volete inserire l'elemento HTML `
`, potete terminare la linea con due o più spazi e poi iniziare un nuovo paragrafo. -```markdown +```md Questa frase finisce con due spazi (evidenziatemi per vederli). C'è un
sopra di me! @@ -101,7 +101,7 @@ C'è un
sopra di me! Le citazioni sono semplici da inserire, basta usare il carattere >. -```markdown +```md > Questa è una citazione. Potete > mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. > Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. @@ -115,7 +115,7 @@ Le citazioni sono semplici da inserire, basta usare il carattere >. ## Liste Le liste non ordinate possono essere inserite usando gli asterischi, il simbolo più o dei trattini -```markdown +```md * Oggetto * Oggetto * Altro oggetto @@ -135,7 +135,7 @@ oppure Le liste ordinate invece, sono inserite con un numero seguito da un punto. -```markdown +```md 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto @@ -143,7 +143,7 @@ Le liste ordinate invece, sono inserite con un numero seguito da un punto. Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzerà comunque nell'ordine corretto, anche se potrebbe non essere una buona idea. -```markdown +```md 1. Primo oggetto 1. Secondo oggetto 1. Terzo oggetto @@ -152,7 +152,7 @@ Non dovete nemmeno mettere i numeri nell'ordine giusto, markdown li visualizzer Potete inserire anche sotto liste -```markdown +```md 1. Primo oggetto 2. Secondo oggetto 3. Terzo oggetto @@ -163,7 +163,7 @@ Potete inserire anche sotto liste Sono presenti anche le task list. In questo modo è possibile creare checkbox in HTML. -```markdown +```md I box senza la 'x' sono checkbox HTML ancora da completare. - [ ] Primo task da completare. - [ ] Secondo task che deve essere completato. @@ -174,14 +174,14 @@ Il box subito sotto è una checkbox HTML spuntata. Potete inserire un estratto di codice (che utilizza l'elemento ``) indentando una linea con quattro spazi oppure con un carattere tab. -```markdown +```md Questa è una linea di codice Come questa ``` Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vostro codice -```markdown +```md my_array.each do |item| puts item end @@ -189,7 +189,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo Codice inline può essere inserito usando il carattere backtick ` -```markdown +```md Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! ``` @@ -205,7 +205,7 @@ Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre ## Linea orizzontale Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. -```markdown +```md *** --- - - - @@ -215,24 +215,24 @@ Le linee orizzontali (`
`) sono inserite facilmente usanto tre o più asteri ## Links Una delle funzionalità migliori di markdown è la facilità con cui si possono inserire i link. Mettete il testo da visualizzare fra parentesi quadre [] seguite dall'url messo fra parentesi tonde () -```markdown +```md [Cliccami!](http://test.com/) ``` Potete inoltre aggiungere al link un titolo mettendolo fra doppi apici dopo il link -```markdown +```md [Cliccami!](http://test.com/ "Link a Test.com") ``` La sintassi funziona anche con i path relativi. -```markdown +```md [Vai a musica](/music/). ``` Markdown supporta inoltre anche la possibilità di aggiungere i link facendo riferimento ad altri punti del testo. -```markdown +```md [Apri questo link][link1] per più informazioni! [Guarda anche questo link][foobar] se ti va. @@ -242,7 +242,7 @@ Markdown supporta inoltre anche la possibilità di aggiungere i link facendo rif l titolo può anche essere inserito in apici singoli o in parentesi, oppure omesso interamente. Il riferimento può essere inserito in un punto qualsiasi del vostro documento e l'identificativo del riferimento può essere lungo a piacere a patto che sia univoco. Esiste anche un "identificativo implicito" che vi permette di usare il testo del link come id. -```markdown +```md [Questo][] è un link. [Questo]: http://thisisalink.com/ @@ -252,13 +252,13 @@ Ma non è comunemente usato. ## Immagini Le immagini sono inserite come i link ma con un punto esclamativo inserito prima delle parentesi quadre! -```markdown +```md ![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") ``` E la modalità a riferimento funziona esattamente come ci si aspetta -```markdown +```md ![Questo è il testo alternativo.][myimage] [myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" @@ -266,25 +266,25 @@ E la modalità a riferimento funziona esattamente come ci si aspetta ## Miscellanea ### Auto link -```markdown +```md è equivalente ad [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto link per le email -```markdown +```md ``` ### Caratteri di escaping -```markdown +```md Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. ``` ### Combinazioni di tasti In Github Flavored Markdown, potete utilizzare il tag `` per raffigurare i tasti della tastiera. -```markdown +```md Il tuo computer è crashato? Prova a premere Ctrl+Alt+Canc ``` @@ -292,7 +292,7 @@ Il tuo computer è crashato? Prova a premere ### Tabelle Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: -```markdown +```md | Col1 | Col2 | Col3 | | :------------------- | :------: | -----------------: | | Allineato a sinistra | Centrato | Allineato a destra | @@ -300,7 +300,7 @@ Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente ``` oppure, per lo stesso risultato -```markdown +```md Col 1 | Col2 | Col3 :-- | :-: | --: È una cosa orrenda | fatela | finire in fretta -- cgit v1.2.3 From 0b36159335327d7b217cfd9116a0adc3e27c5120 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:21:05 +0530 Subject: Fix build error in 'build/docs/es-es/markdown-es/index.html' --- es-es/markdown-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index 0505b4cb..e23a94ea 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también). ¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! -```markdown +```md @@ -34,7 +34,7 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마 텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `

`부터 `

`까지의 HTML 요소를 손쉽게 작성할 수 있습니다. -```markdown +```md #

입니다. ##

입니다. ###

입니다. @@ -43,7 +43,7 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마 ######

입니다. ``` 또한 h1과 h2를 나타내는 다른 방법이 있습니다. -```markdown +```md h1입니다. ============= @@ -53,7 +53,7 @@ h2입니다. ## 간단한 텍스트 꾸미기 마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다. -```markdown +```md *기울인 텍스트입니다.* _이 텍스트도 같습니다._ @@ -65,14 +65,14 @@ __이 텍스트도 같습니다.__ *__이것도 같습니다.__* ``` 깃헙 전용 마크다운에는 취소선도 있습니다. -```markdown +```md ~~이 텍스트에는 취소선이 그려집니다.~~ ``` ## 문단 문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다. -```markdown +```md 문단입니다. 문단에 글을 쓰다니 재밌지 않나요? 이제 두 번째 문단입니다. @@ -83,7 +83,7 @@ __이 텍스트도 같습니다.__ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어쓰기로 문단을 끝내고 새 문단을 시작할 수 있습니다. -```markdown +```md 띄어쓰기 두 개로 끝나는 문단 (마우스로 긁어 보세요). 이 위에는 `
` 태그가 있습니다. @@ -91,7 +91,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 인용문은 > 문자로 쉽게 쓸 수 있습니다. -```markdown +```md > 인용문입니다. 수동으로 개행하고서 > 줄마다 `>`를 칠 수도 있고 줄을 길게 쓴 다음에 저절로 개행되게 내버려 둘 수도 있습니다. > `>`로 시작하기만 한다면 차이가 없습니다. @@ -103,7 +103,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 ## 목록 순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다. -```markdown +```md * 이거 * 저거 * 그거 @@ -111,7 +111,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 또는 -```markdown +```md + 이거 + 저거 + 그거 @@ -119,7 +119,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 또는 -```markdown +```md - 이거 - 저거 - 그거 @@ -127,7 +127,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 순서가 있는 목록은 숫자와 마침표입니다. -```markdown +```md 1. 하나 2. 둘 3. 셋 @@ -135,7 +135,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 숫자를 정확히 붙이지 않더라도 제대로 된 순서로 보여주겠지만, 좋은 생각은 아닙니다. -```markdown +```md 1. 하나 1. 둘 1. 셋 @@ -144,7 +144,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 목록 안에 목록이 올 수도 있습니다. -```markdown +```md 1. 하나 2. 둘 3. 셋 @@ -155,7 +155,7 @@ HTML `
` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 심지어 할 일 목록도 있습니다. HTML 체크박스가 만들어집니다. -```markdown +```md x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. - [ ] 첫 번째 할 일 - [ ] 두 번째 할 일 @@ -168,13 +168,13 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. 띄어쓰기 네 개 혹은 탭 한 개로 줄을 들여씀으로서 (` 요소를 사용하여`) 코드를 나타낼 수 있습니다. -```markdown +```md puts "Hello, world!" ``` 탭을 더 치거나 띄어쓰기를 네 번 더 함으로써 코드를 들여쓸 수 있습니다. -```markdown +```md my_array.each do |item| puts item end @@ -182,7 +182,7 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. 인라인 코드는 백틱 문자를 이용하여 나타냅니다. ` -```markdown +```md 철수는 `go_to()` 함수가 뭘 했는지도 몰랐어! ``` @@ -202,7 +202,7 @@ end 수평선(`
`)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다. 띄어쓰기가 포함될 수 있습니다. -```markdown +```md *** --- - - - @@ -213,19 +213,19 @@ end 마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고 괄호 안에 URL을 쓰면 됩니다. -```markdown +```md [클릭](http://test.com/) ``` 괄호 안에 따옴표를 이용해 링크에 제목을 달 수도 있습니다. -```markdown +```md [클릭](http://test.com/ "test.com으로 가기") ``` 상대 경로도 유효합니다. -```markdown +```md [music으로 가기](/music/). ``` @@ -251,7 +251,7 @@ end ## 이미지 이미지는 링크와 같지만 앞에 느낌표가 붙습니다. -```markdown +```md ![이미지의 alt 속성](http://imgur.com/myimage.jpg "제목") ``` @@ -264,18 +264,18 @@ end ## 기타 ### 자동 링크 -```markdown +```md 와 [http://testwebsite.com/](http://testwebsite.com/)는 동일합니다. ``` ### 이메일 자동 링크 -```markdown +```md ``` ### 탈출 문자 -```markdown +```md *별표 사이에 이 텍스트*를 치고 싶지만 기울이고 싶지는 않다면 이렇게 하시면 됩니다. \*별표 사이에 이 텍스트\*. ``` @@ -284,7 +284,7 @@ end 깃헙 전용 마크다운에서는 `` 태그를 이용해 키보드 키를 나타낼 수 있습니다. -```markdown +```md 컴퓨터가 멈췄다면 눌러보세요. Ctrl+Alt+Del ``` @@ -292,14 +292,14 @@ end ### 표 표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면 -```markdown +```md | 1열 | 2열 | 3열 | | :--------| :-------: | --------: | | 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 | | 머시기 | 머시기 | 머시기 | ``` 혹은 -```markdown +```md 1열 | 2열 | 3열 :-- | :-: | --: 으악 너무 못생겼어 | 그만 | 둬 -- cgit v1.2.3 From 94bf9e8544b0f16bc7a94404f14dab69b4786a90 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:37:27 +0530 Subject: Fix build error in 'build/docs/es-es/visualbasic-es/index.html' --- es-es/visualbasic-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown index c7f581c0..ca00626b 100644 --- a/es-es/visualbasic-es.html.markdown +++ b/es-es/visualbasic-es.html.markdown @@ -10,7 +10,7 @@ filename: learnvisualbasic-es.vb lang: es-es --- -```vb +``` Module Module1 Sub Main() -- cgit v1.2.3 From 61abf1c181d787c23fd529807149e872d0651b07 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:38:12 +0530 Subject: Fix build error in 'build/docs/pt-br/visualbasic-pt/index.html' --- pt-br/visualbasic-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index b94ab609..2a7205cd 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -8,7 +8,7 @@ lang: pt-br filename: learnvisualbasic-pt.vb --- -```vb +``` Module Module1 module Module1 -- cgit v1.2.3 From 38ac974e604b932e1be16d8e4bd87c2f46cdae88 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:45:19 +0530 Subject: Fix build error in 'build/docs/es-es/objective-c-es/index.html' --- es-es/objective-c-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index bdbce524..0e680372 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -13,7 +13,7 @@ Objective C es el lenguaje de programación principal utilizado por Apple para l Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk". -```objective_c +```objc // Los comentarios de una sola línea inician con // /* -- cgit v1.2.3 From b57cca8587b0205cd9b9e898143d2dc237a817be Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 17:57:09 +0530 Subject: Fix build error in 'build/docs/cypher/index.html' --- cypher.html.markdown | 68 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/cypher.html.markdown b/cypher.html.markdown index b7be544a..867474a5 100644 --- a/cypher.html.markdown +++ b/cypher.html.markdown @@ -16,19 +16,29 @@ Nodes **Represents a record in a graph.** -```()``` +``` +() +``` It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query. -```(n)``` +``` +(n) +``` It's a *node* referred by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase. -```(p:Person)``` +``` +(p:Person) +``` You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase. -```(p:Person:Manager)``` +``` +(p:Person:Manager) +``` A node can have many *labels*. -```(p:Person {name : 'Théo Gauchoux', age : 22})``` +``` +(p:Person {name : 'Théo Gauchoux', age : 22}) +``` A node can have some *properties*, here **name** and **age**. It begins with lowercase and uses camelCase. The types allowed in properties : @@ -40,7 +50,9 @@ The types allowed in properties : *Warning : there isn't datetime property in Cypher ! You can use String with a specific pattern or a Numeric from a specific date.* -```p.name``` +``` +p.name +``` You can access to a property with the dot style. @@ -49,16 +61,24 @@ Relationships (or Edges) **Connects two nodes** -```[:KNOWS]``` +``` +[:KNOWS] +``` It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE. -```[k:KNOWS]``` +``` +[k:KNOWS] +``` The same *relationship*, referred by the variable **k**, reusable in the query, but it's not necessary. -```[k:KNOWS {since:2017}]``` +``` +[k:KNOWS {since:2017}] +``` The same *relationship*, with *properties* (like *node*), here **since**. -```[k:KNOWS*..4]``` +``` +[k:KNOWS*..4] +``` It's a structural information to use in a *path* (seen later). Here, **\*..4** says "Match the pattern, with the relationship **k** which be repeated between 1 and 4 times. @@ -67,16 +87,24 @@ Paths **The way to mix nodes and relationships.** -```(a:Person)-[:KNOWS]-(b:Person)``` +``` +(a:Person)-[:KNOWS]-(b:Person) +``` A path describing that **a** and **b** know each other. -```(a:Person)-[:MANAGES]->(b:Person)``` +``` +(a:Person)-[:MANAGES]->(b:Person) +``` A path can be directed. This path describes that **a** is the manager of **b**. -```(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)``` +``` +(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person) +``` You can chain multiple relationships. This path describes the friend of a friend. -```(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)``` +``` +(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person) +``` A chain can also be directed. This path describes that **a** is the boss of **b** and the big boss of **c**. Patterns often used (from Neo4j doc) : @@ -230,13 +258,19 @@ DELETE n, r Other useful clauses --- -```PROFILE``` +``` +PROFILE +``` Before a query, show the execution plan of it. -```COUNT(e)``` +``` +COUNT(e) +``` Count entities (nodes or relationships) matching **e**. -```LIMIT x``` +``` +LIMIT x +``` Limit the result to the x first results. -- cgit v1.2.3 From 926a2bdc88314eac0abbc82a1a15545435fec011 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 18:02:42 +0530 Subject: Revert "Fix build error in 'build/docs/es-es/objective-c-es/index.html'" This reverts commit 38ac974e604b932e1be16d8e4bd87c2f46cdae88 as the issue has already been fixed upstream. --- es-es/objective-c-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index 0e680372..bdbce524 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -13,7 +13,7 @@ Objective C es el lenguaje de programación principal utilizado por Apple para l Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk". -```objc +```objective_c // Los comentarios de una sola línea inician con // /* -- cgit v1.2.3 From f95558ff9260d4522cabca1ca112417deb4fd905 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 29 Aug 2018 18:03:27 +0530 Subject: Revert "Fix build error in 'build/docs/cypher/index.html'" This reverts commit b57cca8587b0205cd9b9e898143d2dc237a817be as the issue has already been fixed upstream. --- cypher.html.markdown | 68 +++++++++++++--------------------------------------- 1 file changed, 17 insertions(+), 51 deletions(-) diff --git a/cypher.html.markdown b/cypher.html.markdown index 867474a5..b7be544a 100644 --- a/cypher.html.markdown +++ b/cypher.html.markdown @@ -16,29 +16,19 @@ Nodes **Represents a record in a graph.** -``` -() -``` +```()``` It's an empty *node*, to indicate that there is a *node*, but it's not relevant for the query. -``` -(n) -``` +```(n)``` It's a *node* referred by the variable **n**, reusable in the query. It begins with lowercase and uses camelCase. -``` -(p:Person) -``` +```(p:Person)``` You can add a *label* to your node, here **Person**. It's like a type / a class / a category. It begins with uppercase and uses camelCase. -``` -(p:Person:Manager) -``` +```(p:Person:Manager)``` A node can have many *labels*. -``` -(p:Person {name : 'Théo Gauchoux', age : 22}) -``` +```(p:Person {name : 'Théo Gauchoux', age : 22})``` A node can have some *properties*, here **name** and **age**. It begins with lowercase and uses camelCase. The types allowed in properties : @@ -50,9 +40,7 @@ The types allowed in properties : *Warning : there isn't datetime property in Cypher ! You can use String with a specific pattern or a Numeric from a specific date.* -``` -p.name -``` +```p.name``` You can access to a property with the dot style. @@ -61,24 +49,16 @@ Relationships (or Edges) **Connects two nodes** -``` -[:KNOWS] -``` +```[:KNOWS]``` It's a *relationship* with the *label* **KNOWS**. It's a *label* as the node's label. It begins with uppercase and use UPPER_SNAKE_CASE. -``` -[k:KNOWS] -``` +```[k:KNOWS]``` The same *relationship*, referred by the variable **k**, reusable in the query, but it's not necessary. -``` -[k:KNOWS {since:2017}] -``` +```[k:KNOWS {since:2017}]``` The same *relationship*, with *properties* (like *node*), here **since**. -``` -[k:KNOWS*..4] -``` +```[k:KNOWS*..4]``` It's a structural information to use in a *path* (seen later). Here, **\*..4** says "Match the pattern, with the relationship **k** which be repeated between 1 and 4 times. @@ -87,24 +67,16 @@ Paths **The way to mix nodes and relationships.** -``` -(a:Person)-[:KNOWS]-(b:Person) -``` +```(a:Person)-[:KNOWS]-(b:Person)``` A path describing that **a** and **b** know each other. -``` -(a:Person)-[:MANAGES]->(b:Person) -``` +```(a:Person)-[:MANAGES]->(b:Person)``` A path can be directed. This path describes that **a** is the manager of **b**. -``` -(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person) -``` +```(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)``` You can chain multiple relationships. This path describes the friend of a friend. -``` -(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person) -``` +```(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)``` A chain can also be directed. This path describes that **a** is the boss of **b** and the big boss of **c**. Patterns often used (from Neo4j doc) : @@ -258,19 +230,13 @@ DELETE n, r Other useful clauses --- -``` -PROFILE -``` +```PROFILE``` Before a query, show the execution plan of it. -``` -COUNT(e) -``` +```COUNT(e)``` Count entities (nodes or relationships) matching **e**. -``` -LIMIT x -``` +```LIMIT x``` Limit the result to the x first results. -- cgit v1.2.3 From 3a5c47af61b62b2feb0f414937de30c6f36dabfe Mon Sep 17 00:00:00 2001 From: 0u0 Date: Wed, 29 Aug 2018 21:57:26 +0800 Subject: fix #3054 --- zh-cn/matlab-cn.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index 2fbccfc4..9632e24f 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -113,7 +113,7 @@ b(2) % ans = 符 % 元组(cell 数组) a = {'one', 'two', 'three'} a(1) % ans = 'one' - 返回一个元组 -char(a(1)) % ans = one - 返回一个字符串 +a{1} % ans = one - 返回一个字符串 % 结构体 @@ -210,8 +210,8 @@ size(A) % 返回矩阵的行数和列数,ans = 3 3 A(1, :) =[] % 删除矩阵的第 1 行 A(:, 1) =[] % 删除矩阵的第 1 列 -transpose(A) % 矩阵转置,等价于 A' -ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数) +transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) +ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数),等价于 A' % 元素运算 vs. 矩阵运算 @@ -463,7 +463,7 @@ triu(x) % 返回 x 的上三角这部分 tril(x) % 返回 x 的下三角这部分 cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积) dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长 -transpose(A) % A 的转置,等价于 A' +transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) fliplr(A) % 将一个矩阵左右翻转 flipud(A) % 将一个矩阵上下翻转 -- cgit v1.2.3 From 8f87b5274105271f5683f2099a1b57483575ac3a Mon Sep 17 00:00:00 2001 From: 0u0 Date: Wed, 29 Aug 2018 22:00:37 +0800 Subject: fix #3176 --- zh-cn/matlab-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index 9632e24f..851ca218 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -45,7 +45,7 @@ edit('myfunction.m') % 在编辑器中打开指定函数或脚本 type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码 profile on % 打开 profile 代码分析工具 -profile of % 关闭 profile 代码分析工具 +profile off % 关闭 profile 代码分析工具 profile viewer % 查看 profile 代码分析工具的分析结果 help command % 在命令窗口中显示指定命令的帮助文档 @@ -226,7 +226,7 @@ A .* B % 元素乘法,要求 A 和 B 形状一致(A 的行数等于 B 的 exp(A) % 对矩阵中每个元素做指数运算 expm(A) % 对矩阵整体做指数运算 sqrt(A) % 对矩阵中每个元素做开方运算 -sqrtm(A) % 对矩阵整体做开放运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) +sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) % 绘图 -- cgit v1.2.3 From b0d4255a8000885f4822652967778c8bf537b734 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 00:12:41 +0800 Subject: fix #2672 --- zh-cn/python3-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 211ce0c5..16478fcb 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -362,7 +362,7 @@ else: # else语句是可选的,必须在所有的except之后 filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) # => range(1,10) 是一个实现可迭代接口的对象 +print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一个实现可迭代接口的对象 # 可迭代对象可以遍历 for i in our_iterable: -- cgit v1.2.3 From ad0fb434b06e31f7c608a68ee4fb1b3ffbba4335 Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Wed, 29 Aug 2018 23:19:28 -0400 Subject: update links on haxe.html.markdown --- haxe.html.markdown | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index df2a1e78..98fb3033 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -771,18 +771,17 @@ class UsingExample { We're still only scratching the surface here of what Haxe can do. For a formal overview of all Haxe features, checkout the [online -manual](http://haxe.org/manual), the [online API](http://api.haxe.org/), and -"haxelib", the [haxe library repo] (http://lib.haxe.org/). +manual](https://haxe.org/manual), the [online API docs](https://api.haxe.org/), and +"haxelib", the [haxe library repo](https://lib.haxe.org/). For more advanced topics, consider checking out: -* [Abstract types](http://haxe.org/manual/abstracts) -* [Macros](http://haxe.org/manual/macros), and [Compiler Macros](http://haxe.org/manual/macros_compiler) -* [Tips and Tricks](http://haxe.org/manual/tips_and_tricks) - - -Finally, please join us on [the mailing list](https://groups.google.com/forum/#!forum/haxelang), on IRC [#haxe on -freenode](http://webchat.freenode.net/), or on -[Google+](https://plus.google.com/communities/103302587329918132234). +* [Abstract types](https://haxe.org/manual/types-abstract.html) +* [Macros](https://haxe.org/manual/macro.html) +* [Compiler Features](https://haxe.org/manual/cr-features.html) +Finally, please join us on [the Haxe forum](https://community.haxe.org/), +on IRC [#haxe on +freenode](http://webchat.freenode.net/), or on the +[Haxe Gitter chat](https://gitter.im/HaxeFoundation/haxe). -- cgit v1.2.3 From 60eac5d50054ddae92bd23fb51f3acc1c306a762 Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Wed, 29 Aug 2018 23:52:31 -0400 Subject: Update haxe.html.markdown Better wording for the "see also" links. --- haxe.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 98fb3033..afb9d1a3 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -770,9 +770,9 @@ class UsingExample { ``` We're still only scratching the surface here of what Haxe can do. For a formal -overview of all Haxe features, checkout the [online -manual](https://haxe.org/manual), the [online API docs](https://api.haxe.org/), and -"haxelib", the [haxe library repo](https://lib.haxe.org/). +overview of all Haxe features, see the [manual](https://haxe.org/manual) and +the [API docs](https://api.haxe.org/). For a comprehensive directory of available +third-party Haxe libraries, see [Haxelib](https://lib.haxe.org/). For more advanced topics, consider checking out: -- cgit v1.2.3 From 93a7d100c2d9f3831a9436b83f513624b99630f7 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 19:00:20 +0800 Subject: fix #3054 --- matlab.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index b88b1c03..9cf1f8a4 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -221,11 +221,11 @@ A(1, :) =[] % Delete the first row of the matrix A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: -A one +A.' % Concise version of transpose (without taking complex conjugate) ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) A' % Concise version of complex transpose -A.' % Concise version of transpose (without taking complex conjugate) + -- cgit v1.2.3 From 130cacf7bfc3d10e19023227efe74d1f23dbe552 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 19:01:57 +0800 Subject: it-it fix #3054 --- it-it/matlab-it.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown index 8d6d4385..38be8848 100644 --- a/it-it/matlab-it.html.markdown +++ b/it-it/matlab-it.html.markdown @@ -199,8 +199,7 @@ size(A) % ans = 3 3 A(1, :) =[] % Rimuove la prima riga della matrice A(:, 1) =[] % Rimuove la prima colonna della matrice -transpose(A) % Traspone la matrice, equivale a: -A one +transpose(A) % Traspone la matrice, equivale a: A.' ctranspose(A) % Trasposizione hermitiana della matrice % (ovvero il complesso coniugato di ogni elemento della matrice trasposta) -- cgit v1.2.3 From 4d2626d98bfa5ada3a502cda15c416db16ceac5a Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 19:02:36 +0800 Subject: pt-br fix #3054 --- pt-br/matlab-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown index eb660d4c..5ed6b7ba 100644 --- a/pt-br/matlab-pt.html.markdown +++ b/pt-br/matlab-pt.html.markdown @@ -206,8 +206,7 @@ size(A) % Resposta = 3 3 A(1, :) =[] % Remove a primeira linha da matriz A(:, 1) =[] % Remove a primeira coluna da matriz -transpose(A) % Transposta a matriz, que é o mesmo de: -A one +transpose(A) % Transposta a matriz, que é o mesmo de: A.' ctranspose(A) % Transposta a matriz % (a transposta, seguida pelo conjugado complexo de cada elemento) -- cgit v1.2.3 From 3a76acef98b53e8cd6759662b41ee521827791e1 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 20:32:12 +0800 Subject: Update to Julia 1.0 (Finish 3/6) --- zh-cn/julia-cn.html.markdown | 359 ++++++++++++++++++++++++------------------- 1 file changed, 203 insertions(+), 156 deletions(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 1f91d52c..6c94aa2f 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -5,10 +5,11 @@ contributors: - ["Jichao Ouyang", "http://oyanglul.us"] translators: - ["Jichao Ouyang", "http://oyanglul.us"] + - ["woclass", "https://github.com/inkydragon"] lang: zh-cn --- -```ruby +```julia # 单行注释只需要一个井号 #= 多行注释 只需要以 '#=' 开始 '=#' 结束 @@ -19,41 +20,41 @@ lang: zh-cn ## 1. 原始类型与操作符 #################################################### -# Julia 中一切皆是表达式。 - -# 这是一些基本数字类型. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2//3 # => 2//3 (Rational{Int64}) - -# 支持所有的普通中缀操作符。 -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 -5 / 2 # => 2.5 # 用 Int 除 Int 永远返回 Float -div(5, 2) # => 2 # 使用 div 截断小数点 -5 \ 35 # => 7.0 -2 ^ 2 # => 4 # 次方, 不是二进制 xor -12 % 10 # => 2 +# Julia 中一切皆为表达式 + +# 这是一些基本数字类型 +typeof(3) # => Int64 +typeof(3.2) # => Float64 +typeof(2 + 1im) # => Complex{Int64} +typeof(2 // 3) # => Rational{Int64} + +# 支持所有的普通中缀操作符 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +10 / 2 # => 5.0 # 整数除法总是返回浮点数 +div(5, 2) # => 2 # 使用 div 可以获得整除的结果 +5 \ 35 # => 7.0 +2^2 # => 4 # 幂运算,不是异或 (xor) +12 % 10 # => 2 # 用括号提高优先级 (1 + 3) * 2 # => 8 -# 二进制操作符 -~2 # => -3 # 非 -3 & 5 # => 1 # 与 -2 | 4 # => 6 # 或 -2 $ 4 # => 6 # 异或 -2 >>> 1 # => 1 # 逻辑右移 -2 >> 1 # => 1 # 算术右移 -2 << 1 # => 4 # 逻辑/算术 右移 - -# 可以用函数 bits 查看二进制数。 -bits(12345) +# 位操作符 +~2 # => -3 # 按位非 (not) +3 & 5 # => 1 # 按位与 (and) +2 | 4 # => 6 # 按位或 (or) +xor(2, 4) # => 6 # 按位异或 (xor) +2 >>> 1 # => 1 # 逻辑右移 +2 >> 1 # => 1 # 算术右移 +2 << 1 # => 4 # 逻辑/算术左移 + +# 可以用函数 bitstring 查看二进制数。 +bitstring(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" -bits(12345.0) +bitstring(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" # 布尔值是原始类型 @@ -61,17 +62,18 @@ true false # 布尔操作符 -!true # => false -!false # => true -1 == 1 # => true -2 == 1 # => false -1 != 1 # => false -2 != 1 # => true -1 < 10 # => true -1 > 10 # => false -2 <= 2 # => true -2 >= 2 # => true -# 比较可以串联 +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true + +# 链式比较 1 < 2 < 3 # => true 2 < 3 < 2 # => false @@ -82,7 +84,8 @@ false 'a' # 可以像取数组取值一样用 index 取出对应字符 -"This is a string"[1] # => 'T' # Julia 的 index 从 1 开始 :( +ascii("This is a string")[1] # => 'T' +# Julia 的 index 从 1 开始 :( # 但是对 UTF-8 无效, # 因此建议使用遍历器 (map, for loops, 等). @@ -90,12 +93,18 @@ false "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # 可以将任何 Julia 表达式放入括号。 -# 另一种格式化字符串的方式是 printf 宏. -@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# 另一种输出格式化字符串的方法是使用标准库 Printf 中的 Printf 宏 +using Printf +@printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000 # 打印字符串很容易 println("I'm Julia. Nice to meet you!") +# 字符串可以按字典序进行比较 +"good" > "bye" # => true +"good" == "good" # => true +"1 + 2 = 3" == "1 + 2 = $(1 + 2)" # => true + #################################################### ## 2. 变量与集合 #################################################### @@ -106,12 +115,12 @@ some_var # => 5 # 访问未声明变量会抛出异常 try - some_other_var # => ERROR: some_other_var not defined + some_other_var # => ERROR: UndefVarError: some_other_var not defined catch e println(e) end -# 变量名需要以字母开头. +# 变量名必须以下划线或字母开头 # 之后任何字母,数字,下划线,叹号都是合法的。 SomeOtherVar123! = 6 # => 6 @@ -122,7 +131,7 @@ SomeOtherVar123! = 6 # => 6 # 注意 Julia 的命名规约: # -# * 变量名为小写,单词之间以下划线连接('\_')。 +# * 变量名为小写,单词之间以下划线连接 "_" 。 # # * 类型名以大写字母开头,单词以 CamelCase 方式连接。 # @@ -131,57 +140,81 @@ SomeOtherVar123! = 6 # => 6 # * 会改变输入的函数名末位为 !。 # 这类函数有时被称为 mutating functions 或 in-place functions. -# 数组存储一列值,index 从 1 开始。 -a = Int64[] # => 0-element Int64 Array +# 数组存储一列值,index 从 1 开始 +a = Int64[] # => 0-element Array{Int64,1} + +# 一维数组可以以逗号分隔值的方式声明 +b = [4, 5, 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b = [4; 5; 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 -# 一维数组可以以逗号分隔值的方式声明。 -b = [4, 5, 6] # => 包含 3 个 Int64 类型元素的数组: [4, 5, 6] -b[1] # => 4 -b[end] # => 6 +# 二维数组以分号分隔维度 +matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4] -# 二维数组以分号分隔维度。 -matrix = [1 2; 3 4] # => 2x2 Int64 数组: [1 2; 3 4] +# 指定数组的类型 +b = Int8[4, 5, 6] # => 3-element Array{Int8,1}: [4, 5, 6] # 使用 push! 和 append! 往数组末尾添加元素 -push!(a,1) # => [1] -push!(a,2) # => [1,2] -push!(a,4) # => [1,2,4] -push!(a,3) # => [1,2,4,3] -append!(a,b) # => [1,2,4,3,4,5,6] +push!(a, 1) # => [1] +push!(a, 2) # => [1,2] +push!(a, 4) # => [1,2,4] +push!(a, 3) # => [1,2,4,3] +append!(a, b) # => [1,2,4,3,4,5,6] -# 用 pop 弹出末尾元素 -pop!(b) # => 6 and b is now [4,5] +# 用 pop 弹出尾部的元素 +pop!(b) # => 6 +b # => [4,5] -# 可以再放回去 -push!(b,6) # b 又变成了 [4,5,6]. +# 再放回去 +push!(b, 6) # => [4,5,6] +b # => [4,5,6] -a[1] # => 1 # 永远记住 Julia 的 index 从 1 开始! +a[1] # => 1 # 永远记住 Julia 的引索从 1 开始!而不是 0! # 用 end 可以直接取到最后索引. 可用作任何索引表达式 a[end] # => 6 -# 还支持 shift 和 unshift -shift!(a) # => 返回 1,而 a 现在时 [2,4,3,4,5,6] -unshift!(a,7) # => [7,2,4,3,4,5,6] +# 数组还支持 popfirst! 和 pushfirst! +popfirst!(a) # => 1 +a # => [2,4,3,4,5,6] +pushfirst!(a, 7) # => [7,2,4,3,4,5,6] +a # => [7,2,4,3,4,5,6] # 以叹号结尾的函数名表示它会改变参数的值 -arr = [5,4,6] # => 包含三个 Int64 元素的数组: [5,4,6] -sort(arr) # => [4,5,6]; arr 还是 [5,4,6] -sort!(arr) # => [4,5,6]; arr 现在是 [4,5,6] +arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] +arr # => [5,4,6] +sort!(arr) # => [4,5,6] +arr # => [4,5,6] -# 越界会抛出 BoundsError 异常 +# 数组越界会抛出 BoundsError try - a[0] # => ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 + a[0] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [0] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:188 + a[end + 1] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [8] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:196 catch e println(e) end -# 错误会指出发生的行号,包括标准库 -# 如果你有 Julia 源代码,你可以找到这些地方 +# 报错时错误会指出出错的文件位置以及行号,标准库也一样 +# 你可以在 Julia 安装目录下的 share/julia 文件夹里找到这些标准库 # 可以用 range 初始化数组 -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5] # 可以切割数组 a[1:3] # => [1, 2, 3] @@ -189,11 +222,13 @@ a[2:end] # => [2, 3, 4, 5] # 用 splice! 切割原数组 arr = [3,4,5] -splice!(arr,2) # => 4 ; arr 变成了 [3,5] +splice!(arr, 2) # => 4 +arr # => [3,5] # 用 append! 连接数组 b = [1,2,3] -append!(a,b) # a 变成了 [1, 2, 3, 4, 5, 1, 2, 3] +append!(a, b) # => [1, 2, 3, 4, 5, 1, 2, 3] +a # => [1, 2, 3, 4, 5, 1, 2, 3] # 检查元素是否在数组中 in(1, a) # => true @@ -201,162 +236,174 @@ in(1, a) # => true # 用 length 获得数组长度 length(a) # => 8 -# Tuples 是 immutable 的 -tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +# 元组(Tuples)是不可变的 +tup = (1, 2, 3) # => (1,2,3) +typeof(tup) # => Tuple{Int64,Int64,Int64} tup[1] # => 1 -try: - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +try + tup[1] = 3 + # => ERROR: MethodError: no method matching + # setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64) catch e println(e) end -# 大多数组的函数同样支持 tuples +# 大多数组的函数同样支持元组 length(tup) # => 3 -tup[1:2] # => (1,2) -in(2, tup) # => true +tup[1:2] # => (1,2) +in(2, tup) # => true -# 可以将 tuples 元素分别赋给变量 -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# 可以将元组的元素解包赋给变量 +a, b, c = (1, 2, 3) # => (1,2,3) +a # => 1 +b # => 2 +c # => 3 # 不用括号也可以 -d, e, f = 4, 5, 6 # => (4,5,6) +d, e, f = 4, 5, 6 # => (4,5,6) +d # => 4 +e # => 5 +f # => 6 # 单元素 tuple 不等于其元素值 (1,) == 1 # => false -(1) == 1 # => true +(1) == 1 # => true # 交换值 -e, d = d, e # => (5,4) # d is now 5 and e is now 4 +e, d = d, e # => (5,4) +d # => 5 +e # => 4 # 字典Dictionaries store mappings -empty_dict = Dict() # => Dict{Any,Any}() +empty_dict = Dict() # => Dict{Any,Any} with 0 entries # 也可以用字面量创建字典 -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] -# => Dict{ASCIIString,Int64} +filled_dict = Dict("one" => 1, "two" => 2, "three" => 3) +# => Dict{String,Int64} with 3 entries: +# => "two" => 2, "one" => 1, "three" => 3 # 用 [] 获得键值 filled_dict["one"] # => 1 # 获得所有键 keys(filled_dict) -# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: +# => "two", "one", "three" # 注意,键的顺序不是插入时的顺序 # 获得所有值 values(filled_dict) -# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: +# => 2, 1, 3 # 注意,值的顺序也一样 # 用 in 检查键值是否已存在,用 haskey 检查键是否存在 -in(("one", 1), filled_dict) # => true -in(("two", 3), filled_dict) # => false -haskey(filled_dict, "one") # => true -haskey(filled_dict, 1) # => false +in(("one" => 1), filled_dict) # => true +in(("two" => 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false # 获取不存在的键的值会抛出异常 try - filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 + filled_dict["four"] # => ERROR: KeyError: key "four" not found catch e println(e) end # 使用 get 可以提供默认值来避免异常 # get(dictionary,key,default_value) -get(filled_dict,"one",4) # => 1 -get(filled_dict,"four",4) # => 4 +get(filled_dict, "one", 4) # => 1 +get(filled_dict, "four", 4) # => 4 -# 用 Sets 表示无序不可重复的值的集合 -empty_set = Set() # => Set{Any}() -# 初始化一个 Set 并定义其值 -filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# Sets 表示无序不可重复的值的集合 +empty_set = Set() # => Set(Any[]) +# 初始化一个带初值的 Set +filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) -# 添加值 -push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) +# 新增值 +push!(filled_set, 5) # => Set([4, 2, 3, 5, 1]) -# 检查是否存在某值 -in(2, filled_set) # => true -in(10, filled_set) # => false +# 检查 Set 中是否存在某值 +in(2, filled_set) # => true +in(10, filled_set) # => false # 交集,并集,差集 -other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) -intersect(filled_set, other_set) # => Set{Int64}(3,4,5) -union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +other_set = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) +intersect(filled_set, other_set) # => Set([4, 3, 5]) +union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1]) +setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) #################################################### -## 3. 控制流 +## 3. 控制语句 #################################################### # 声明一个变量 some_var = 5 -# 这是一个 if 语句,缩进不是必要的 +# 这是一个 if 语句块,其中的缩进不是必须的 if some_var > 10 println("some_var is totally bigger than 10.") -elseif some_var < 10 # elseif 是可选的. +elseif some_var < 10 # elseif 是可选的 println("some_var is smaller than 10.") -else # else 也是可选的. +else # else 也是可选的 println("some_var is indeed 10.") end -# => prints "some var is smaller than 10" +# => some_var is smaller than 10. # For 循环遍历 -# Iterable 类型包括 Range, Array, Set, Dict, 以及 String. -for animal=["dog", "cat", "mouse"] +# 可迭代的类型包括:Range, Array, Set, Dict 和 AbstractString +for animal = ["dog", "cat", "mouse"] println("$animal is a mammal") - # 可用 $ 将 variables 或 expression 转换为字符串into strings + # 你可以用 $ 将变量或表达式插入字符串中 end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal -# You can use 'in' instead of '='. +# 你也可以不用 '=' 而使用 'in' for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal -for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] - println("$(a[1]) is a $(a[2])") +for pair in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") + from, to = pair + println("$from is a $to") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal +# 注意!这里的输出顺序和上面的不同 -for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for (k, v) in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") println("$k is a $v") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal # While 循环 -x = 0 -while x < 4 - println(x) - x += 1 # x = x + 1 +let x = 0 + while x < 4 + println(x) + x += 1 # x = x + 1 的缩写 + end end -# prints: -# 0 -# 1 -# 2 -# 3 +# => 0 +# => 1 +# => 2 +# => 3 # 用 try/catch 处理异常 try - error("help") + error("help") catch e - println("caught it $e") + println("caught it $e") end # => caught it ErrorException("help") -- cgit v1.2.3 From efd37d969547b5a2a9beaa0a874364b24a8f6e4d Mon Sep 17 00:00:00 2001 From: 0u0 Date: Thu, 30 Aug 2018 20:42:42 +0800 Subject: Correct contributors --- zh-cn/julia-cn.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 6c94aa2f..f9c68eb6 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -2,7 +2,9 @@ language: Julia filename: learn-julia-zh.jl contributors: - - ["Jichao Ouyang", "http://oyanglul.us"] + - ["Leah Hanson", "http://leahhanson.us"] + - ["Pranit Bauva", "https://github.com/pranitbauva1997"] + - ["Daniel YC Lin", "https://github.com/dlintw"] translators: - ["Jichao Ouyang", "http://oyanglul.us"] - ["woclass", "https://github.com/inkydragon"] -- cgit v1.2.3 From 6d8c4b191128721aa82c8deaf9fb56cc1cccd5c9 Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Thu, 30 Aug 2018 18:42:55 +0300 Subject: Start translating jQuery into Russian --- ru-ru/jquery-ru.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 ru-ru/jquery-ru.html.markdown diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown new file mode 100644 index 00000000..d91f14a7 --- /dev/null +++ b/ru-ru/jquery-ru.html.markdown @@ -0,0 +1,19 @@ +--- +category: tool +tool: jquery +contributors: + - ["Sawyer Charles", "https://github.com/xssc"] +translators: + - ["Ev Bogdanov", "https://github.com/evbogdanov"] +lang: ru-ru +filename: jquery-ru.js +--- + +jQuery — это библиотека JavaScript, которая помогает "делать больше, писать меньше". Она выполняет множество типичных JavaScript-задач, упрощая написание кода. jQuery используется крупными компаниями и разработчиками со всего мира. Она упрощает и ускоряет работу с AJAX, с событиями, с DOM и со многим другим. + +Поскольку jQuery является библиотекой JavaScript, сначала вам следует [изучить JavaScript](https://learnxinyminutes.com/docs/ru-ru/javascript-ru/). + +```js + + +``` -- cgit v1.2.3 From cf3736c7f1965c7756ca9126428580f302dcb139 Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Thu, 30 Aug 2018 22:55:47 +0300 Subject: Translate topic: Selectors --- ru-ru/jquery-ru.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index d91f14a7..b99be215 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -16,4 +16,16 @@ jQuery — это библиотека JavaScript, которая помогае ```js +/////////////////////////////////// +// 1. Селекторы + +// Для получения элемента в jQuery используются селекторы +var page = $(window); // Получить страницу целиком + +// В качестве селектора может выступать CSS-селектор +var paragraph = $('p'); // Получить все

элементы +var table1 = $('#table1'); // Получить элемент с идентификатором 'table1' +var squares = $('.square'); // Получить все элементы с классом 'square' +var square_p = $('p.square') // Получить

элементы с классом 'square' + ``` -- cgit v1.2.3 From d8beb0651810ea77d31ef5b337d5863ee1ace72c Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Thu, 30 Aug 2018 23:53:46 +0300 Subject: Translate topic: Events and Effects (part I) --- ru-ru/jquery-ru.html.markdown | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index b99be215..473418e1 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -28,4 +28,33 @@ var table1 = $('#table1'); // Получить элемент с идентиф var squares = $('.square'); // Получить все элементы с классом 'square' var square_p = $('p.square') // Получить

элементы с классом 'square' + +/////////////////////////////////// +// 2. События и эффекты +// jQuery прекрасно справляется с обработкой событий +// Часто используемое событие — это событие документа 'ready' +// Вы можете использовать метод 'ready', который сработает, как только документ полностью загрузится +$(document).ready(function(){ + // Код не выполнится до тех пор, пока документ не будет загружен +}); +// Обработку события можно вынести в отдельную функцию +function onAction() { + // Код выполнится, когда произойдёт событие +} +$('#btn').click(onAction); // Обработчик события сработает при клике + +// Другие распространенные события: +$('#btn').dblclick(onAction); // Двойной клик +$('#btn').hover(onAction); // Наведение курсора +$('#btn').focus(onAction); // Фокус +$('#btn').blur(onAction); // Потеря фокуса +$('#btn').submit(onAction); // Отправка формы +$('#btn').select(onAction); // Когда выбрали элемент +$('#btn').keydown(onAction); // Когда нажали клавишу +$('#btn').keyup(onAction); // Когда отпустили клавишу +$('#btn').keypress(onAction); // Когда нажали символьную клавишу (нажатие привело к появлению символа) +$('#btn').mousemove(onAction); // Когда переместили курсор мыши +$('#btn').mouseenter(onAction); // Когда навели курсор на элемент +$('#btn').mouseleave(onAction); // Когда сдвинули курсор с элемента + ``` -- cgit v1.2.3 From 656ef60a392e5d94000aa5ad5150bbc0ddac279c Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Fri, 31 Aug 2018 00:57:46 +0300 Subject: Translate topic: Events and Effects (part II) --- ru-ru/jquery-ru.html.markdown | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index 473418e1..47571589 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -57,4 +57,46 @@ $('#btn').mousemove(onAction); // Когда переместили курсор $('#btn').mouseenter(onAction); // Когда навели курсор на элемент $('#btn').mouseleave(onAction); // Когда сдвинули курсор с элемента + +// Вы можете не только обрабатывать события, но и вызывать их +$('#btn').dblclick(); // Вызвать двойной клик на элементе + +// Для одного селектора возможно назначить несколько обработчиков событий +$('#btn').on( + {dblclick: myFunction1} // Обработать двойной клик + {blur: myFunction1} // Обработать исчезновение фокуса +); + +// Вы можете перемещать и прятать элементы с помощью методов-эффектов +$('.table').hide(); // Спрятать элемент(ы) + +// Обратите внимание: вызов функции в этих методах всё равно спрячет сам элемент +$('.table').hide(function(){ + // Сначала спрятать элемент, затем вызвать функцию +}); + +// Вы можете хранить селекторы в переменных +var tables = $('.table'); + +// Некоторые основные методы для манипуляций с документом: +tables.hide(); // Спрятать элемент(ы) +tables.show(); // Показать элемент(ы) +tables.toggle(); // Спрятать/показать +tables.fadeOut(); // Плавное исчезновение +tables.fadeIn(); // Плавное появление +tables.fadeToggle(); // Плавное исчезновение или появление +tables.fadeTo(0.5); // Изменение прозрачности +tables.slideUp(); // Свернуть элемент +tables.slideDown(); // Развернуть элемент +tables.slideToggle(); // Свернуть или развернуть + +// Все эти методы принимают скорость (в миллисекундах) и функцию обратного вызова +tables.hide(1000, myFunction); // Анимация длится 1 секунду, затем вызов функции + +// В методе 'fadeTo' вторым параметром обязательно идёт прозрачность +tables.fadeTo(2000, 0.1, myFunction); // Прозрачность меняется в течение 2 секунд до 0.1, затем вызывается функция + +// Метод 'animate' позволяет делать более продвинутую анимацию +tables.animate({"margin-top": "+=50", height: "100px"}, 500, myFunction); + ``` -- cgit v1.2.3 From df78ed16d458989986eac7d0d2ee71e531f9c505 Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Fri, 31 Aug 2018 01:38:51 +0300 Subject: Translate topic: Manipulation --- ru-ru/jquery-ru.html.markdown | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index 47571589..54c91bf5 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -43,7 +43,7 @@ function onAction() { } $('#btn').click(onAction); // Обработчик события сработает при клике -// Другие распространенные события: +// Другие распространённые события: $('#btn').dblclick(onAction); // Двойной клик $('#btn').hover(onAction); // Наведение курсора $('#btn').focus(onAction); // Фокус @@ -99,4 +99,28 @@ tables.fadeTo(2000, 0.1, myFunction); // Прозрачность меняетс // Метод 'animate' позволяет делать более продвинутую анимацию tables.animate({"margin-top": "+=50", height: "100px"}, 500, myFunction); + +/////////////////////////////////// +// 3. Манипуляции + +// Манипуляции похожи на эффекты, но позволяют добиться большего +$('div').addClass('taming-slim-20'); // Добавить класс 'taming-slim-20' ко всем

элементам + +// Часто встречающиеся методы манипуляций +$('p').append('Hello world'); // Добавить в конец элемента +$('p').attr('class'); // Получить атрибут +$('p').attr('class', 'content'); // Установить атрибут +$('p').hasClass('taming-slim-20'); // Проверить наличие класса +$('p').height(); // Получить или установить высоту элемента + +// Во многих этих методах получение информации вернёт значение ТОЛЬКО для первого элемента +$('p').height(); // Получить высоту только для первого

элемента + +// Метод 'each' позволяет пройтись по всем выбранным элементам +var heights = []; +$('p').each(function() { + heights.push($(this).height()); // Добавить высоту всех

элементов в массив +}); + + ``` -- cgit v1.2.3 From d9d04d38d85133243521e5b61383daf252ed462a Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Fri, 31 Aug 2018 01:54:17 +0300 Subject: A better explanation of the Manipulation topic --- ru-ru/jquery-ru.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index 54c91bf5..d6661836 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -113,10 +113,11 @@ $('p').attr('class', 'content'); // Установить атрибут $('p').hasClass('taming-slim-20'); // Проверить наличие класса $('p').height(); // Получить или установить высоту элемента -// Во многих этих методах получение информации вернёт значение ТОЛЬКО для первого элемента -$('p').height(); // Получить высоту только для первого

элемента -// Метод 'each' позволяет пройтись по всем выбранным элементам +// Во многих методах вам доступна информация ТОЛЬКО о первом элементе из выбранных +$('p').height(); // Вы получите высоту только для первого

элемента + +// Метод 'each' позволяет это исправить и пройтись по всем выбранным вами элементам var heights = []; $('p').each(function() { heights.push($(this).height()); // Добавить высоту всех

элементов в массив -- cgit v1.2.3 From b622673dae3441f1260401fbb44d90e0e4aea6a2 Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Fri, 31 Aug 2018 02:08:20 +0300 Subject: Slightly improve text for JS learning --- ru-ru/jquery-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/jquery-ru.html.markdown b/ru-ru/jquery-ru.html.markdown index d6661836..471b4e24 100644 --- a/ru-ru/jquery-ru.html.markdown +++ b/ru-ru/jquery-ru.html.markdown @@ -11,7 +11,7 @@ filename: jquery-ru.js jQuery — это библиотека JavaScript, которая помогает "делать больше, писать меньше". Она выполняет множество типичных JavaScript-задач, упрощая написание кода. jQuery используется крупными компаниями и разработчиками со всего мира. Она упрощает и ускоряет работу с AJAX, с событиями, с DOM и со многим другим. -Поскольку jQuery является библиотекой JavaScript, сначала вам следует [изучить JavaScript](https://learnxinyminutes.com/docs/ru-ru/javascript-ru/). +Поскольку jQuery является библиотекой JavaScript, вам следует начать с [изучения JavaScript](https://learnxinyminutes.com/docs/ru-ru/javascript-ru/). ```js -- cgit v1.2.3 From 207e16a93181e1ccf057a04ca4e1a1a1e2d59491 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 07:55:10 +0800 Subject: Update to Julia 1.0 (Finish 6/6) --- zh-cn/julia-cn.html.markdown | 479 ++++++++++++++++++++++++------------------- 1 file changed, 272 insertions(+), 207 deletions(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index f9c68eb6..35c2e2d4 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -336,7 +336,6 @@ intersect(filled_set, other_set) # => Set([4, 3, 5]) union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1]) setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) - #################################################### ## 3. 控制语句 #################################################### @@ -409,81 +408,88 @@ catch e end # => caught it ErrorException("help") - #################################################### ## 4. 函数 #################################################### -# 用关键字 'function' 可创建一个新函数 -#function name(arglist) -# body... -#end +# 关键字 'function' 用于定义函数 +# function name(arglist) +# body... +# end function add(x, y) println("x is $x and y is $y") - # 最后一行语句的值为返回 + # 函数会返回最后一行的值 x + y end -add(5, 6) # => 在 "x is 5 and y is 6" 后会打印 11 +add(5, 6) +# => x is 5 and y is 6 +# => 11 + +# 更紧凑的定义函数 +f_add(x, y) = x + y # => f_add (generic function with 1 method) +f_add(3, 4) # => 7 + +# 函数可以将多个值作为元组返回 +fn(x, y) = x + y, x - y # => fn (generic function with 1 method) +fn(3, 4) # => (7, -1) # 还可以定义接收可变长参数的函数 function varargs(args...) return args - # 关键字 return 可在函数内部任何地方返回 + # 使用 return 可以在函数内的任何地方返回 end # => varargs (generic function with 1 method) varargs(1,2,3) # => (1,2,3) -# 省略号 ... 被称为 splat. +# 省略号 ... 称为 splat # 刚刚用在了函数定义中 -# 还可以用在函数的调用 -# Array 或者 Tuple 的内容会变成参数列表 -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 获得一个 Array 的 Set -Set([1,2,3]...) # => Set{Int64}(1,2,3) # 相当于 Set(1,2,3) - -x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # 一个 Tuple 的 Set -Set(x...) # => Set{Int64}(2,3,1) +# 在调用函数时也可以使用它,此时它会把数组或元组解包为参数列表 +add([5,6]...) # 等价于 add(5,6) +x = (5, 6) # => (5,6) +add(x...) # 等价于 add(5,6) -# 可定义可选参数的函数 -function defaults(a,b,x=5,y=6) +# 可定义带可选参数的函数 +function defaults(a, b, x=5, y=6) return "$a $b and $x $y" end +# => defaults (generic function with 3 methods) -defaults('h','g') # => "h g and 5 6" -defaults('h','g','j') # => "h g and j 6" -defaults('h','g','j','k') # => "h g and j k" +defaults('h', 'g') # => "h g and 5 6" +defaults('h', 'g', 'j') # => "h g and j 6" +defaults('h', 'g', 'j', 'k') # => "h g and j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # => ERROR: MethodError: no method matching defaults(::Char) + defaults() # => ERROR: MethodError: no method matching defaults() catch e println(e) end -# 还可以定义键值对的参数 -function keyword_args(;k1=4,name2="hello") # note the ; - return ["k1"=>k1,"name2"=>name2] +# 还可以定义带关键字参数的函数 +function keyword_args(;k1=4, name2="hello") # 注意分号 ';' + return Dict("k1" => k1, "name2" => name2) end +# => keyword_args (generic function with 1 method) -keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] -keyword_args() # => ["name2"=>"hello","k1"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness", "k1"=>4] +keyword_args(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] +keyword_args() # => ["name2"=>"hello", "k1"=>4] -# 可以组合各种类型的参数在同一个函数的参数列表中 +# 可以在一个函数中组合各种类型的参数 function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") println("optional arg: $optional_positional_arg") println("keyword arg: $keyword_arg") end +# => all_the_args (generic function with 2 methods) all_the_args(1, 3, keyword_arg=4) -# prints: -# normal arg: 1 -# optional arg: 3 -# keyword arg: 4 +# => normal arg: 1 +# => optional arg: 3 +# => keyword arg: 4 # Julia 有一等函数 function create_adder(x) @@ -492,14 +498,16 @@ function create_adder(x) end return adder end +# => create_adder (generic function with 1 method) # 这是用 "stabby lambda syntax" 创建的匿名函数 (x -> x > 2)(3) # => true -# 这个函数和上面的 create_adder 一模一样 +# 这个函数和上面的 create_adder 是等价的 function create_adder(x) y -> x + y end +# => create_adder (generic function with 1 method) # 你也可以给内部函数起个名字 function create_adder(x) @@ -508,18 +516,19 @@ function create_adder(x) end adder end +# => create_adder (generic function with 1 method) -add_10 = create_adder(10) -add_10(3) # => 13 - +add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) + # (generic function with 1 method) +add_10(3) # => 13 # 内置的高阶函数有 -map(add_10, [1,2,3]) # => [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# 还可以使用 list comprehensions 替代 map -[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# 还可以使用 list comprehensions 让 map 更美观 +[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### ## 5. 类型 @@ -531,248 +540,304 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] typeof(5) # => Int64 # 类型是一等值 -typeof(Int64) # => DataType -typeof(DataType) # => DataType +typeof(Int64) # => DataType +typeof(DataType) # => DataType # DataType 是代表类型的类型,也代表他自己的类型 -# 类型可用作文档化,优化,以及调度 -# 并不是静态检查类型 +# 类型可用于文档化代码、执行优化以及多重派分(dispatch) +# Julia 并不只是静态的检查类型 # 用户还可以自定义类型 -# 跟其他语言的 records 或 structs 一样 -# 用 `type` 关键字定义新的类型 +# 就跟其它语言的 records 或 structs 一样 +# 用 `struct` 关键字定义新的类型 -# type Name +# struct Name # field::OptionalType # ... # end -type Tiger - taillength::Float64 - coatcolor # 不附带类型标注的相当于 `::Any` +struct Tiger + taillength::Float64 + coatcolor # 不带类型标注相当于 `::Any` end -# 构造函数参数是类型的属性 -tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") +# 默认构造函数的参数是类型的属性,按类型定义中的顺序排列 +tigger = Tiger(3.5, "orange") # => Tiger(3.5, "orange") # 用新类型作为构造函数还会创建一个类型 -sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") +sherekhan = typeof(tigger)(5.6, "fire") # => Tiger(5.6, "fire") -# struct 类似的类型被称为具体类型 -# 他们可被实例化但不能有子类型 +# 类似 struct 的类型被称为具体类型 +# 它们可被实例化,但不能有子类型 # 另一种类型是抽象类型 -# abstract Name -abstract Cat # just a name and point in the type hierarchy +# 抽象类型名 +abstract type Cat end # 仅仅是指向类型结构层次的一个名称 -# 抽象类型不能被实例化,但是可以有子类型 +# 抽象类型不能被实例化,但可以有子类型 # 例如,Number 就是抽象类型 -subtypes(Number) # => 6-element Array{Any,1}: - # Complex{Float16} - # Complex{Float32} - # Complex{Float64} - # Complex{T<:Real} - # ImaginaryUnit - # Real -subtypes(Cat) # => 0-element Array{Any,1} - -# 所有的类型都有父类型; 可以用函数 `super` 得到父类型. +subtypes(Number) # => 2-element Array{Any,1}: + # => Complex + # => Real +subtypes(Cat) # => 0-element Array{Any,1} + +# AbstractString,类如其名,也是一个抽象类型 +subtypes(AbstractString) # => 4-element Array{Any,1}: + # => String + # => SubString + # => SubstitutionString + # => Test.GenericString + +# 所有的类型都有父类型。可以用函数 `supertype` 得到父类型 typeof(5) # => Int64 -super(Int64) # => Signed -super(Signed) # => Real -super(Real) # => Number -super(Number) # => Any -super(super(Signed)) # => Number -super(Any) # => Any -# 所有这些类型,除了 Int64, 都是抽象类型. - -# <: 是类型集成操作符 -type Lion <: Cat # Lion 是 Cat 的子类型 - mane_color - roar::String +supertype(Int64) # => Signed +supertype(Signed) # => Integer +supertype(Integer) # => Real +supertype(Real) # => Number +supertype(Number) # => Any +supertype(supertype(Signed)) # => Real +supertype(Any) # => Any +# 除了 Int64 外,其余的类型都是抽象类型 +typeof("fire") # => String +supertype(String) # => AbstractString +supertype(AbstractString) # => Any +supertype(SubString) # => AbstractString + +# <: 是子类型化操作符 +struct Lion <: Cat # Lion 是 Cat 的子类型 + mane_color + roar::AbstractString end # 可以继续为你的类型定义构造函数 -# 只需要定义一个同名的函数 -# 并调用已有的构造函数设置一个固定参数 -Lion(roar::String) = Lion("green",roar) -# 这是一个外部构造函数,因为他再类型定义之外 - -type Panther <: Cat # Panther 也是 Cat 的子类型 - eye_color - Panther() = new("green") - # Panthers 只有这个构造函数,没有默认构造函数 +# 只需要定义一个与类型同名的函数,并调用已有的构造函数得到正确的类型 +Lion(roar::AbstractString) = Lion("green", roar) # => Lion +# 这是一个外部构造函数,因为它在类型定义之外 + +struct Panther <: Cat # Panther 也是 Cat 的子类型 + eye_color + Panther() = new("green") + # Panthers 只有这个构造函数,没有默认构造函数 end -# 使用内置构造函数,如 Panther,可以让你控制 -# 如何构造类型的值 -# 应该尽可能使用外部构造函数而不是内部构造函数 +# 像 Panther 一样使用内置构造函数,让你可以控制如何构建类型的值 +# 应该尽量使用外部构造函数,而不是内部构造函数 #################################################### ## 6. 多分派 #################################################### -# 在Julia中, 所有的具名函数都是类属函数 -# 这意味着他们都是有很大小方法组成的 -# 每个 Lion 的构造函数都是类属函数 Lion 的方法 +# Julia 中所有的函数都是通用函数,或者叫做泛型函数(generic functions) +# 也就是说这些函数都是由许多小方法组合而成的 +# Lion 的每一种构造函数都是通用函数 Lion 的一个方法 # 我们来看一个非构造函数的例子 +# 首先,让我们定义一个函数 meow -# Lion, Panther, Tiger 的 meow 定义为 +# Lion, Panther, Tiger 的 meow 定义分别为 function meow(animal::Lion) - animal.roar # 使用点符号访问属性 + animal.roar # 使用点记号 '.' 访问属性 end function meow(animal::Panther) - "grrr" + "grrr" end function meow(animal::Tiger) - "rawwwr" + "rawwwr" end # 试试 meow 函数 -meow(tigger) # => "rawwr" -meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(tigger) # => "rawwwr" +meow(Lion("brown", "ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" -# 再看看层次结构 -issubtype(Tiger,Cat) # => false -issubtype(Lion,Cat) # => true -issubtype(Panther,Cat) # => true +# 回顾类型的层次结构 +Tiger <: Cat # => false +Lion <: Cat # => true +Panther <: Cat # => true -# 定义一个接收 Cats 的函数 +# 定义一个接收 Cat 类型的函数 function pet_cat(cat::Cat) - println("The cat says $(meow(cat))") + println("The cat says $(meow(cat))") end +# => pet_cat (generic function with 1 method) -pet_cat(Lion("42")) # => prints "The cat says 42" +pet_cat(Lion("42")) # => The cat says 42 try - pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) + pet_cat(tigger) # => ERROR: MethodError: no method matching pet_cat(::Tiger) catch e println(e) end # 在面向对象语言中,通常都是单分派 -# 这意味着分派方法是通过第一个参数的类型决定的 -# 在Julia中, 所有参数类型都会被考虑到 +# 这意味着使用的方法取决于第一个参数的类型 +# 而 Julia 中选择方法时会考虑到所有参数的类型 -# 让我们定义有多个参数的函数,好看看区别 -function fight(t::Tiger,c::Cat) - println("The $(t.coatcolor) tiger wins!") +# 让我们定义一个有更多参数的函数,这样我们就能看出区别 +function fight(t::Tiger, c::Cat) + println("The $(t.coatcolor) tiger wins!") end # => fight (generic function with 1 method) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => fight(tigger, Lion("ROAR")) -# 让我们修改一下传入具体为 Lion 类型时的行为 -fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# 让我们修改一下传入 Lion 类型时的行为 +fight(t::Tiger, l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) -fight(tigger,Panther()) # => prints The orange tiger wins! -fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => The green-maned lion wins! -# 把 Tiger 去掉 -fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# 我们不需要一只老虎参与战斗 +fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) -fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr try - fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) -catch + fight(Panther(), Lion("RAWR")) + # => ERROR: MethodError: no method matching fight(::Panther, ::Lion) + # => Closest candidates are: + # => fight(::Tiger, ::Lion) at ... + # => fight(::Tiger, ::Cat) at ... + # => fight(::Lion, ::Cat) at ... + # => ... +catch e + println(e) end -# 在试试让 Cat 在前面 -fight(c::Cat,l::Lion) = println("The cat beats the Lion") -# => Warning: New definition -# fight(Cat,Lion) at none:1 -# is ambiguous with -# fight(Lion,Cat) at none:2. -# Make sure -# fight(Lion,Lion) -# is defined first. -#fight (generic function with 4 methods) +# 试试把 Cat 放在前面 +fight(c::Cat, l::Lion) = println("The cat beats the Lion") +# => fight (generic function with 4 methods) -# 警告说明了无法判断使用哪个 fight 方法 -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr -# 结果在老版本 Julia 中可能会不一样 +# 由于无法判断该使用哪个 fight 方法,而产生了错误 +try + fight(Lion("RAR"), Lion("brown", "rarrr")) + # => ERROR: MethodError: fight(::Lion, ::Lion) is ambiguous. Candidates: + # => fight(c::Cat, l::Lion) in Main at ... + # => fight(l::Lion, c::Cat) in Main at ... + # => Possible fix, define + # => fight(::Lion, ::Lion) + # => ... +catch e + println(e) +end +# 在不同版本的 Julia 中错误信息可能有所不同 -fight(l::Lion,l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie +fight(l::Lion, l2::Lion) = println("The lions come to a tie") +# => fight (generic function with 5 methods) +fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie # Under the hood -# 你还可以看看 llvm 以及生成的汇编代码 - -square_area(l) = l * l # square_area (generic function with 1 method) +# 你还可以看看 llvm 以及它生成的汇编代码 -square_area(5) #25 +square_area(l) = l * l # => square_area (generic function with 1 method) +square_area(5) # => 25 -# 给 square_area 一个整形时发生什么 +# 当我们喂给 square_area 一个整数时会发生什么? code_native(square_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX + # .text + # ; Function square_area { + # ; Location: REPL[49]:1 + # pushq %rbp + # movq %rsp, %rbp + # ; Function *; { + # ; Location: int.jl:54 + # imull %ecx, %ecx + # ;} + # movl %ecx, %eax + # popq %rbp + # retq + # nopl (%rax,%rax) + # ;} code_native(square_area, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret + # .text + # ; Function square_area { + # ; Location: REPL[49]:1 + # pushq %rbp + # movq %rsp, %rbp + # ; Function *; { + # ; Location: float.jl:398 + # vmulss %xmm0, %xmm0, %xmm0 + # ;} + # popq %rbp + # retq + # nopw (%rax,%rax) + # ;} code_native(square_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # -# 注意 只要参数中又浮点类型,Julia 就使用浮点指令 + # .text + # ; Function square_area { + # ; Location: REPL[49]:1 + # pushq %rbp + # movq %rsp, %rbp + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd %xmm0, %xmm0, %xmm0 + # ;} + # popq %rbp + # retq + # nopw (%rax,%rax) + # ;} + +# 注意!只要参数中有浮点数,Julia 就会使用浮点指令 # 让我们计算一下圆的面积 -circle_area(r) = pi * r * r # circle_area (generic function with 1 method) -circle_area(5) # 78.53981633974483 +circle_area(r) = pi * r * r # => circle_area (generic function with 1 method) +circle_area(5) # => 78.53981633974483 code_native(circle_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # + # .text + # ; Function circle_area { + # ; Location: REPL[53]:1 + # pushq %rbp + # movq %rsp, %rbp + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function promote; { + # ; Location: promotion.jl:284 + # ; Function _promote; { + # ; Location: promotion.jl:261 + # ; Function convert; { + # ; Location: number.jl:7 + # ; Function Type; { + # ; Location: float.jl:60 + # vcvtsi2sdl %ecx, %xmm0, %xmm0 + # movabsq $532051920, %rax # imm = 0x1FB677D0 + # ;}}}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd (%rax), %xmm0, %xmm1 + # vmulsd %xmm0, %xmm1, %xmm0 + # ;}} + # popq %rbp + # retq + # nopl (%rax) + # ;} code_native(circle_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # + # .text + # ; Function circle_area { + # ; Location: REPL[53]:1 + # pushq %rbp + # movq %rsp, %rbp + # movabsq $532052040, %rax # imm = 0x1FB67848 + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd (%rax), %xmm0, %xmm1 + # ;}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd %xmm0, %xmm1, %xmm0 + # ;} + # popq %rbp + # retq + # nopl (%rax,%rax) + # ;} ``` -- cgit v1.2.3 From 5691fb7a8d824a879a8d4391a93c50f27be1ec25 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 09:43:02 +0800 Subject: Update output for Julia 1.0 --- julia.html.markdown | 317 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 194 insertions(+), 123 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index dfa3103c..416f1a5a 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -89,7 +89,9 @@ false # Strings are UTF8 encoded. Only if they contain only ASCII characters can # they be safely indexed. -ascii("This is a string")[1] # => 'T' # Julia indexes from 1 +ascii("This is a string")[1] +# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase) +# Julia indexes from 1 # Otherwise, iterating over strings is recommended (map, for loops, etc). # $ can be used for string interpolation: @@ -101,7 +103,7 @@ using Printf @printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000 # Printing is easy -println("I'm Julia. Nice to meet you!") +println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you! # String can be compared lexicographically "good" > "bye" # => true @@ -147,19 +149,18 @@ SomeOtherVar123! = 6 # => 6 # functions are sometimes called mutating functions or in-place functions. # Arrays store a sequence of values indexed by integers 1 through n: -a = Int64[] # => 0-element Int64 Array +a = Int64[] # => 0-element Array{Int64,1} # 1-dimensional array literals can be written with comma-separated values. -b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] -b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] -b[1] # => 4 +b = [4, 5, 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b = [4; 5; 6] # => 3-element Array{Int64,1}: [4, 5, 6] b[end] # => 6 # 2-dimensional arrays use space-separated values and semicolon-separated rows. -matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +matrix = [1 2; 3 4] # => 2×2 Array{Int64,2}: [1 2; 3 4] # Arrays of a particular type -b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6] +b = Int8[4, 5, 6] # => 3-element Array{Int8,1}: [4, 5, 6] # Add stuff to the end of a list with push! and append! push!(a, 1) # => [1] @@ -186,16 +187,28 @@ pushfirst!(a, 7) # => [7,2,4,3,4,5,6] # Function names that end in exclamations points indicate that they modify # their argument. -arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr is still [5,4,6] sort!(arr) # => [4,5,6]; arr is now [4,5,6] +arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6] # Looking out of bounds is a BoundsError try - a[0] - # => BoundsError: attempt to access 7-element Array{Int64,1} at index [0] - a[end + 1] - # => BoundsError: attempt to access 7-element Array{Int64,1} at index [8] + a[0] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [0] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:180 + a[end + 1] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + # index [8] + # => Stacktrace: + # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 + # => [2] top-level scope at none:0 + # => [3] ... + # => in expression starting at ...\LearnJulia.jl:188 catch e println(e) end @@ -205,7 +218,8 @@ end # find these files. # You can initialize arrays from ranges -a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5] +a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5] +a2 = [1:5] # => 1-element Array{UnitRange{Int64},1}: [1:5] # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] @@ -229,7 +243,9 @@ length(a) # => 8 tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] # => 1 try - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 + # => ERROR: MethodError: no method matching + # setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64) catch e println(e) end @@ -254,11 +270,12 @@ e, d = d, e # => (5,4) # d is now 5 and e is now 4 # Dictionaries store mappings -empty_dict = Dict() # => Dict{Any,Any}() +empty_dict = Dict() # => Dict{Any,Any} with 0 entries # You can create a dictionary using a literal filled_dict = Dict("one" => 1, "two" => 2, "three" => 3) -# => Dict{String,Int64} +# => Dict{String,Int64} with 3 entries: +# => "two" => 2, "one" => 1, "three" => 3 # Look up values with [] filled_dict["one"] # => 1 @@ -266,12 +283,13 @@ filled_dict["one"] # => 1 # Get all keys keys(filled_dict) # => Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: -# "two", "one", "three" +# => "two", "one", "three" # Note - dictionary keys are not sorted or in the order you inserted them. # Get all values values(filled_dict) -# => Base.ValueIterator{Dict{String,Int64}} with 3 entries. Values: 2, 1, 3 +# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: +# => 2, 1, 3 # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with in, haskey @@ -282,7 +300,7 @@ haskey(filled_dict, 1) # => false # Trying to look up a non-existent key will raise an error try - filled_dict["four"] # => KeyError: key "four" not found + filled_dict["four"] # => ERROR: KeyError: key "four" not found catch e println(e) end @@ -293,7 +311,7 @@ get(filled_dict, "one", 4) # => 1 get(filled_dict, "four", 4) # => 4 # Use Sets to represent collections of unordered, unique values -empty_set = Set() # => Set{Any}() +empty_set = Set() # => Set(Any[]) # Initialize a set with values filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) @@ -353,18 +371,16 @@ for pair in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") from, to = pair println("$from is a $to") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal for (k, v) in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") println("$k is a $v") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => mouse is a mammal +# => cat is a mammal +# => dog is a mammal # While loops loop while a condition is true let x = 0 @@ -406,11 +422,11 @@ end add(5, 6) # => 11 after printing out "x is 5 and y is 6" # Compact assignment of functions -f_add(x, y) = x + y # => "f (generic function with 1 method)" +f_add(x, y) = x + y # => f_add (generic function with 1 method) f_add(3, 4) # => 7 # Function can also return multiple values as tuple -fn(x, y) = x + y, x - y +fn(x, y) = x + y, x - y # => fn (generic function with 1 method) fn(3, 4) # => (7, -1) # You can define functions that take a variable number of @@ -437,13 +453,14 @@ add(x...) # this is equivalent to add(5,6) function defaults(a, b, x=5, y=6) return "$a $b and $x $y" end +# => defaults (generic function with 3 methods) defaults('h', 'g') # => "h g and 5 6" defaults('h', 'g', 'j') # => "h g and j 6" defaults('h', 'g', 'j', 'k') # => "h g and j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # => ERROR: MethodError: no method matching defaults(::Char) + defaults() # => ERROR: MethodError: no method matching defaults() catch e println(e) end @@ -452,10 +469,11 @@ end function keyword_args(;k1=4, name2="hello") # note the ; return Dict("k1" => k1, "name2" => name2) end +# => keyword_args (generic function with 1 method) -keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] -keyword_args() # => ["name2"=>"hello","k1"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness", "k1"=>4] +keyword_args(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] +keyword_args() # => ["name2"=>"hello", "k1"=>4] # You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") @@ -463,6 +481,7 @@ function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("optional arg: $optional_positional_arg") println("keyword arg: $keyword_arg") end +# => all_the_args (generic function with 2 methods) all_the_args(1, 3, keyword_arg=4) # prints: @@ -477,6 +496,7 @@ function create_adder(x) end return adder end +# => create_adder (generic function with 1 method) # This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true @@ -485,6 +505,7 @@ end function create_adder(x) y -> x + y end +# => create_adder (generic function with 1 method) # You can also name the internal function, if you want function create_adder(x) @@ -493,9 +514,11 @@ function create_adder(x) end adder end +# => create_adder (generic function with 1 method) -add_10 = create_adder(10) -add_10(3) # => 13 +add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) + # (generic function with 1 method) +add_10(3) # => 13 # There are built-in higher order functions @@ -555,16 +578,16 @@ abstract type Cat end # just a name and point in the type hierarchy using InteractiveUtils # defines the subtype and supertype function # For example, Number is an abstract type subtypes(Number) # => 2-element Array{Any,1}: - # Complex{T<:Real} - # Real + # => Complex + # => Real subtypes(Cat) # => 0-element Array{Any,1} # AbstractString, as the name implies, is also an abstract type -subtypes(AbstractString) # 4-element Array{Any,1}: - # String - # SubString - # SubstitutionString - # Test.GenericString +subtypes(AbstractString) # => 4-element Array{Any,1}: + # => String + # => SubString + # => SubstitutionString + # => Test.GenericString # Every type has a super type; use the `supertype` function to get it. typeof(5) # => Int64 @@ -626,7 +649,7 @@ function meow(animal::Tiger) end # Testing the meow function -meow(tigger) # => "rawwr" +meow(tigger) # => "rawwwr" meow(Lion("brown", "ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" @@ -639,10 +662,11 @@ Panther <: Cat # => true function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end +# => pet_cat (generic function with 1 method) -pet_cat(Lion("42")) # => prints "The cat says 42" +pet_cat(Lion("42")) # => The cat says 42 try - pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) + pet_cat(tigger) # => ERROR: MethodError: no method matching pet_cat(::Tiger) catch e println(e) end @@ -657,45 +681,54 @@ function fight(t::Tiger, c::Cat) end # => fight (generic function with 1 method) -fight(tigger, Panther()) # => prints The orange tiger wins! -fight(tigger, Lion("ROAR")) # => prints The orange tiger wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => The orange tiger wins! # Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger, l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) -fight(tigger, Panther()) # => prints The orange tiger wins! -fight(tigger, Lion("ROAR")) # => prints The green-maned lion wins! +fight(tigger, Panther()) # => The orange tiger wins! +fight(tigger, Lion("ROAR")) # => The green-maned lion wins! # We don't need a Tiger in order to fight fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) -fight(Lion("balooga!"), Panther()) # => prints The victorious cat says grrr +fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr try - fight(Panther(), Lion("RAWR")) + fight(Panther(), Lion("RAWR")) + # => ERROR: MethodError: no method matching fight(::Panther, ::Lion) + # => Closest candidates are: + # => fight(::Tiger, ::Lion) at ... + # => fight(::Tiger, ::Cat) at ... + # => fight(::Lion, ::Cat) at ... + # => ... catch e println(e) - # => MethodError(fight, (Panther("green"), Lion("green", "RAWR")), - # 0x000000000000557b) end # Also let the cat go first fight(c::Cat, l::Lion) = println("The cat beats the Lion") +# => fight (generic function with 4 methods) # This warning is because it's unclear which fight will be called in: try fight(Lion("RAR"), Lion("brown", "rarrr")) - # => prints The victorious cat says rarrr + # => ERROR: MethodError: fight(::Lion, ::Lion) is ambiguous. Candidates: + # => fight(c::Cat, l::Lion) in Main at ... + # => fight(l::Lion, c::Cat) in Main at ... + # => Possible fix, define + # => fight(::Lion, ::Lion) + # => ... catch e println(e) - # => MethodError(fight, (Lion("green", "RAR"), Lion("brown", "rarrr")), - # 0x000000000000557c) end # The result may be different in other versions of Julia -fight(l::Lion, l2::Lion) = println("The lions come to a tie") -fight(Lion("RAR"), Lion("brown", "rarrr")) # => prints The lions come to a tie +fight(l::Lion, l2::Lion) = println("The lions come to a tie") +# => fight (generic function with 5 methods) +fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie # Under the hood @@ -706,74 +739,112 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) # => 25 # What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX - -code_native(square_area, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret - -code_native(square_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # +code_native(square_area, (Int32,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 # Prologue + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: int.jl:54 + # imul ecx, ecx # Square l and store the result in ECX + # ;} + # mov eax, ecx + # pop rbp # Restore old base pointer + # ret # Result will still be in EAX + # nop dword ptr [rax + rax] + # ;} + +code_native(square_area, (Float32,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: float.jl:398 + # vmulss xmm0, xmm0, xmm0 # Scalar single precision multiply (AVX) + # ;} + # pop rbp + # ret + # nop word ptr [rax + rax] + # ;} + +code_native(square_area, (Float64,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm0, xmm0, xmm0 # Scalar double precision multiply (AVX) + # ;} + # pop rbp + # ret + # nop word ptr [rax + rax] + # ;} + # Note that julia will use floating point instructions if any of the # arguments are floats. # Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 -code_native(circle_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # - -code_native(circle_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # +code_native(circle_area, (Int32,), syntax = :intel) + # .text + # ; Function circle_area { + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function promote; { + # ; Location: promotion.jl:284 + # ; Function _promote; { + # ; Location: promotion.jl:261 + # ; Function convert; { + # ; Location: number.jl:7 + # ; Function Type; { + # ; Location: float.jl:60 + # vcvtsi2sd xmm0, xmm0, ecx # Load integer (r) from memory + # movabs rax, 497710928 # Load pi + # ;}}}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm1, xmm0, qword ptr [rax] # pi * r + # vmulsd xmm0, xmm1, xmm0 # (pi * r) * r + # ;}} + # pop rbp + # ret + # nop dword ptr [rax] + # ;} + +code_native(circle_area, (Float64,), syntax = :intel) + # .text + # ; Function circle_area { + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp + # movabs rax, 497711048 + # ; Function *; { + # ; Location: operators.jl:502 + # ; Function *; { + # ; Location: promotion.jl:314 + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm1, xmm0, qword ptr [rax] + # ;}}} + # ; Function *; { + # ; Location: float.jl:399 + # vmulsd xmm0, xmm1, xmm0 + # ;} + # pop rbp + # ret + # nop dword ptr [rax + rax] + # ;} ``` ## Further Reading -- cgit v1.2.3 From 4fcac31e9cfe169f006244dbdb01d0d16fa696e5 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 09:45:50 +0800 Subject: ry to use as few words as possible --- julia.html.markdown | 48 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 416f1a5a..54860fca 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -170,10 +170,12 @@ push!(a, 3) # => [1,2,4,3] append!(a, b) # => [1,2,4,3,4,5,6] # Remove from the end with pop -pop!(b) # => 6 and b is now [4,5] +pop!(b) # => 6 +b # => [4,5] # Let's put it back -push!(b, 6) # b is now [4,5,6] again. +push!(b, 6) # => [4,5,6] +b # => [4,5,6] a[1] # => 1 # remember that Julia indexes from 1, not 0! @@ -182,14 +184,18 @@ a[1] # => 1 # remember that Julia indexes from 1, not 0! a[end] # => 6 # we also have popfirst! and pushfirst! -popfirst!(a) # => 1 and a is now [2,4,3,4,5,6] +popfirst!(a) # => 1 +a # => [2,4,3,4,5,6] pushfirst!(a, 7) # => [7,2,4,3,4,5,6] +a # => [7,2,4,3,4,5,6] # Function names that end in exclamations points indicate that they modify # their argument. -sort(arr) # => [4,5,6]; arr is still [5,4,6] -sort!(arr) # => [4,5,6]; arr is now [4,5,6] arr = [5,4,6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] +arr # => [5,4,6] +sort!(arr) # => [4,5,6] +arr # => [4,5,6] # Looking out of bounds is a BoundsError try @@ -227,11 +233,13 @@ a[2:end] # => [2, 3, 4, 5] # Remove elements from an array by index with splice! arr = [3,4,5] -splice!(arr, 2) # => 4 ; arr is now [3,5] +splice!(arr, 2) # => 4 +arr # => [3,5] # Concatenate lists with append! b = [1,2,3] -append!(a, b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] +append!(a, b) # => [1, 2, 3, 4, 5, 1, 2, 3] +a # => [1, 2, 3, 4, 5, 1, 2, 3] # Check for existence in a list with in in(1, a) # => true @@ -240,8 +248,9 @@ in(1, a) # => true length(a) # => 8 # Tuples are immutable. -tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. -tup[1] # => 1 +tup = (1, 2, 3) # => (1,2,3) +typeof(tup) # => Tuple{Int64,Int64,Int64} +tup[1] # => 1 try tup[1] = 3 # => ERROR: MethodError: no method matching @@ -251,23 +260,30 @@ catch e end # Many array functions also work on tuples -length(tup) # => 3 -tup[1:2] # => (1,2) +length(tup) # => 3 +tup[1:2] # => (1,2) in(2, tup) # => true # You can unpack tuples into variables -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # => (1,2,3) +a # => 1 +b # => 2 +c # => 3 # Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 # => (4,5,6) +d # => 4 +e # => 5 +f # => 6 # A 1-element tuple is distinct from the value it contains (1,) == 1 # => false (1) == 1 # => true # Look how easy it is to swap two values -e, d = d, e # => (5,4) # d is now 5 and e is now 4 - +e, d = d, e # => (5,4) +d # => 5 +e # => 4 # Dictionaries store mappings empty_dict = Dict() # => Dict{Any,Any} with 0 entries @@ -419,7 +435,9 @@ function add(x, y) x + y end -add(5, 6) # => 11 after printing out "x is 5 and y is 6" +add(5, 6) +# => x is 5 and y is 6 +# => 11 # Compact assignment of functions f_add(x, y) = x + y # => f_add (generic function with 1 method) -- cgit v1.2.3 From 749e81ace2cf75710926cc0e9e35a8a675545648 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 09:46:52 +0800 Subject: Uniform output format --- julia.html.markdown | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 54860fca..fa614992 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -369,19 +369,17 @@ for animal = ["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal # You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end -# prints: -# dog is a mammal -# cat is a mammal -# mouse is a mammal +# => dog is a mammal +# => cat is a mammal +# => mouse is a mammal for pair in Dict("dog" => "mammal", "cat" => "mammal", "mouse" => "mammal") from, to = pair @@ -405,11 +403,10 @@ let x = 0 x += 1 # Shorthand for x = x + 1 end end -# prints: -# 0 -# 1 -# 2 -# 3 +# => 0 +# => 1 +# => 2 +# => 3 # Handle exceptions with a try/catch block try @@ -502,10 +499,9 @@ end # => all_the_args (generic function with 2 methods) all_the_args(1, 3, keyword_arg=4) -# prints: -# normal arg: 1 -# optional arg: 3 -# keyword arg: 4 +# => normal arg: 1 +# => optional arg: 3 +# => keyword arg: 4 # Julia has first class functions function create_adder(x) -- cgit v1.2.3 From e96bfe490e2df68075e277cb18bdf58f90af2c0a Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 09:47:30 +0800 Subject: Adjust for alignment --- julia.html.markdown | 51 +++++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index fa614992..eadf6415 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -154,6 +154,7 @@ a = Int64[] # => 0-element Array{Int64,1} # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] # => 3-element Array{Int64,1}: [4, 5, 6] b = [4; 5; 6] # => 3-element Array{Int64,1}: [4, 5, 6] +b[1] # => 4 b[end] # => 6 # 2-dimensional arrays use space-separated values and semicolon-separated rows. @@ -277,7 +278,7 @@ e # => 5 f # => 6 # A 1-element tuple is distinct from the value it contains -(1,) == 1 # => false +(1,) == 1 # => false (1) == 1 # => true # Look how easy it is to swap two values @@ -335,15 +336,14 @@ filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) push!(filled_set, 5) # => Set([4, 2, 3, 5, 1]) # Check if the values are in the set -in(2, filled_set) # => true +in(2, filled_set) # => true in(10, filled_set) # => false # There are functions for set intersection, union, and difference. -other_set = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) -intersect(filled_set, other_set) # => Set([4, 3, 5]) -union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1]) -setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) - +other_set = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) +intersect(filled_set, other_set) # => Set([4, 3, 5]) +union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1]) +setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) #################################################### ## 3. Control Flow @@ -416,15 +416,14 @@ catch e end # => caught it ErrorException("help") - #################################################### ## 4. Functions #################################################### # The keyword 'function' creates new functions -#function name(arglist) -# body... -#end +# function name(arglist) +# body... +# end function add(x, y) println("x is $x and y is $y") @@ -540,8 +539,8 @@ map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions -[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### @@ -554,7 +553,7 @@ filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] typeof(5) # => Int64 # Types are first-class values -typeof(Int64) # => DataType +typeof(Int64) # => DataType typeof(DataType) # => DataType # DataType is the type that represents types, including itself. @@ -604,17 +603,17 @@ subtypes(AbstractString) # => 4-element Array{Any,1}: # => Test.GenericString # Every type has a super type; use the `supertype` function to get it. -typeof(5) # => Int64 -supertype(Int64) # => Signed -supertype(Signed) # => Integer +typeof(5) # => Int64 +supertype(Int64) # => Signed +supertype(Signed) # => Integer supertype(Integer) # => Real -supertype(Real) # => Number -supertype(Number) # => Any +supertype(Real) # => Number +supertype(Number) # => Any supertype(supertype(Signed)) # => Real -supertype(Any) # => Any +supertype(Any) # => Any # All of these type, except for Int64, are abstract. -typeof("fire") # => String -supertype(String) # => AbstractString +typeof("fire") # => String +supertype(String) # => AbstractString # Likewise here with String supertype(SubString) # => AbstractString @@ -665,12 +664,12 @@ end # Testing the meow function meow(tigger) # => "rawwwr" meow(Lion("brown", "ROAAR")) # => "ROAAR" -meow(Panther()) # => "grrr" +meow(Panther()) # => "grrr" # Review the local type hierarchy -Tiger <: Cat # => false -Lion <: Cat # => true -Panther <: Cat # => true +Tiger <: Cat # => false +Lion <: Cat # => true +Panther <: Cat # => true # Defining a function that takes Cats function pet_cat(cat::Cat) -- cgit v1.2.3 From b0bbe39b46a1825563c903c0e9c25eed3c63293b Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 09:50:30 +0800 Subject: remove useless Blank Lines --- julia.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index eadf6415..3ef3148a 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -14,7 +14,6 @@ and low-level control, Julia is as easy to learn and use as Python. This is based on Julia 1.0.0 ```julia - # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' @@ -362,7 +361,6 @@ else # The else clause is optional too. end # => prints "some var is smaller than 10" - # For loops iterate over iterables. # Iterable types include Range, Array, Set, Dict, and AbstractString. for animal = ["dog", "cat", "mouse"] -- cgit v1.2.3 From 6353b66f8a9448f62889c21eab45a44fd02529a3 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 10:10:45 +0800 Subject: update Statements outside of code --- zh-cn/julia-cn.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 35c2e2d4..4e97d147 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -11,6 +11,11 @@ translators: lang: zh-cn --- +Julia 是一种新的同像函数式编程语言(homoiconic functional language),它专注于科学计算领域。 +虽然拥有同像宏(homoiconic macros)、一级函数(first-class functions)和底层控制等全部功能,但 Julia 依旧和 Python 一样易于学习和使用。 + +示例代码基于 Julia 1.0.0 + ```julia # 单行注释只需要一个井号 #= 多行注释 @@ -841,3 +846,10 @@ code_native(circle_area, (Float64,)) # nopl (%rax,%rax) # ;} ``` + +## 拓展阅读材料 + +你可以在 [Julia 中文文档](http://docs.juliacn.com/latest/) / [Julia 文档(en)](https://docs.julialang.org/) +中获得关于 Julia 的更多细节。 + +如果有任何问题可以去 [Julia 中文社区](http://discourse.juliacn.com/) / [官方社区(en)](https://discourse.julialang.org/) 提问,大家对待新手都非常的友好。 -- cgit v1.2.3 From 099462b49e37edb327edb3afe01250e02c477e11 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 30 Aug 2018 19:10:56 -0700 Subject: Reinstate test --- tests/encoding.rb | 32 ++++++++++++++++++++++++++++++++ tests/yaml.rb | 21 +++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 tests/encoding.rb create mode 100644 tests/yaml.rb diff --git a/tests/encoding.rb b/tests/encoding.rb new file mode 100644 index 00000000..a0b3b184 --- /dev/null +++ b/tests/encoding.rb @@ -0,0 +1,32 @@ +#!/usr/bin/env ruby +require 'charlock_holmes' +$file_count = 0; +markdown_files = Dir["./**/*.html.markdown"] +markdown_files.each do |file| + begin + contents = File.read(file) + detection = CharlockHolmes::EncodingDetector.detect(contents) + case detection[:encoding] + when 'UTF-8' + $file_count = $file_count + 1 + when 'ISO-8859-1' + $file_count = $file_count + 1 + when /ISO-8859/ + puts "Notice: #{file} was detected as #{detection[:encoding]} encoding. Everything is probably fine." + $file_count = $file_count + 1 + else + puts "WARNING #{file} was detected as #{detection[:encoding]} encoding. Please save the file in UTF-8!" + end + rescue Exception => msg + puts msg + end +end +files_failed = markdown_files.length - $file_count +if files_failed != 0 + puts "FAILURE!!! #{files_failed} files were unable to be validated as UTF-8!" + puts "Please resave the file as UTF-8." + exit 1 +else + puts "Success. All #{$file_count} files passed UTF-8 validity checks." + exit 0 +end diff --git a/tests/yaml.rb b/tests/yaml.rb new file mode 100644 index 00000000..0ed918e0 --- /dev/null +++ b/tests/yaml.rb @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby +require 'yaml'; +$file_count = 0; +markdown_files = Dir["./**/*.html.markdown"] +markdown_files.each do |file| + begin + YAML.load_file(file) + $file_count = $file_count + 1 + rescue Exception => msg + puts msg + end +end +files_failed = markdown_files.length - $file_count +if files_failed != 0 + puts "FAILURE!!! #{files_failed} files were unable to be parsed!" + puts "Please check the YAML headers for the documents that failed!" + exit 1 +else + puts "All #{$file_count} files were verified valid YAML" + exit 0 +end -- cgit v1.2.3 From 639c56cc7522f344c18300d646d8420d67b0f045 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 10:47:16 +0800 Subject: Polish translation --- zh-cn/julia-cn.html.markdown | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 4e97d147..f54a4d4c 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -90,11 +90,13 @@ false # 字符字面量可用 ' 创建 'a' +# 字符串使用 UTF-8 编码 # 可以像取数组取值一样用 index 取出对应字符 -ascii("This is a string")[1] # => 'T' +ascii("This is a string")[1] +# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase) # Julia 的 index 从 1 开始 :( -# 但是对 UTF-8 无效, -# 因此建议使用遍历器 (map, for loops, 等). +# 但只有在字符串仅由 ASCII 字符构成时,字符串才能够被安全的引索 +# 因此建议使用遍历器 (map, for loops, 等) # $ 可用于字符插值: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" @@ -105,7 +107,7 @@ using Printf @printf "%d is less than %f\n" 4.5 5.3 # => 5 is less than 5.300000 # 打印字符串很容易 -println("I'm Julia. Nice to meet you!") +println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you! # 字符串可以按字典序进行比较 "good" > "bye" # => true @@ -138,9 +140,10 @@ SomeOtherVar123! = 6 # => 6 # 注意 Julia 的命名规约: # -# * 变量名为小写,单词之间以下划线连接 "_" 。 +# * 名称可以用下划线「_」分割。 +# 不过一般不推荐使用下划线,除非不用变量名就会变得难于理解 # -# * 类型名以大写字母开头,单词以 CamelCase 方式连接。 +# * 类型名以大写字母开头,单词以 CamelCase 方式连接,无下划线。 # # * 函数与宏的名字小写,无下划线。 # @@ -179,7 +182,7 @@ b # => [4,5,6] a[1] # => 1 # 永远记住 Julia 的引索从 1 开始!而不是 0! -# 用 end 可以直接取到最后索引. 可用作任何索引表达式 +# 用 end 可以直接取到最后索引。它可以用在任何索引表达式中 a[end] # => 6 # 数组还支持 popfirst! 和 pushfirst! @@ -204,7 +207,7 @@ try # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 # => [2] top-level scope at none:0 # => [3] ... - # => in expression starting at ...\LearnJulia.jl:188 + # => in expression starting at ...\LearnJulia.jl:203 a[end + 1] # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at # index [8] @@ -212,7 +215,7 @@ try # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 # => [2] top-level scope at none:0 # => [3] ... - # => in expression starting at ...\LearnJulia.jl:196 + # => in expression starting at ...\LearnJulia.jl:211 catch e println(e) end @@ -222,6 +225,8 @@ end # 可以用 range 初始化数组 a = [1:5;] # => 5-element Array{Int64,1}: [1,2,3,4,5] +# 注意!分号不可省略 +a2 = [1:5] # => 1-element Array{UnitRange{Int64},1}: [1:5] # 可以切割数组 a[1:3] # => [1, 2, 3] @@ -282,7 +287,7 @@ d # => 5 e # => 4 -# 字典Dictionaries store mappings +# 字典用于储存映射(mappings)(键值对) empty_dict = Dict() # => Dict{Any,Any} with 0 entries # 也可以用字面量创建字典 @@ -323,7 +328,7 @@ end get(filled_dict, "one", 4) # => 1 get(filled_dict, "four", 4) # => 4 -# Sets 表示无序不可重复的值的集合 +# Set 表示无序不可重复的值的集合 empty_set = Set() # => Set(Any[]) # 初始化一个带初值的 Set filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) @@ -417,7 +422,7 @@ end ## 4. 函数 #################################################### -# 关键字 'function' 用于定义函数 +# 关键字 function 用于定义函数 # function name(arglist) # body... # end @@ -553,7 +558,7 @@ typeof(DataType) # => DataType # Julia 并不只是静态的检查类型 # 用户还可以自定义类型 -# 就跟其它语言的 records 或 structs 一样 +# 就跟其它语言的 record 或 struct 一样 # 用 `struct` 关键字定义新的类型 # struct Name @@ -641,14 +646,17 @@ end function meow(animal::Lion) animal.roar # 使用点记号 '.' 访问属性 end +# => meow (generic function with 1 method) function meow(animal::Panther) "grrr" end +# => meow (generic function with 2 methods) function meow(animal::Tiger) "rawwwr" end +# => meow (generic function with 3 methods) # 试试 meow 函数 meow(tigger) # => "rawwwr" @@ -656,8 +664,8 @@ meow(Lion("brown", "ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" # 回顾类型的层次结构 -Tiger <: Cat # => false -Lion <: Cat # => true +Tiger <: Cat # => false +Lion <: Cat # => true Panther <: Cat # => true # 定义一个接收 Cat 类型的函数 @@ -733,7 +741,7 @@ fight(l::Lion, l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie -# Under the hood +# 深入编译器之后 # 你还可以看看 llvm 以及它生成的汇编代码 square_area(l) = l * l # => square_area (generic function with 1 method) -- cgit v1.2.3 From 5c3a6d1f5a6fbbe113c00791d7bea7b023a32a1a Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 10:47:50 +0800 Subject: Using Intel asm syntax --- zh-cn/julia-cn.html.markdown | 107 ++++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 53 deletions(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index f54a4d4c..99b27464 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -748,50 +748,51 @@ square_area(l) = l * l # => square_area (generic function with 1 method) square_area(5) # => 25 # 当我们喂给 square_area 一个整数时会发生什么? -code_native(square_area, (Int32,)) +code_native(square_area, (Int32,), syntax = :intel) + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 # 函数序言 (Prologue) + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: int.jl:54 + # imul ecx, ecx # 求 l 的平方,并把结果放在 ECX 中 + # ;} + # mov eax, ecx + # pop rbp # 还原旧的基址指针(base pointer) + # ret # 返回值放在 EAX 中 + # nop dword ptr [rax + rax] + # ;} +# 使用 syntax 参数指定输出语法。默认为 AT&T 格式,这里指定为 Intel 格式 + +code_native(square_area, (Float32,), syntax = :intel) # .text # ; Function square_area { - # ; Location: REPL[49]:1 - # pushq %rbp - # movq %rsp, %rbp - # ; Function *; { - # ; Location: int.jl:54 - # imull %ecx, %ecx - # ;} - # movl %ecx, %eax - # popq %rbp - # retq - # nopl (%rax,%rax) - # ;} - -code_native(square_area, (Float32,)) - # .text - # ; Function square_area { - # ; Location: REPL[49]:1 - # pushq %rbp - # movq %rsp, %rbp + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp # ; Function *; { # ; Location: float.jl:398 - # vmulss %xmm0, %xmm0, %xmm0 + # vmulss xmm0, xmm0, xmm0 # 标量双精度乘法 (AVX) # ;} - # popq %rbp - # retq - # nopw (%rax,%rax) + # pop rbp + # ret + # nop word ptr [rax + rax] # ;} -code_native(square_area, (Float64,)) +code_native(square_area, (Float64,), syntax = :intel) # .text # ; Function square_area { - # ; Location: REPL[49]:1 - # pushq %rbp - # movq %rsp, %rbp + # ; Location: REPL[116]:1 + # push rbp + # mov rbp, rsp # ; Function *; { # ; Location: float.jl:399 - # vmulsd %xmm0, %xmm0, %xmm0 + # vmulsd xmm0, xmm0, xmm0 # 标量双精度乘法 (AVX) # ;} - # popq %rbp - # retq - # nopw (%rax,%rax) + # pop rbp + # ret + # nop word ptr [rax + rax] # ;} # 注意!只要参数中有浮点数,Julia 就会使用浮点指令 @@ -799,12 +800,12 @@ code_native(square_area, (Float64,)) circle_area(r) = pi * r * r # => circle_area (generic function with 1 method) circle_area(5) # => 78.53981633974483 -code_native(circle_area, (Int32,)) +code_native(circle_area, (Int32,), syntax = :intel) # .text # ; Function circle_area { - # ; Location: REPL[53]:1 - # pushq %rbp - # movq %rsp, %rbp + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp # ; Function *; { # ; Location: operators.jl:502 # ; Function *; { @@ -817,41 +818,41 @@ code_native(circle_area, (Int32,)) # ; Location: number.jl:7 # ; Function Type; { # ; Location: float.jl:60 - # vcvtsi2sdl %ecx, %xmm0, %xmm0 - # movabsq $532051920, %rax # imm = 0x1FB677D0 + # vcvtsi2sd xmm0, xmm0, ecx # 从内存中读取整数 r + # movabs rax, 497710928 # 读取 pi # ;}}}}} # ; Function *; { # ; Location: float.jl:399 - # vmulsd (%rax), %xmm0, %xmm1 - # vmulsd %xmm0, %xmm1, %xmm0 + # vmulsd xmm1, xmm0, qword ptr [rax] # pi * r + # vmulsd xmm0, xmm1, xmm0 # (pi * r) * r # ;}} - # popq %rbp - # retq - # nopl (%rax) + # pop rbp + # ret + # nop dword ptr [rax] # ;} -code_native(circle_area, (Float64,)) +code_native(circle_area, (Float64,), syntax = :intel) # .text # ; Function circle_area { - # ; Location: REPL[53]:1 - # pushq %rbp - # movq %rsp, %rbp - # movabsq $532052040, %rax # imm = 0x1FB67848 + # ; Location: REPL[121]:1 + # push rbp + # mov rbp, rsp + # movabs rax, 497711048 # ; Function *; { # ; Location: operators.jl:502 # ; Function *; { # ; Location: promotion.jl:314 # ; Function *; { # ; Location: float.jl:399 - # vmulsd (%rax), %xmm0, %xmm1 + # vmulsd xmm1, xmm0, qword ptr [rax] # ;}}} # ; Function *; { # ; Location: float.jl:399 - # vmulsd %xmm0, %xmm1, %xmm0 + # vmulsd xmm0, xmm1, xmm0 # ;} - # popq %rbp - # retq - # nopl (%rax,%rax) + # pop rbp + # ret + # nop dword ptr [rax + rax] # ;} ``` -- cgit v1.2.3 From 7b773b916488bddccc884da5138a31e6f029e2af Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 10:48:19 +0800 Subject: Using Chinese square brackets --- zh-cn/julia-cn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index 99b27464..b350b6dc 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -17,9 +17,9 @@ Julia 是一种新的同像函数式编程语言(homoiconic functional language) 示例代码基于 Julia 1.0.0 ```julia -# 单行注释只需要一个井号 +# 单行注释只需要一个井号「#」 #= 多行注释 - 只需要以 '#=' 开始 '=#' 结束 + 只需要以「#=」开始「=#」结束 还可以嵌套. =# @@ -84,10 +84,10 @@ false 1 < 2 < 3 # => true 2 < 3 < 2 # => false -# 字符串可以由 " 创建 +# 字符串可以由「"」创建 "This is a string." -# 字符字面量可用 ' 创建 +# 字符字面量可用「'」创建 'a' # 字符串使用 UTF-8 编码 @@ -147,7 +147,7 @@ SomeOtherVar123! = 6 # => 6 # # * 函数与宏的名字小写,无下划线。 # -# * 会改变输入的函数名末位为 !。 +# * 会改变输入的函数名末位为「!」。 # 这类函数有时被称为 mutating functions 或 in-place functions. # 数组存储一列值,index 从 1 开始 @@ -374,7 +374,7 @@ end # => cat is a mammal # => mouse is a mammal -# 你也可以不用 '=' 而使用 'in' +# 你也可以不用「=」而使用「in」 for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end @@ -454,7 +454,7 @@ end varargs(1,2,3) # => (1,2,3) -# 省略号 ... 称为 splat +# 省略号「...」称为 splat # 刚刚用在了函数定义中 # 在调用函数时也可以使用它,此时它会把数组或元组解包为参数列表 add([5,6]...) # 等价于 add(5,6) @@ -644,7 +644,7 @@ end # Lion, Panther, Tiger 的 meow 定义分别为 function meow(animal::Lion) - animal.roar # 使用点记号 '.' 访问属性 + animal.roar # 使用点记号「.」访问属性 end # => meow (generic function with 1 method) -- cgit v1.2.3 From 2a7bf762c65a50a609cc65c275267203309f97be Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 11:24:57 +0800 Subject: Remove useless lib In fact, if you donot import InteractiveUtils, you still can use the subtype and supertype function --- julia.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 3ef3148a..15c09da4 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -586,7 +586,6 @@ sherekhan = typeof(tigger)(5.6, "fire") # => Tiger(5.6,"fire") abstract type Cat end # just a name and point in the type hierarchy # Abstract types cannot be instantiated, but can have subtypes. -using InteractiveUtils # defines the subtype and supertype function # For example, Number is an abstract type subtypes(Number) # => 2-element Array{Any,1}: # => Complex -- cgit v1.2.3 From 246922fc25b3b2c96e57e5ba5b10c54f0445eeef Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 11:45:47 +0800 Subject: Keep a line 80 chars --- zh-cn/matlab-cn.html.markdown | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index 851ca218..94d44a3e 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -10,9 +10,12 @@ lang: zh-cn --- -MATLAB 是 MATrix LABoratory (矩阵实验室)的缩写,它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 +MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。 +它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 -如果您有任何需要反馈或交流的内容,请联系本教程作者[@the_ozzinator](https://twitter.com/the_ozzinator)、[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 +如果您有任何需要反馈或交流的内容,请联系本教程作者: +[@the_ozzinator](https://twitter.com/the_ozzinator) +或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 ```matlab % 以百分号作为注释符 @@ -219,8 +222,9 @@ ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复 % 在运算符加上英文句点就是对矩阵中的元素进行元素计算 % 示例如下: A * B % 矩阵乘法,要求 A 的列数等于 B 的行数 -A .* B % 元素乘法,要求 A 和 B 形状一致(A 的行数等于 B 的行数, A 的列数等于 B 的列数) -% 元素乘法的结果是与 A 和 B 形状一致的矩阵,其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 +A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完全一致 + % 元素乘法的结果是与 A 和 B 形状一致的矩阵 + % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 % 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: exp(A) % 对矩阵中每个元素做指数运算 @@ -230,7 +234,8 @@ sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该 % 绘图 -x = 0:.10:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi(pi 就是圆周率) +x = 0:0.1:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi + % 其中 pi 为圆周率 y = sin(x); plot(x,y) xlabel('x axis') @@ -288,7 +293,10 @@ clf clear % 清除图形窗口中的图像,并重置图像属性 % 也可以用 gcf 函数返回当前图像的句柄 h = plot(x, y); % 在创建图像时显式地保存图像句柄 set(h, 'Color', 'r') -% 颜色代码:'y' 黄色,'m' 洋红色,'c' 青色,'r' 红色,'g' 绿色,'b' 蓝色,'w' 白色,'k' 黑色 +% 颜色代码: +% 'y' 黄色,'m' 洋红,'c' 青色 +% 'r' 红色,'g' 绿色,'b' 蓝色 +% 'w' 白色,'k' 黑色 set(h, 'Color', [0.5, 0.5, 0.4]) % 也可以使用 RGB 值指定颜色 set(h, 'LineStyle', '--') @@ -328,7 +336,8 @@ load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 % 与脚本文件类似,同样以 .m 作为后缀名 % 但函数文件可以接受用户输入的参数并返回运算结果 % 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突 -% 函数文件的名称应当与其所定义的函数的名称一致(比如下面例子中函数文件就应命名为 double_input.m) +% 函数文件的名称应当与其所定义的函数的名称一致 +% 比如下面例子中函数文件就应命名为 double_input.m % 使用 'help double_input.m' 可返回函数定义中第一行注释信息 function output = double_input(x) % double_input(x) 返回 x 的 2 倍 @@ -468,9 +477,11 @@ fliplr(A) % 将一个矩阵左右翻转 flipud(A) % 将一个矩阵上下翻转 % 矩阵分解 -[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 -[P, D] = eig(A) % 特征值分解:AP = PD,D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 -[U, S, V] = svd(X) % 奇异值分解:XV = US,U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 +[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 +[P, D] = eig(A) % 特征值分解:AP = PD + % D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 +[U, S, V] = svd(X) % 奇异值分解:XV = US + % U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 % 常用向量函数 max % 最大值 -- cgit v1.2.3 From edf7a9818a1b7a16751f7cfc97cd353e7493e866 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 11:46:24 +0800 Subject: Update localized links --- zh-cn/matlab-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index 94d44a3e..d215755c 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -500,5 +500,5 @@ perms(x) % x 元素的全排列 ## 相关资料 -* 官方网页:[http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -* 官方论坛:[http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) +* 官方网页:[MATLAB - 技术计算语言 - MATLAB & Simulink](https://ww2.mathworks.cn/products/matlab.html) +* 官方论坛:[MATLAB Answers - MATLAB Central](https://ww2.mathworks.cn/matlabcentral/answers/) -- cgit v1.2.3 From 5f1439e5616c3ea63647a8e646553e0bdba72d3b Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 11:56:34 +0800 Subject: Keep a line 80 chars --- zh-cn/python3-cn.html.markdown | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 16478fcb..6ba2c2ce 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -10,13 +10,13 @@ filename: learnpython3-cn.py lang: zh-cn --- -Python是由吉多·范罗苏姆(Guido Van Rossum)在90年代早期设计。它是如今最常用的编程 -语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 +Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 +它是如今最常用的编程语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。 -欢迎大家斧正。英文版原作Louie Dinh [@louiedinh](http://twitter.com/louiedinh) -或着Email louiedinh [at] [谷歌的信箱服务]。中文翻译Geoff Liu。 +欢迎大家斧正。英文版原作 Louie Dinh [@louiedinh](http://twitter.com/louiedinh) +邮箱 louiedinh [at] [谷歌的信箱服务]。中文翻译 Geoff Liu。 -注意:这篇教程是特别为Python3写的。如果你想学旧版Python2,我们特别有另一篇教程。 +注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/python/)。 ```python @@ -113,10 +113,11 @@ False or True #=> True # 可以重复参数以节省时间 "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # 如果不想数参数,可以用关键字 -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +"{name} wants to eat {food}".format(name="Bob", food="lasagna") +# => "Bob wants to eat lasagna" # 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 "%s can be %s the %s way" % ("strings", "interpolated", "old") @@ -233,7 +234,8 @@ filled_dict = {"one": 1, "two": 2, "three": 3} filled_dict["one"] # => 1 -# 用keys获得所有的键。因为keys返回一个可迭代对象,所以在这里把结果包在list里。我们下面会详细介绍可迭代。 +# 用 keys 获得所有的键。 +# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 # 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 list(filled_dict.keys()) # => ["three", "two", "one"] -- cgit v1.2.3 From 4f8f1d0a5d75fb70b8cbf4e509dcf02cb4fedf74 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 11:57:12 +0800 Subject: Uniform output symbol --- zh-cn/python3-cn.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index 6ba2c2ce..fd962305 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -70,15 +70,15 @@ not True # => False not False # => True # 逻辑运算符,注意and和or都是小写 -True and False #=> False -False or True #=> True +True and False # => False +False or True # => True # 整数也可以当作布尔值 -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True # 用==判断相等 1 == 1 # => True @@ -133,8 +133,8 @@ None is None # => True # 所有其他值都是True bool(0) # => False bool("") # => False -bool([]) #=> False -bool({}) #=> False +bool([]) # => False +bool({}) # => False #################################################### @@ -263,7 +263,7 @@ filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 # 字典赋值 -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} filled_dict["four"] = 4 # 另一种赋值方法 # 用del删除 @@ -378,17 +378,17 @@ our_iterator = iter(our_iterable) # 迭代器是一个可以记住遍历的位置的对象 # 用__next__可以取得下一个元素 -our_iterator.__next__() #=> "one" +our_iterator.__next__() # => "one" # 再一次调取__next__时会记得位置 -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +our_iterator.__next__() # => "two" +our_iterator.__next__() # => "three" # 当迭代器所有元素都取出后,会抛出StopIteration our_iterator.__next__() # 抛出StopIteration # 可以用list一次取出迭代器所有的元素 -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +list(filled_dict.keys()) # => Returns ["one", "two", "three"] -- cgit v1.2.3 From 0393e51669da1eaaf3c21d81b05bfdc67daa79a5 Mon Sep 17 00:00:00 2001 From: 0u0 Date: Fri, 31 Aug 2018 12:13:02 +0800 Subject: [en] Adjust statement --- matlab.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9cf1f8a4..5790bcc6 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -222,9 +222,9 @@ A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: A.' % Concise version of transpose (without taking complex conjugate) -ctranspose(A) % Hermitian transpose the matrix -% (the transpose, followed by taking complex conjugate of each element) -A' % Concise version of complex transpose +ctranspose(A) % Hermitian transpose the matrix, which is the same as: +A' % Concise version of complex transpose + % (the transpose, followed by taking complex conjugate of each element) -- cgit v1.2.3 From e8ff91c87a9bcdba1d5b74c4dd81ccd59f2c0766 Mon Sep 17 00:00:00 2001 From: muxueqz Date: Fri, 31 Aug 2018 14:35:24 +0800 Subject: Update c-cn.html.markdown --- zh-cn/c-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index 02ec7f7b..8566e811 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -41,7 +41,7 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; void function_1(char c); void function_2(void); -// 如果函数调用在main()之后,那么必须在main()之前 +// 如果函数调用在main()之后,那么必须声明在main()之前 // 先声明一个函数原型 int add_two_ints(int x1, int x2); // 函数原型 -- cgit v1.2.3 From f0849286f84adcfbfd0b4a64ddcdf8e88f27ae28 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 31 Aug 2018 16:54:29 +0530 Subject: Fix build error in 'build/docs/es-es/learnsmallbasic-es/index.html' --- es-es/learnsmallbasic-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/learnsmallbasic-es.html.markdown b/es-es/learnsmallbasic-es.html.markdown index 21208792..ff320afb 100644 --- a/es-es/learnsmallbasic-es.html.markdown +++ b/es-es/learnsmallbasic-es.html.markdown @@ -18,7 +18,7 @@ SmallBASIC fue desarrollado originalmente por Nicholas Christopoulos a finales d Versiones de SmallBASIC se han hecho para una serie dispositivos de mano antiguos, incluyendo Franklin eBookman y el Nokia 770. También se han publicado varias versiones de escritorio basadas en una variedad de kits de herramientas GUI, algunas de las cuales han desaparecido. Las plataformas actualmente soportadas son Linux y Windows basadas en SDL2 y Android basadas en NDK. También está disponible una versión de línea de comandos de escritorio, aunque no suele publicarse en formato binario. Alrededor de 2008 una gran corporación lanzó un entorno de programación BASIC con un nombre de similar. SmallBASIC no está relacionado con este otro proyecto. -```SmallBASIC +``` REM Esto es un comentario ' y esto tambien es un comentario -- cgit v1.2.3 From 478a43c1d4a230a36420cd6d4bc0a27a23f4afef Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 4 Sep 2018 18:25:57 +0530 Subject: Add language code suffix (#3206) --- fr-fr/java-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown index d0f91611..d6c68343 100644 --- a/fr-fr/java-fr.html.markdown +++ b/fr-fr/java-fr.html.markdown @@ -11,7 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] -filename: JavaFr.java +filename: java-fr.java translators: - ['Mathieu Gemard', 'https://github.com/mgemard'] lang: fr-fr -- cgit v1.2.3 From 4d9aff1d02c06ce45edb708366e5da0bf32d4ef0 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 4 Sep 2018 18:29:22 +0530 Subject: Add language code suffix (#3206) --- tr-tr/c++-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index 8ac6ef8b..2c841456 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1,7 +1,7 @@ --- language: c++ lang: tr-tr -filename: learncpp.cpp +filename: learncpp-tr.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From 63924d02cc7c00d77920bfdaa5fded9ea850e95a Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 4 Sep 2018 18:29:36 +0530 Subject: Add language code suffix (#3206) --- tr-tr/git-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown index 72197050..87c1820c 100644 --- a/tr-tr/git-tr.html.markdown +++ b/tr-tr/git-tr.html.markdown @@ -12,7 +12,7 @@ contributors: - ["Milo Gilad", "http://github.com/Myl0g"] - ["Adem Budak", "https://github.com/p1v0t"] -filename: LearnGit.txt +filename: LearnGit-tr.txt --- Git dağınık versiyon kontrol ve kaynak kod yönetim sistemidir. -- cgit v1.2.3 From 7debaf3bfbe3dcb30edffb25c284011b8c649eb1 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 4 Sep 2018 18:31:52 +0530 Subject: Add language code suffix (#3206) --- pt-br/solidity-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/solidity-pt.html.markdown b/pt-br/solidity-pt.html.markdown index 37d15bf2..d4555fa7 100644 --- a/pt-br/solidity-pt.html.markdown +++ b/pt-br/solidity-pt.html.markdown @@ -1,6 +1,6 @@ --- language: Solidity -filename: learnSolidity.sol +filename: learnSolidity-br.sol contributors: - ["Nemil Dalal", "https://www.nemil.com"] - ["Joseph Chow", ""] -- cgit v1.2.3 From 2e55664c992f3f5e18b5b113ce9419504a2e25d4 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 4 Sep 2018 18:43:46 +0530 Subject: Fix YAML error (#3206) --- es-es/csharp-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/csharp-es.html.markdown b/es-es/csharp-es.html.markdown index 5d730497..72a0f90c 100644 --- a/es-es/csharp-es.html.markdown +++ b/es-es/csharp-es.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Irfan Charania", "https://github.com/irfancharania"] - ["Max Yankov", "https://github.com/golergka"] translators: - - ["Olfran Jiménez", "https://twitter.com/neslux"] + - ["Olfran Jiménez", "https://twitter.com/neslux"] lang: es-es --- -- cgit v1.2.3 From 5a78f9b3fc8af1370a7a2a9f01abe3a485177079 Mon Sep 17 00:00:00 2001 From: "Dragos B. Chirila" Date: Tue, 4 Sep 2018 17:24:42 +0200 Subject: Add C99 comments, fix some typos and add clarifications in 'c.html.markdown' --- c.html.markdown | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 684d330a..2d54560b 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Zachary Ferguson", "https://github.io/zfergus2"] - ["himanshu", "https://github.com/himanshu81494"] - ["Joshua Li", "https://github.com/JoshuaRLi"] + - ["Dragos B. Chirila", "https://github.com/dchirila"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -18,7 +19,7 @@ it more than makes up for it with raw speed. Just be aware of its manual memory management and C will take you as far as you need to go. > **About compiler flags** -> +> > By default, gcc and clang are pretty quiet about compilation warnings and > errors, which can be very useful information. Explicitly using stricter > compiler flags is recommended. Here are some recommended defaults: @@ -89,6 +90,8 @@ int main (int argc, char** argv) // All variables MUST be declared at the top of the current block scope // we declare them dynamically along the code for the sake of the tutorial + // (however, C99-compliant compilers allow declarations near the point where + // the value is used) // ints are usually 4 bytes int x_int = 0; @@ -141,6 +144,17 @@ int main (int argc, char** argv) // You can initialize an array to 0 thusly: char my_array[20] = {0}; + // where the "{0}" part is called an "array initializer". + // NOTE that you get away without explicitly declaring the size of the array, + // IF you initialize the array on the same line. So, the following declaration + // is equivalent: + char my_array[] = {0}; + // BUT, then you have to evaluate the size of the array at run-time, like this: + size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]); + // WARNING If you adopt this approach, you should evaluate the size *before* + // you begin passing the array to function (see later discussion), because + // arrays get "downgraded" to raw pointers when they are passed to functions + // (so the statement above will produce the wrong result inside the function). // Indexing an array is like other languages -- or, // rather, other languages are like C @@ -433,7 +447,7 @@ int main (int argc, char** argv) // or when it's the argument of the `sizeof` or `alignof` operator: int arraythethird[10]; int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; - printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); + printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr)); // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type @@ -449,7 +463,7 @@ int main (int argc, char** argv) for (xx = 0; xx < 20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - + // Be careful passing user-provided values to malloc! If you want // to be safe, you can use calloc instead (which, unlike malloc, also zeros out the memory) int* my_other_ptr = calloc(20, sizeof(int)); @@ -522,9 +536,11 @@ Example: in-place string reversal void str_reverse(char *str_in) { char tmp; - int ii = 0; + size_t ii = 0; size_t len = strlen(str_in); // `strlen()` is part of the c standard library - for (ii = 0; ii < len / 2; ii++) { + // NOTE: length returned by `strlen` DOESN'T include the + // terminating NULL byte ('\0') + for (ii = 0; ii < len / 2; ii++) { // in C99 you can directly declare type of `ii` here tmp = str_in[ii]; str_in[ii] = str_in[len - ii - 1]; // ii-th char from end str_in[len - ii - 1] = tmp; @@ -703,7 +719,8 @@ typedef void (*my_fnp_type)(char *); "%3.2f"; // minimum 3 digits left and 2 digits right decimal float "%7.4s"; // (can do with strings too) "%c"; // char -"%p"; // pointer +"%p"; // pointer. NOTE: need to (void *)-cast the pointer, before passing + // it as an argument to `printf`. "%x"; // hexadecimal "%o"; // octal "%%"; // prints % -- cgit v1.2.3 From b955d9386b302c185fa882c627e1df66f9a87c76 Mon Sep 17 00:00:00 2001 From: DevHugo Date: Wed, 5 Sep 2018 10:34:20 +0200 Subject: Translate: Part 2 --- fr-fr/pyqt-fr.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown index a0df8be5..870a2c4e 100644 --- a/fr-fr/pyqt-fr.html.markdown +++ b/fr-fr/pyqt-fr.html.markdown @@ -44,8 +44,8 @@ if __name__ == '__main__': ``` -In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. -Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information. +Pour obtenir certaines des fonctionnalités les plus avancées de **pyqt** nous devons commencer par chercher à construire des éléments supplémentaires. +Ici nous voyons comment introduire une boîte de dialogue popup, utile pour demander une confirmation à un utilisateur ou fournir des informations. ```Python import sys @@ -56,27 +56,27 @@ from PyQt4.QtCore import * def window(): app = QApplication(sys.argv) w = QWidget() - # Create a button and attach to widget w + # Creation d'un bouton attaché au widget w b = QPushButton(w) b.setText("Press me") b.move(50, 50) - # Tell b to call this function when clicked - # notice the lack of "()" on the function call + # Dire à b d'appeler cette fonction quand il est cliqué + # remarquez l'absence de "()" sur l'appel de la fonction b.clicked.connect(showdialog) w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) -# This function should create a dialog window with a button -# that waits to be clicked and then exits the program +# Cette fonction devrait créer une fenêtre de dialogue avec un bouton +# qui attend d'être cliqué puis quitte le programme def showdialog(): d = QDialog() b1 = QPushButton("ok", d) b1.move(50, 50) d.setWindowTitle("Dialog") - # This modality tells the popup to block the parent whilst it's active + # Cette "Modality" dit au popup de bloquer le parent pendant qu'il est actif d.setWindowModality(Qt.ApplicationModal) - # On click I'd like the entire process to end + # En cliquant je voudrais que tout le processus se termine b1.clicked.connect(sys.exit) d.exec_() -- cgit v1.2.3 From 5da3efebe49e5ef7cdfbbaf8e24d6ee679b09e37 Mon Sep 17 00:00:00 2001 From: Rholais Lii Date: Wed, 5 Sep 2018 11:53:59 -0500 Subject: Add language label --- ro-ro/elixir-ro.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown index d8b261af..10fec3c5 100644 --- a/ro-ro/elixir-ro.html.markdown +++ b/ro-ro/elixir-ro.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Ev Bogdanov", "https://github.com/evbogdanov"] translators: - ["Vitalie Lazu", "https://github.com/vitaliel"] - +lang: ro-ro filename: learnelixir-ro.ex --- -- cgit v1.2.3 From 619f97a1d2c33ad48b37d3f5344fb7bf387be62c Mon Sep 17 00:00:00 2001 From: Liu Hao Date: Thu, 6 Sep 2018 13:58:25 +0800 Subject: Fix space style and little content --- zh-cn/typescript-cn.html.markdown | 132 ++++++++++++++++++++------------------ 1 file changed, 69 insertions(+), 63 deletions(-) diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown index 032f89e4..5d6153da 100644 --- a/zh-cn/typescript-cn.html.markdown +++ b/zh-cn/typescript-cn.html.markdown @@ -9,97 +9,103 @@ filename: learntypescript-cn.ts lang: zh-cn --- -TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。 +TypeScript 是一门为开发大型 JavaScript 应用而设计的语言。TypeScript 在 JavaScript 的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是 JavaScript 的超集:所有 JavaScript 代码都是有效的 TypeScript 代码,因此任何 JavaScript 项目都可以无缝引入 TypeScript,TypeScript 编译器最终会把 TypeScript 代码编译成 JavaScript 代码。 -本文只关注TypeScript额外增加的区别于[JavaScript](../javascript-cn/)的语法,. +本文只关注 TypeScript 额外增加的区别于 [JavaScript](../javascript-cn/) 的语法,. -如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。 +如需测试 TypeScript 编译器,你可以到 [Playground](https://www.typescriptlang.org/play/) 编写代码,它会自动将你编写的 TypeScript 代码编译成 JavaScript 代码后,在右侧即时展示出来。 -```js -// TypeScript有三种基本类型 -var isDone: boolean = false; -var lines: number = 42; -var name: string = "Anders"; +```ts +// TypeScript 有三种基本类型,布尔类型、数值类型、字符串类型 +let isDone: boolean = false; +let lines: number = 42; +let name: string = 'Anders'; -// 如果不知道是什么类型,可以使用"any"(任意)类型 -var notSure: any = 4; -notSure = "maybe a string instead"; -notSure = false; // 亦可,定义为布尔型 +// 如果不知道是什么类型,可以使用 "any" (任意)类型 +let notSure: any = 4; +notSure = '可以重新赋值,转换为字符串类型'; +notSure = false; // 亦可,重新定义为布尔类型 -// 对于集合的声明, 有类型化数组和泛型数组 -var list: number[] = [1, 2, 3]; -// 另外一种,使用泛型数组 -var list: Array = [1, 2, 3]; +// 使用 const 关键字将一个字面量修饰为常量 +const numLivesForCat = 9; +numLivesForCat = 1; // 常量不能重新被赋值,所以这里会报错 + +// TypeScript 中的 collection 有两种表示形式, 一种是有类型的数组,另一种是泛型数组 +let list: number[] = [1, 2, 3]; +// 或者,使用泛型数组 +let list: Array = [1, 2, 3]; // 枚举: -enum Color {Red, Green, Blue}; -var c: Color = Color.Green; +enum Color {Red, Green, Blue} +let c: Color = Color.Green; -// 最后,"void"用于函数没有任何返回的特殊情况下 +// 最后是 "void",它用于表明函数没有任何返回值的特殊情况 function bigHorribleAlert(): void { - alert("I'm a little annoying box!"); + alert('我是个烦人的弹出框!'); } -// 函数是"第一等公民"(first class citizens), 支持使用箭头表达式和类型推断 - -// 以下是相等的,TypeScript编译器会把它们编译成相同的JavaScript代码 -var f1 = function(i: number): number { return i * i; } -// 返回推断类型的值 -var f2 = function(i: number) { return i * i; } -var f3 = (i: number): number => { return i * i; } -// 返回推断类型的值 -var f4 = (i: number) => { return i * i; } -// 返回推断类型的值, 单行程式可以不需要return关键字和大括号 -var f5 = (i: number) => i * i; - -// 接口是结构化的,任何具有这些属性的对象都与该接口兼容 +// 函数是"一等公民"(first class citizens), 支持使用 lambda 胖箭头表达式和类型推断 + +// 以下 f1-f5 五个函数是等价的,TypeScript 编译器会把它们编译成相同的 JavaScript 代码(可以到 Playground 验证) +// 一般的函数 +let f1 = function(i: number): number { return i * i; }; +// 根据返回值推断函数返回类型 +let f2 = function(i: number) { return i * i; }; +// 胖箭头表达式 +let f3 = (i: number): number => { return i * i; }; +// 根据返回值推断返回类型的胖箭头表达式 +let f4 = (i: number) => { return i * i; }; +// 根据返回值推断返回类型的胖箭头表达式, 省略花括号的同时,可以同时省去 return 关键字 +let f5 = (i: number) => i * i; + +// 接口是结构化的,任何具备接口中声明的全部属性的对象,都与该接口兼容 interface Person { name: string; - // 可选属性,使用"?"标识 + // 使用 "?" 标识,表明该属性是一个非必需属性 age?: number; // 函数 move(): void; } -// 实现"Person"接口的对象,当它有了"name"和"move"方法之后可被视为一个"Person" -var p: Person = { name: "Bobby", move: () => {} }; -// 带了可选参数的对象 -var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; -// 因为"age"不是"number"类型所以这不是一个"Person" -var invalidPerson: Person = { name: "Bobby", age: true }; +// 实现 "Person" 接口的对象,当它具备 "name" 属性和 "move" 方法之后可被视为一个 "Person" +let p: Person = { name: 'Bobby', move: () => {} }; +// 带可选属性的对象 +let validPerson: Person = { name: 'Bobby', age: 42, move: () => {} }; +// 由于该对象 "age" 属性的类型不是 "number" ,所以这不是一个 "Person" +let invalidPerson: Person = { name: 'Bobby', age: true }; // 接口同样可以描述一个函数的类型 interface SearchFunc { (source: string, subString: string): boolean; } -// 参数名并不重要,参数类型才是重要的 -var mySearch: SearchFunc; +// 参数名并不重要,参数类型才是最重要的 +let mySearch: SearchFunc; mySearch = function(src: string, sub: string) { - return src.search(sub) != -1; -} + return src.search(sub) !== -1; +}; -// 类 - 成员默认为公共的(public) +// 类 - 成员访问权限默认都是公共的 (public) class Point { - // 属性 + // 成员属性 x: number; - // 构造器 - 这里面的public/private关键字会为属性生成样板代码和初始化值 - // 这个例子中,y会被同x一样定义,不需要额外代码 - // 同样支持默认值 + // 构造器 - 在构造器中使用 public/private 关键字修饰的变量,会被声明为类的成员属性。 + // 下面这个例子中,y 会像 x 一样被声明定义为类成员属性,而不再需要额外代码 + // 声明时,同样支持指定默认值 constructor(x: number, public y: number = 0) { this.x = x; } - // 函数 + // 成员函数 dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } // 静态成员 static origin = new Point(0, 0); } -var p1 = new Point(10 ,20); -var p2 = new Point(25); //y为0 +let p1 = new Point(10 , 20); +let p2 = new Point(25); // y 为构造器中指定的默认值:0 // 继承 class Point3D extends Point { @@ -107,14 +113,14 @@ class Point3D extends Point { super(x, y); // 必须显式调用父类的构造器 } - // 重写 + // 重写父类中的 dist() 函数 dist() { - var d = super.dist(); + let d = super.dist(); return Math.sqrt(d * d + this.z * this.z); } } -// 模块, "."可以作为子模块的分隔符 +// 模块, "." 符号可以作为子模块的分隔符 module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -125,12 +131,12 @@ module Geometry { } } -var s1 = new Geometry.Square(5); +let s1 = new Geometry.Square(5); -// 引入模块并定义本地别名 +// 为模块创建一个本地别名 import G = Geometry; -var s2 = new G.Square(10); +let s2 = new G.Square(10); // 泛型 // 类 @@ -146,21 +152,21 @@ interface Pair { } // 以及函数 -var pairToTuple = function(p: Pair) { +let pairToTuple = function(p: Pair) { return new Tuple(p.item1, p.item2); }; -var tuple = pairToTuple({ item1:"hello", item2:"world"}); +let tuple = pairToTuple({ item1: 'hello', item2: 'world'}); // 引用定义文件 /// // 模板字符串(使用反引号的字符串) // 嵌入变量的模板字符串 -var name = 'Tyrone'; -var greeting = `Hi ${name}, how are you?` +let name = 'Tyrone'; +let greeting = `Hi ${name}, how are you?`; // 有多行内容的模板字符串 -var multiline = `This is an example +let multiline = `This is an example of a multiline string`; ``` -- cgit v1.2.3 From a8bb5c76a3b8c96a165dd4133f1f25bee92148c5 Mon Sep 17 00:00:00 2001 From: x89k Date: Sat, 8 Sep 2018 23:46:28 +1000 Subject: Update montilang.html.markdown --- montilang.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/montilang.html.markdown b/montilang.html.markdown index c7bee5a2..cceb7aa1 100644 --- a/montilang.html.markdown +++ b/montilang.html.markdown @@ -1,6 +1,5 @@ --- - -language: "MontiLang" +language: "montilang" filename: montilang.ml contributors: - ["Leo Whitehead", "https://github.com/lduck11007"] -- cgit v1.2.3 From 4bc5f2a91ba9c2b51b4be3f11549dc96806b9237 Mon Sep 17 00:00:00 2001 From: Vap0r1ze Date: Sat, 8 Sep 2018 15:31:57 -0400 Subject: [moonscript/en] Created MoonScript markdown --- moonscript.html.markdown | 570 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 570 insertions(+) create mode 100644 moonscript.html.markdown diff --git a/moonscript.html.markdown b/moonscript.html.markdown new file mode 100644 index 00000000..941578e7 --- /dev/null +++ b/moonscript.html.markdown @@ -0,0 +1,570 @@ +--- +language: moonscript +contributors: + - ["RyanSquared", "https://ryansquared.github.io/"] + - ["Job van der Zwan", "https://github.com/JobLeonard"] +filename: moonscript.moon +--- + +MoonScript is a dynamic scripting language that compiles into Lua. It gives +you the power of one of the fastest scripting languages combined with a +rich set of features. + +See [the MoonScript website](https://moonscript.org/) to see official guides on installation for all platforms. + +```moon +-- Two dashes start a comment. Comments can go until the end of the line. +-- MoonScript transpiled to Lua does not keep comments. + +-- As a note, MoonScript does not use 'do', 'then', or 'end' like Lua would and +-- instead uses an indented syntax, much like Python. + +-------------------------------------------------- +-- 1. Assignment +-------------------------------------------------- + +hello = "world" +a, b, c = 1, 2, 3 +hello = 123 -- Overwrites `hello` from above. + +x = 0 +x += 10 -- x = x + 10 + +s = "hello " +s ..= "world" -- s = s .. "world" + +b = false +b and= true or false -- b = b and (true or false) + +-------------------------------------------------- +-- 2. Literals and Operators +-------------------------------------------------- + +-- Literals work almost exactly as they would in Lua. Strings can be broken in +-- the middle of a line without requiring a \. + +some_string = "exa +mple" -- local some_string = "exa\nmple" + +-- Strings can also have interpolated values, or values that are evaluated and +-- then placed inside of a string. + +some_string = "This is an #{some_string}" -- Becomes 'This is an exa\nmple' + +-------------------------------------------------- +-- 2.1. Function Literals +-------------------------------------------------- + +-- Functions are written using arrows: + +my_function = -> -- compiles to `function() end` +my_function() -- calls an empty function + +-- Functions can be called without using parenthesis. Parentheses may still be +-- used to have priority over other functions. + +func_a = -> print "Hello World!" +func_b = -> + value = 100 + print "The value: #{value}" + +-- If a function needs no parameters, it can be called with either `()` or `!`. + +func_a! +func_b() + +-- Functions can use arguments by preceding the arrow with a list of argument +-- names bound by parentheses. + +sum = (x, y)-> x + y -- The last expression is returned from the function. +print sum(5, 10) + +-- Lua has an idiom of sending the first argument to a function as the object, +-- like a 'self' object. Using a fat arrow (=>) instead of a skinny arrow (->) +-- automatically creates a `self` variable. `@x` is a shorthand for `self.x`. + +func = (num)=> @value + num + +-- Default arguments can also be used with function literals: + +a_function = (name = "something", height=100)-> + print "Hello, I am #{name}.\nMy height is #{height}." + +-- Because default arguments are calculated in the body of the function when +-- transpiled to Lua, you can reference previous arguments. + +some_args = (x = 100, y = x + 1000)-> print(x + y) + +-------------------------------------------------- +-- Considerations +-------------------------------------------------- + +-- The minus sign plays two roles, a unary negation operator and a binary +-- subtraction operator. It is recommended to always use spaces between binary +-- operators to avoid the possible collision. + +a = x - 10 -- a = x - 10 +b = x-10 -- b = x - 10 +c = x -y -- c = x(-y) +d = x- z -- d = x - z + +-- When there is no space between a variable and string literal, the function +-- call takes priority over following expressions: + +x = func"hello" + 100 -- func("hello") + 100 +y = func "hello" + 100 -- func("hello" + 100) + +-- Arguments to a function can span across multiple lines as long as the +-- arguments are indented. The indentation can be nested as well. + +my_func 5, -- called as my_func(5, 8, another_func(6, 7, 9, 1, 2), 5, 4) + 8, another_func 6, 7, -- called as + 9, 1, 2, -- another_func(6, 7, 9, 1, 2) + 5, 4 + +-- If a function is used at the start of a block, the indentation can be +-- different than the level of indentation used in a block: + +if func 1, 2, 3, -- called as func(1, 2, 3, "hello", "world") + "hello", + "world" + print "hello" + +-------------------------------------------------- +-- 3. Tables +-------------------------------------------------- + +-- Tables are defined by curly braces, like Lua: + +some_values = {1, 2, 3, 4} + +-- Tables can use newlines instead of commas. + +some_other_values = { + 5, 6 + 7, 8 +} + +-- Assignment is done with `:` instead of `=`: + +profile = { + name: "Bill" + age: 200 + "favorite food": "rice" +} + +-- Curly braces can be left off for `key: value` tables. + +y = type: "dog", legs: 4, tails: 1 + +profile = + height: "4 feet", + shoe_size: 13, + favorite_foods: -- nested table + foo: "ice cream", + bar: "donuts" + +my_function dance: "Tango", partner: "none" -- :( forever alone + +-- Tables constructed from variables can use the same name as the variables +-- by using `:` as a prefix operator. + +hair = "golden" +height = 200 +person = {:hair, :height} + +-- Like in Lua, keys can be non-string or non-numeric values by using `[]`. + +t = + [1 + 2]: "hello" + "hello world": true -- Can use string literals without `[]`. + +-------------------------------------------------- +-- 3.1. Table Comprehensions +-------------------------------------------------- + +-- List Comprehensions + +-- Creates a copy of a list but with all items doubled. Using a star before a +-- variable name or table can be used to iterate through the table's values. + +items = {1, 2, 3, 4} +doubled = [item * 2 for item in *items] +-- Uses `when` to determine if a value should be included. + +slice = [item for item in *items when i > 1 and i < 3] + +-- `for` clauses inside of list comprehensions can be chained. + +x_coords = {4, 5, 6, 7} +y_coords = {9, 2, 3} + +points = [{x,y} for x in *x_coords for y in *y_coords] + +-- Numeric for loops can also be used in comprehensions: + +evens = [i for i=1, 100 when i % 2 == 0] + +-- Table Comprehensions are very similar but use `{` and `}` and take two +-- values for each iteration. + +thing = color: "red", name: "thing", width: 123 +thing_copy = {k, v for k, v in pairs thing} + +-- Tables can be "flattened" from key-value pairs in an array by using `unpack` +-- to return both values, using the first as the key and the second as the +-- value. + +tuples = {{"hello", "world"}, {"foo", "bar"}} +table = {unpack tuple for tuple in *tuples} + +-- Slicing can be done to iterate over only a certain section of an array. It +-- uses the `*` notation for iterating but appends `[start, end, step]`. + +-- The next example also shows that this syntax can be used in a `for` loop as +-- well as any comprehensions. + +for item in *points[1, 10, 2] + print unpack item + +-- Any undesired values can be left off. The second comma is not required if +-- the step is not included. + +words = {"these", "are", "some", "words"} +for word in *words[,3] + print word + +-------------------------------------------------- +-- 4. Control Structures +-------------------------------------------------- + +have_coins = false +if have_coins + print "Got coins" +else + print "No coins" + +-- Use `then` for single-line `if` +if have_coins then "Got coins" else "No coins" + +-- `unless` is the opposite of `if` +unless os.date("%A") == "Monday" + print "It is not Monday!" + +-- `if` and `unless` can be used as expressions +is_tall = (name)-> if name == "Rob" then true else false +message = "I am #{if is_tall "Rob" then "very tall" else "not so tall"}" +print message -- "I am very tall" + +-- `if`, `elseif`, and `unless` can evaluate assignment as well as expressions. +if x = possibly_nil! -- sets `x` to `possibly_nil()` and evaluates `x` + print x + +-- Conditionals can be used after a statement as well as before. This is +-- called a "line decorator". + +is_monday = os.date("%A") == "Monday" +print("It IS Monday!") if isMonday +print("It is not Monday..") unless isMonday +--print("It IS Monday!" if isMonday) -- Not a statement, does not work + +-------------------------------------------------- +-- 4.1 Loops +-------------------------------------------------- + +for i = 1, 10 + print i + +for i = 10, 1, -1 do print i -- Use `do` for single-line loops. + +i = 0 +while i < 10 + continue if i % 2 == 0 -- Continue statement; skip the rest of the loop. + print i + +-- Loops can be used as a line decorator, just like conditionals +print "item: #{item}" for item in *items + +-- Using loops as an expression generates an array table. The last statement +-- in the block is coerced into an expression and added to the table. +my_numbers = for i = 1, 6 do i -- {1, 2, 3, 4, 5, 6} + +-- use `continue` to filter out values +odds = for i in *my_numbers + continue if i % 2 == 0 -- acts opposite to `when` in comprehensions! + i -- Only added to return table if odd + +-- A `for` loop returns `nil` when it is the last statement of a function +-- Use an explicit `return` to generate a table. +print_squared = (t) -> for x in *t do x*x -- returns `nil` +squared = (t) -> return for x in *t do x*x -- returns new table of squares + +-- The following does the same as `(t) -> [i for i in *t when i % 2 == 0]` +-- But list comprehension generates better code and is more readable! + +filter_odds = (t) -> + return for x in *t + if x % 2 == 0 then x else continue +evens = filter_odds(my_numbers) -- {2, 4, 6} + +-------------------------------------------------- +-- 4.2 Switch Statements +-------------------------------------------------- + +-- Switch statements are a shorthand way of writing multiple `if` statements +-- checking against the same value. The value is only evaluated once. + +name = "Dan" + +switch name + when "Dave" + print "You are Dave." + when "Dan" + print "You are not Dave, but Dan." + else + print "You are neither Dave nor Dan." + +-- Switches can also be used as expressions, as well as compare multiple +-- values. The values can be on the same line as the `when` clause if they +-- are only one expression. + +b = 4 +next_even = switch b + when 1 then 2 + when 2, 3 then 4 + when 4, 5 then 6 + else error "I can't count that high! D:" + +-------------------------------------------------- +-- 5. Object Oriented Programming +-------------------------------------------------- + +-- Classes are created using the `class` keyword followed by an identifier, +-- typically written using CamelCase. Values specific to a class can use @ as +-- the identifier instead of `self.value`. + +class Inventory + new: => @items = {} + add_item: (name)=> -- note the use of fat arrow for classes! + @items[name] = 0 unless @items[name] + @items[name] += 1 + +-- The `new` function inside of a class is special because it is called when +-- an instance of the class is created. + +-- Creating an instance of the class is as simple as calling the class as a +-- function. Calling functions inside of the class uses \ to separate the +-- instance from the function it is calling. + +inv = Inventory! +inv\add_item "t-shirt" +inv\add_item "pants" + +-- Values defined in the class - not the new() function - will be shared across +-- all instances of the class. + +class Person + clothes: {} + give_item: (name)=> + table.insert @clothes name + +a = Person! +b = Person! + +a\give_item "pants" +b\give_item "shirt" + +-- prints out both "pants" and "shirt" + +print item for item in *a.clothes + +-- Class instances have a value `.__class` that are equal to the class object +-- that created the instance. + +assert(b.__class == Person) + +-- Variables declared in class body the using the `=` operator are locals, +-- so these "private" variables are only accessible within the current scope. + +class SomeClass + x = 0 + reveal: -> + x += 1 + print x + +a = SomeClass! +b = SomeClass! +print a.x -- nil +a.reveal! -- 1 +b.reveal! -- 2 + +-------------------------------------------------- +-- 5.1 Inheritance +-------------------------------------------------- + +-- The `extends` keyword can be used to inherit properties and methods from +-- another class. + +class Backpack extends Inventory + size: 10 + add_item: (name)=> + error "backpack is full" if #@items > @size + super name -- calls Inventory.add_item with `name`. + +-- Because a `new` method was not added, the `new` method from `Inventory` will +-- be used instead. If we did want to use a constructor while still using the +-- constructor from `Inventory`, we could use the magical `super` function +-- during `new()`. + +-- When a class extends another, it calls the method `__inherited` on the +-- parent class (if it exists). It is always called with the parent and the +-- child object. + +class ParentClass + @__inherited: (child)=> + print "#{@__name} was inherited by #{child.__name}" + a_method: (a, b) => print a .. ' ' .. b + +-- Will print 'ParentClass was inherited by MyClass' + +class MyClass extends ParentClass + a_method: => + super "hello world", "from MyClass!" + assert super == ParentClass + +-------------------------------------------------- +-- 6. Scope +-------------------------------------------------- + +-- All values are local by default. The `export` keyword can be used to +-- declare the variable as a global value. + +export var_1, var_2 +var_1, var_3 = "hello", "world" -- var_3 is local, var_1 is not. + +export this_is_global_assignment = "Hi!" + +-- Classes can also be prefixed with `export` to make them global classes. +-- Alternatively, all CamelCase variables can be exported automatically using +-- `export ^`, and all values can be exported using `export *`. + +-- `do` lets you manually create a scope, for when you need local variables. + +do + x = 5 +print x -- nil + +-- Here we use `do` as an expression to create a closure. + +counter = do + i = 0 + -> + i += 1 + return i + +print counter! -- 1 +print counter! -- 2 + +-- The `local` keyword can be used to define variables +-- before they are assigned. + +local var_4 +if something + var_4 = 1 +print var_4 -- works because `var_4` was set in this scope, not the `if` scope. + +-- The `local` keyword can also be used to shadow an existing variable. + +x = 10 +if false + local x + x = 12 +print x -- 10 + +-- Use `local *` to forward-declare all variables. +-- Alternatively, use `local ^` to forward-declare all CamelCase values. + +local * + +first = -> + second! + +second = -> + print data + +data = {} + +-------------------------------------------------- +-- 6.1 Import +-------------------------------------------------- + +-- Values from a table can be brought to the current scope using the `import` +-- and `from` keyword. Names in the `import` list can be preceded by `\` if +-- they are a module function. + +import insert from table -- local insert = table.insert +import \add from state: 100, add: (value)=> @state + value +print add 22 + +-- Like tables, commas can be excluded from `import` lists to allow for longer +-- lists of imported items. + +import + asdf, gh, jkl + antidisestablishmentarianism + from {} + +-------------------------------------------------- +-- 6.2 With +-------------------------------------------------- + +-- The `with` statement can be used to quickly call and assign values in an +-- instance of a class or object. + +file = with File "lmsi15m.moon" -- `file` is the value of `set_encoding()`. + \set_encoding "utf8" + +create_person = (name, relatives)-> + with Person! + .name = name + \add_relative relative for relative in *relatives +me = create_person "Ryan", {"sister", "sister", "brother", "dad", "mother"} + +with str = "Hello" -- assignment as expression! :D + print "original: #{str}" + print "upper: #{\upper!}" + +-------------------------------------------------- +-- 6.3 Destructuring +-------------------------------------------------- + +-- Destructuring can take arrays, tables, and nested tables and convert them +-- into local variables. + +obj2 = + numbers: {1, 2, 3, 4} + properties: + color: "green" + height: 13.5 + +{numbers: {first, second}, properties: {:color}} = obj2 + +print first, second, color -- 1 2 green + +-- `first` and `second` return [1] and [2] because they are as an array, but +-- `:color` is like `color: color` so it sets itself to the `color` value. + +-- Destructuring can be used in place of `import`. + +{:max, :min, random: rand} = math -- rename math.random to rand + +-- Destructuring can be done anywhere assignment can be done. + +for {left, right} in *{{"hello", "world"}, {"egg", "head"}} + print left, right +``` + +## Additional Resources + +- [Language Guide](https://moonscript.org/reference/) +- [Online Compiler](https://moonscript.org/compiler/) -- cgit v1.2.3 From 6d087ae0f289e7013807639cbd609f991f968166 Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 8 Sep 2018 23:29:35 +0200 Subject: Revert "[scala/en] Make return value example actually demonstrate issue" (#3213) --- scala.html.markdown | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 7429ac9a..28424684 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,20 +253,16 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def addTenButMaybeTwelve(x: Int): Int = { - val anonMaybeAddTwo: Int => Int = { z => +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of addTenButMaybeTwelve! + return z // This line makes z the return value of foo! else - z + 2 // This line is the return value of anonMaybeAddTwo + z + 2 // This line is the return value of anonFunc } - anonMaybeAddTwo(x) + 10 // This line is the return value of addTenButMaybeTwelve + anonFunc(x) // This line is the return value of foo } -addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 -addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so - // last line doesn't get called and 10 is not added - ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3 From 305e08b9594b65a3f0a62920e6ad165a9d861ce9 Mon Sep 17 00:00:00 2001 From: DevHugo Date: Mon, 10 Sep 2018 11:54:47 +0200 Subject: Update pyqt-fr.html.markdown --- fr-fr/pyqt-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown index 870a2c4e..6da9a380 100644 --- a/fr-fr/pyqt-fr.html.markdown +++ b/fr-fr/pyqt-fr.html.markdown @@ -74,7 +74,7 @@ def showdialog(): b1 = QPushButton("ok", d) b1.move(50, 50) d.setWindowTitle("Dialog") - # Cette "Modality" dit au popup de bloquer le parent pendant qu'il est actif + # Cette modalité dit au popup de bloquer le parent pendant qu'il est actif d.setWindowModality(Qt.ApplicationModal) # En cliquant je voudrais que tout le processus se termine b1.clicked.connect(sys.exit) -- cgit v1.2.3 From 14719728ddbe8b71379c7702d3985f1c8b352e15 Mon Sep 17 00:00:00 2001 From: Zohar Jackson Date: Mon, 10 Sep 2018 11:44:00 -0400 Subject: Update kotlin.html.markdown --- kotlin.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 0c787d7e..86d1baa0 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -370,6 +370,12 @@ fun useObject() { val someRef: Any = ObjectExample // we use objects name just as is } + +/* The not-null assertion operator (!!) converts any value to a non-null type and +throws an exception if the value is null. +*/ +var b: String? = "abc" +val l = b!!.length ``` ### Further Reading -- cgit v1.2.3 From 7daca0eaa49f8de64965c18df5333fb1392cdd3b Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Tue, 11 Sep 2018 19:01:43 +0800 Subject: Updates as per request --- processing.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 84c2dee1..5ec123b3 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -1,5 +1,5 @@ --- -language: "Processing" +language: processing filename: learnprocessing.pde contributors: - ["Phone Thant Ko", "http://github.com/phonethantko"] @@ -417,7 +417,7 @@ However, that does not apply when you introduce external libraries, packages and ## What's Next? -Here, I have compiled some useful resources: +Some useful resources: - [Processing Website](http://processing.org) - [Processing Sketches](http://openprocessing.org) -- cgit v1.2.3 From 0bbd51ba4894e9030066e1d850fa607e95fafecc Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Tue, 11 Sep 2018 19:08:18 +0800 Subject: Fixing the wrong placement --- processing.html.markdown | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 5ec123b3..fc5dc997 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -415,9 +415,7 @@ the program flow. However, that does not apply when you introduce external libraries, packages and even your own classes. (Trust me! Processing projects can get real humongous...) -## What's Next? - -Some useful resources: +## Some useful resources: - [Processing Website](http://processing.org) - [Processing Sketches](http://openprocessing.org) -- cgit v1.2.3 From c8284c9c959abf9662d03bc152af6c8a49a12e58 Mon Sep 17 00:00:00 2001 From: dtkerns Date: Tue, 11 Sep 2018 13:52:30 -0700 Subject: Update awk.html.markdown --- awk.html.markdown | 244 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 134 insertions(+), 110 deletions(-) diff --git a/awk.html.markdown b/awk.html.markdown index de26c0a1..3d2c4ccb 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -6,14 +6,15 @@ contributors: --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read +AWK is a standard tool on every POSIX-compliant UNIX system. It's like +flex/lex, from the command-line, perfect for text-processing tasks and +other scripting needs. It has a C-like syntax, but without mandatory +semicolons (although, you should use them anyway, because they are required +when you're writing one-liners, something AWK excells at), manual memory +management, or static typing. It excels at text processing. You can call to +it from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Readability. AWK is easier to read than Perl. For simple text-processing scripts, particularly ones that read files line by line and split on delimiters, AWK is probably the right tool for the job. @@ -23,8 +24,23 @@ the job. # Comments are like this -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. + +# AWK programs consist of a collection of patterns and actions. +pattern1 { action; } # just like lex +pattern2 { action; } + +# There is an implied loop and AWK automatically reads and parses each +# record of each file supplied. Each record is split by the FS delimiter, +# which defaults to white-space (multiple spaces,tabs count as one) +# You cann assign FS either on the command line (-F C) or in your BEGIN +# pattern + +# One of the special patterns is BEGIN. The BEGIN pattern is true +# BEFORE any of the files are read. The END pattern is true after +# an End-of-file from the last file (or standard-in if no files specified) +# There is also an output field separator (OFS) that you can assign, which +# defaults to a single space + BEGIN { # BEGIN will run at the beginning of the program. It's where you put all @@ -32,114 +48,116 @@ BEGIN { # have no text files, then think of BEGIN as the main entry point. # Variables are global. Just set them or use them, no need to declare.. - count = 0 + count = 0; # Operators just like in C and friends - a = count + 1 - b = count - 1 - c = count * 1 - d = count / 1 # integer division - e = count % 1 # modulus - f = count ^ 1 # exponentiation - - a += 1 - b -= 1 - c *= 1 - d /= 1 - e %= 1 - f ^= 1 + a = count + 1; + b = count - 1; + c = count * 1; + d = count / 1; # integer division + e = count % 1; # modulus + f = count ^ 1; # exponentiation + + a += 1; + b -= 1; + c *= 1; + d /= 1; + e %= 1; + f ^= 1; # Incrementing and decrementing by one - a++ - b-- + a++; + b--; # As a prefix operator, it returns the incremented value - ++a - --b + ++a; + --b; # Notice, also, no punctuation such as semicolons to terminate statements # Control statements if (count == 0) - print "Starting with count of 0" + print "Starting with count of 0"; else - print "Huh?" + print "Huh?"; # Or you could use the ternary operator - print (count == 0) ? "Starting with count of 0" : "Huh?" + print (count == 0) ? "Starting with count of 0" : "Huh?"; # Blocks consisting of multiple lines use braces while (a < 10) { print "String concatenation is done" " with a series" " of" - " space-separated strings" - print a + " space-separated strings"; + print a; - a++ + a++; } for (i = 0; i < 10; i++) - print "Good ol' for loop" + print "Good ol' for loop"; # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal + # a < b # Less than + # a <= b # Less than or equal + # a != b # Not equal + # a == b # Equal + # a > b # Greater than + # a >= b # Greater than or equal # Logical operators as well - a && b # AND - a || b # OR + # a && b # AND + # a || b # OR # In addition, there's the super useful regular expression match if ("foo" ~ "^fo+$") - print "Fooey!" + print "Fooey!"; if ("boo" !~ "^fo+$") - print "Boo!" + print "Boo!"; # Arrays - arr[0] = "foo" - arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. - - # You also have associative arrays - assoc["foo"] = "bar" - assoc["bar"] = "baz" + 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) + assoc["foo"] = "bar"; + assoc["bar"] = "baz"; # And multi-dimensional arrays, with some limitations I won't mention here - multidim[0,0] = "foo" - multidim[0,1] = "bar" - multidim[1,0] = "baz" - multidim[1,1] = "boo" + multidim[0,0] = "foo"; + multidim[0,1] = "bar"; + multidim[1,0] = "baz"; + multidim[1,1] = "boo"; # You can test for array membership if ("foo" in assoc) - print "Fooey!" + print "Fooey!"; # You can also use the 'in' operator to traverse the keys of an array for (key in assoc) - print assoc[key] + print assoc[key]; # The command line is in a special array called ARGV for (argnum in ARGV) - print ARGV[argnum] + print ARGV[argnum]; # You can remove elements of an array # This is particularly useful to prevent AWK from assuming the arguments # are files for it to process - delete ARGV[1] + delete ARGV[1]; # The number of command line arguments is in a variable called ARGC - print ARGC + print ARGC; # AWK has several built-in functions. They fall into three categories. I'll # demonstrate each of them in their own functions, defined later. - return_value = arithmetic_functions(a, b, c) - string_functions() - io_functions() + return_value = arithmetic_functions(a, b, c); + string_functions(); + io_functions(); } # Here's how you define a function @@ -159,26 +177,26 @@ function arithmetic_functions(a, b, c, d) { # Now, to demonstrate the arithmetic functions # Most AWK implementations have some standard trig functions - localvar = sin(a) - localvar = cos(a) - localvar = atan2(b, a) # arc tangent of b / a + localvar = sin(a); + localvar = cos(a); + localvar = atan2(b, a); # arc tangent of b / a # And logarithmic stuff - localvar = exp(a) - localvar = log(a) + localvar = exp(a); + localvar = log(a); # Square root - localvar = sqrt(a) + localvar = sqrt(a); # Truncate floating point to integer - localvar = int(5.34) # localvar => 5 + localvar = int(5.34); # localvar => 5 # Random numbers - srand() # Supply a seed as an argument. By default, it uses the time of day - localvar = rand() # Random number between 0 and 1. + srand(); # Supply a seed as an argument. By default, it uses the time of day + localvar = rand(); # Random number between 0 and 1. # Here's how to return a value - return localvar + return localvar; } function string_functions( localvar, arr) { @@ -188,61 +206,66 @@ function string_functions( localvar, arr) { # Search and replace, first instance (sub) or all instances (gsub) # Both return number of matches replaced - 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" + 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" # Search for a string that matches a regular expression # index() does the same thing, but doesn't allow a regular expression - match(localvar, "t") # => 4, since the 't' is the fourth character + match(localvar, "t"); # => 4, since the 't' is the fourth character # Split on a delimiter - split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + n = split("foo-bar-baz", arr, "-"); # 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" - substr("foobar", 2, 3) # => "oob" - substr("foobar", 4) # => "bar" - length("foo") # => 3 - tolower("FOO") # => "foo" - toupper("foo") # => "FOO" + sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" + substr("foobar", 2, 3); # => "oob" + substr("foobar", 4); # => "bar" + length("foo"); # => 3 + tolower("FOO"); # => "foo" + toupper("foo"); # => "FOO" } function io_functions( localvar) { # You've already seen print - print "Hello world" + print "Hello world"; # There's also printf - printf("%s %d %d %d\n", "Testing", 1, 2, 3) + printf("%s %d %d %d\n", "Testing", 1, 2, 3); # 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: + # it feel sort of like shell scripting, but to get the same output, the string + # must match exactly, so use a vaiable: + + outfile = "/tmp/foobar.txt"; - print "foobar" >"/tmp/foobar.txt" + print "foobar" > outfile; - # Now the string "/tmp/foobar.txt" is a file handle. You can close it: - close("/tmp/foobar.txt") + # Now the string outfile is a file handle. You can close it: + close(outfile); # Here's how you run something in the shell - system("echo foobar") # => prints foobar + system("echo foobar"); # => prints foobar # Reads a line from standard input and stores in localvar - getline localvar + getline localvar; - # Reads a line from a pipe - "echo foobar" | getline localvar # localvar => "foobar" - close("echo foobar") + # Reads a line from a pipe (again, use a string so you close it properly) + cmd = "echo foobar"; + cmd | getline localvar; # localvar => "foobar" + close(cmd); # Reads a line from a file and stores in localvar - getline localvar <"/tmp/foobar.txt" - close("/tmp/foobar.txt") + infile = "/tmp/foobar.txt"; + getline localvar < infile; + close(infile); } # As I said at the beginning, AWK programs consist of a collection of patterns -# and actions. You've already seen the all-important BEGIN pattern. Other +# and actions. You've already seen the BEGIN pattern. Other # patterns are used only if you're processing lines from files or standard # input. # @@ -257,7 +280,7 @@ function io_functions( localvar) { # expression, /^fo+bar$/, and will be skipped for any line that fails to # match it. Let's just print the line: - print + print; # Whoa, no argument! That's because print has a default argument: $0. # $0 is the name of the current line being processed. It is created @@ -268,16 +291,16 @@ function io_functions( localvar) { # does. And, like the shell, each field can be access with a dollar sign # This will print the second and fourth fields in the line - print $2, $4 + print $2, $4; # AWK automatically defines many other variables to help you inspect and # process each line. The most important one is NF # Prints the number of fields on this line - print NF + print NF; # Print the last field on this line - print $NF + print $NF; } # Every pattern is actually a true/false test. The regular expression in the @@ -286,7 +309,7 @@ function io_functions( localvar) { # currently processing. Thus, the complete version of it is this: $0 ~ /^fo+bar$/ { - print "Equivalent to the last pattern" + print "Equivalent to the last pattern"; } a > 0 { @@ -315,10 +338,10 @@ a > 0 { BEGIN { # First, ask the user for the name - print "What name would you like the average age for?" + print "What name would you like the average age for?"; # Get a line from standard input, not from files on the command line - getline name <"/dev/stdin" + getline name < "/dev/stdin"; } # Now, match every line whose first field is the given name @@ -335,8 +358,8 @@ $1 == name { # ...etc. There are plenty more, documented in the man page. # Keep track of a running total and how many lines matched - sum += $3 - nlines++ + sum += $3; + nlines++; } # Another special pattern is called END. It will run after processing all the @@ -348,7 +371,7 @@ $1 == name { END { if (nlines) - print "The average age for " name " is " sum / nlines + print "The average age for " name " is " sum / nlines; } ``` @@ -357,3 +380,4 @@ 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. +* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) -- cgit v1.2.3 From 70f896eed7d3a3733ebcdf2fd280a7ffa660304b Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 13 Sep 2018 00:18:37 +0530 Subject: Fix printf, closes #2730 --- c.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 2d54560b..bf93dcf5 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -388,8 +388,8 @@ int main (int argc, char** argv) // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from // Integral types can be cast to floating-point types, and vice-versa. - printf("%f\n", (float)100); // %f formats a float - printf("%lf\n", (double)100); // %lf formats a double + printf("%f\n", (double) 100); // %f always formats a double... + printf("%f\n", (float) 100); // ...even with a float. printf("%d\n", (char)100.0); /////////////////////////////////////// -- cgit v1.2.3 From c8c351d1531f1e7a2507f233652a2e23a588ae66 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 13 Sep 2018 00:47:08 +0530 Subject: Fix rst rendering issue, closes #2775 --- rst.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/rst.html.markdown b/rst.html.markdown index 65f848ed..fbf9a069 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -47,9 +47,6 @@ Title are underlined with equals signs too Subtitles with dashes --------------------- -And sub-subtitles with tildes -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. Lists are as simple as in Markdown: -- cgit v1.2.3 From 4c3ea2021d5b93e57300108798e07cf91b1ef4f4 Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Fri, 14 Sep 2018 16:55:28 +0800 Subject: wrap some line --- zh-cn/awk-cn.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index 1fafa559..3fea782b 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -182,7 +182,8 @@ function string_functions( localvar, arr) { # 搜索匹配正则的字符串 # index() 也是搜索, 不支持正则 - match(localvar, "t") # => 4, 't'在4号位置. (译者注: awk是1开始计数的,不是常见的0-base) + match(localvar, "t") # => 4, 't'在4号位置. + # (译者注: awk是1开始计数的,不是常见的0-base) # 按分隔符分隔 split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] @@ -204,8 +205,8 @@ function io_functions( localvar) { # 也有printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK本身没有文件句柄, 当你使用需要文件的东西时会自动打开文件, 做文件I/O时, 字符串就是打开的文件句柄. - # 这看起来像Shell + # AWK本身没有文件句柄, 当你使用需要文件的东西时会自动打开文件, + # 做文件I/O时, 字符串就是打开的文件句柄. 这看起来像Shell print "foobar" >"/tmp/foobar.txt" # 现在"/tmp/foobar.txt"字符串是一个文件句柄, 你可以关闭它 @@ -267,7 +268,8 @@ a > 0 { # 只要a是整数, 这块会在每一行上执行. } -# 就是这样, 处理文本文件, 一次读一行, 对行做一些操作. 按分隔符分隔, 这在UNIX中很常见, awk都帮你做好了. +# 就是这样, 处理文本文件, 一次读一行, 对行做一些操作. +# 按分隔符分隔, 这在UNIX中很常见, awk都帮你做好了. # 你所需要做的是基于自己的需求写一些模式和动作. # 这里有一个快速的例子, 展示了AWK所擅长做的事. -- cgit v1.2.3 From d3335643d1709b6bf4b9c60b4b34de679b84b32b Mon Sep 17 00:00:00 2001 From: Yvan Sraka Date: Mon, 17 Sep 2018 08:14:02 +0200 Subject: Update lambda-calculus-fr.html.markdown --- fr-fr/lambda-calculus-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/lambda-calculus-fr.html.markdown b/fr-fr/lambda-calculus-fr.html.markdown index 68868830..c91f21d6 100644 --- a/fr-fr/lambda-calculus-fr.html.markdown +++ b/fr-fr/lambda-calculus-fr.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Max Sun", "http://github.com/maxsun"] translators: - ["Yvan Sraka", "https://github.com/yvan-sraka"] +lang: fr-fr --- # Lambda-calcul @@ -102,4 +103,4 @@ En utilisant `S`, nous pouvons définir la fonction `ADD`: 1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) 2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) -3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) -- cgit v1.2.3 From aa51a89522709ec7b824fbf11f896994d2d783a0 Mon Sep 17 00:00:00 2001 From: Angel Arciniega Date: Tue, 18 Sep 2018 21:01:24 -0700 Subject: Add F# tutorial in Spanish New tutorial of F# in spanish from Angel Arciniega --- es-es/fsharp-es.html.markdown | 629 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 629 insertions(+) create mode 100644 es-es/fsharp-es.html.markdown diff --git a/es-es/fsharp-es.html.markdown b/es-es/fsharp-es.html.markdown new file mode 100644 index 00000000..b7f80c44 --- /dev/null +++ b/es-es/fsharp-es.html.markdown @@ -0,0 +1,629 @@ +--- +language: F# +lang: es-es +contributors: + - ['Scott Wlaschin', 'http://fsharpforfunandprofit.com/'] +translators: + - ['Angel Arciniega', 'https://github.com/AngelsProjects'] +filename: learnfsharp-es.fs +--- + +F# es un lenguaje de programación funcional y orientado a objetos. Es gratis y su código fuente está abierto. Se ejecuta en Linux, Mac, Windows y más. + +Tiene un poderoso sistema de tipado que atrapa muchos errores de tiempo de compilación, pero usa inferencias de tipados que le permiten ser leídos como un lenguaje dinámico. + +La sintaxis de F# es diferente de los lenguajes que heredan de C. + +- Las llaves no se usan para delimitar bloques de código. En cambio, se usa sangría (como en Python). +- Los espacios se usan para separar parámetros en lugar de comas. + +Si quiere probar el siguiente código, puede ir a [tryfsharp.org](http://www.tryfsharp.org/Create) y pegarlo en [REPL](https://es.wikipedia.org/wiki/REPL). + +```fsharp +// Los comentarios de una línea se escibren con una doble diagonal +(* Los comentarios multilínea usan parentesis (* . . . *) + +-final del comentario multilínea- *) + +// ================================================ +// Syntaxis básica +// ================================================ + +// ------ "Variables" (pero no realmente) ------ +// La palabra reservada "let" define un valor (inmutable) +let miEntero = 5 +let miFlotante = 3.14 +let miCadena = "hola" // Tenga en cuenta que no es necesario ningún tipado + +// ------ Listas ------ +let dosACinco = [2;3;4;5] // Los corchetes crean una lista con + // punto y coma para delimitadores. +let unoACinco = 1 :: dosACinco // :: Crea una lista con un nuevo elemento +// El resultado es [1;2;3;4;5] +let ceroACinco = [0;1] @ dosACinco // @ Concatena dos listas + +// IMPORTANTE: las comas no se usan para delimitar, +// solo punto y coma ! + +// ------ Funciones ------ +// La palabra reservada "let" también define el nombre de una función. +let cuadrado x = x * x // Tenga en cuenta que no se usa paréntesis. +cuadrado 3 // Ahora, ejecutemos la función. + // De nuevo, sin paréntesis. + +let agregar x y = x + y // ¡No use add (x, y)! Eso significa + // algo completamente diferente. +agregar 2 3 // Ahora, ejecutemos la función. + +// Para definir una función en varias líneas, usemos la sangría. +// Los puntos y coma no son necesarios. +let pares lista = + let esPar x = x%2 = 0 // Establece "esPar" como una función anidada + List.filter esPar lista // List.filter es una función de la biblioteca + // dos parámetros: una función que devuelve un + // booleano y una lista en la que trabajar + +pares unoACinco // Ahora, ejecutemos la función. + +// Puedes usar paréntesis para aclarar. +// En este ejemplo, "map" se ejecuta primero, con dos argumentos, +// entonces "sum" se ejecuta en el resultado. +// Sin los paréntesis, "List.map" se pasará como argumento a List.sum. +let sumaDeCuadradosHasta100 = + List.sum ( List.map cuadrado [1..100] ) + +// Puedes redirigir la salida de una función a otra con "|>" +// Redirigir datos es muy común en F#, como con los pipes de UNIX. + +// Aquí está la misma función sumOfSquares escrita usando pipes +let sumaDeCuadradosHasta100piped = + [1..100] |> List.map cuadrado |> List.sum // "cuadrado" se declara antes + +// Puede definir lambdas (funciones anónimas) gracias a la palabra clave "fun" +let sumaDeCuadradosHasta100ConFuncion = + [1..100] |> List.map (fun x -> x*x) |> List.sum + +// En F#, no hay palabra clave "return". Una función siempre regresa +// el valor de la última expresión utilizada. + +// ------ Coincidencia de patrones ------ +// Match..with .. es una sobrecarga de la condición de case/ switch. +let coincidenciaDePatronSimple = + let x = "a" + match x with + | "a" -> printfn "x es a" + | "b" -> printfn "x es b" + | _ -> printfn "x es algo mas" // guion bajo corresponde con todos los demás + +// F# no permite valores nulos por defecto - debe usar el tipado de Option +// y luego coincide con el patrón. +// Some(..) y None son aproximadamente análogos a los envoltorios Nullable +let valorValido = Some(99) +let valorInvalido = None + +// En este ejemplo, match..with encuentra una coincidencia con "Some" y "None", +// y muestra el valor de "Some" al mismo tiempo. +let coincidenciaDePatronDeOpciones entrada = + match entrada with + | Some i -> printfn "la entrada es un int=%d" i + | None -> printfn "entrada faltante" + +coincidenciaDePatronDeOpciones validValue +coincidenciaDePatronDeOpciones invalidValue + +// ------ Viendo ------ +// Las funciones printf/printfn son similares a las funciones +// Console.Write/WriteLine de C#. +printfn "Imprimiendo un int %i, a float %f, a bool %b" 1 2.0 true +printfn "Un string %s, y algo generico %A" "hola" [1;2;3;4] + +// También hay funciones printf/sprintfn para formatear datos +// en cadena. Es similar al String.Format de C#. + +// ================================================ +// Mas sobre funciones +// ================================================ + +// F# es un verdadero lenguaje funcional - las funciones son +// entidades de primer nivel y se pueden combinar fácilmente +// para crear construcciones poderosas + +// Los módulos se utilizan para agrupar funciones juntas. +// Se requiere sangría para cada módulo anidado. +module EjemploDeFuncion = + + // define una función de suma simple + let agregar x y = x + y + + // uso básico de una función + let a = agregar 1 2 + printfn "1+2 = %i" a + + // aplicación parcial para "hornear en" los parámetros (?) + let agregar42 = agregar 42 + let b = agregar42 1 + printfn "42+1 = %i" b + + // composición para combinar funciones + let agregar1 = agregar 1 + let agregar2 = agregar 2 + let agregar3 = agregar1 >> agregar2 + let c = agregar3 7 + printfn "3+7 = %i" c + + // funciones de primer nivel + [1..10] |> List.map agregar3 |> printfn "la nueva lista es %A" + + // listas de funciones y más + let agregar6 = [agregar1; agregar2; agregar3] |> List.reduce (>>) + let d = agregar6 7 + printfn "1+2+3+7 = %i" d + +// ================================================ +// Lista de colecciones +// ================================================ + +// Il y a trois types de collection ordonnée : +// * Les listes sont les collections immutables les plus basiques +// * Les tableaux sont mutables et plus efficients +// * Les séquences sont lazy et infinies (e.g. un enumerator) +// +// Des autres collections incluent des maps immutables et des sets +// plus toutes les collections de .NET + +module EjemplosDeLista = + + // las listas utilizan corchetes + let lista1 = ["a";"b"] + let lista2 = "c" :: lista1 // :: para una adición al principio + let lista3 = lista1 @ lista2 // @ para la concatenación + + // Lista de comprensión (alias generadores) + let cuadrados = [for i in 1..10 do yield i*i] + + // Generador de números primos + let rec tamiz = function + | (p::xs) -> p :: tamiz [ for x in xs do if x % p > 0 then yield x ] + | [] -> [] + let primos = tamiz [2..50] + printfn "%A" primos + + // coincidencia de patrones para listas + let listaDeCoincidencias unaLista = + match unaLista with + | [] -> printfn "la lista esta vacia" + | [primero] -> printfn "la lista tiene un elemento %A " primero + | [primero; segundo] -> printfn "la lista es %A y %A" primero segundo + | _ -> printfn "la lista tiene mas de dos elementos" + + listaDeCoincidencias [1;2;3;4] + listaDeCoincidencias [1;2] + listaDeCoincidencias [1] + listaDeCoincidencias [] + + // Récursion en utilisant les listes + let rec suma unaLista = + match unaLista with + | [] -> 0 + | x::xs -> x + suma xs + suma [1..10] + + // ----------------------------------------- + // Funciones de la biblioteca estándar + // ----------------------------------------- + + // mapeo + let agregar3 x = x + 3 + [1..10] |> List.map agregar3 + + // filtrado + let par x = x % 2 = 0 + [1..10] |> List.filter par + + // mucho más - consulte la documentación + +module EjemploDeArreglo = + + // los arreglos usan corchetes con barras. + let arreglo1 = [| "a";"b" |] + let primero = arreglo1.[0] // se accede al índice usando un punto + + // la coincidencia de patrones de los arreglos es la misma que la de las listas + let coincidenciaDeArreglos una Lista = + match unaLista with + | [| |] -> printfn "la matriz esta vacia" + | [| primero |] -> printfn "el arreglo tiene un elemento %A " primero + | [| primero; second |] -> printfn "el arreglo es %A y %A" primero segundo + | _ -> printfn "el arreglo tiene mas de dos elementos" + + coincidenciaDeArreglos [| 1;2;3;4 |] + + // La biblioteca estándar funciona como listas + [| 1..10 |] + |> Array.map (fun i -> i+3) + |> Array.filter (fun i -> i%2 = 0) + |> Array.iter (printfn "el valor es %i. ") + +module EjemploDeSecuencia = + + // Las secuencias usan llaves + let secuencia1 = seq { yield "a"; yield "b" } + + // Las secuencias pueden usar yield y +    // puede contener subsecuencias + let extranio = seq { + // "yield" agrega un elemento + yield 1; yield 2; + + // "yield!" agrega una subsecuencia completa + yield! [5..10] + yield! seq { + for i in 1..10 do + if i%2 = 0 then yield i }} + // prueba + extranio |> Seq.toList + + // Las secuencias se pueden crear usando "unfold" +    // Esta es la secuencia de fibonacci + let fib = Seq.unfold (fun (fst,snd) -> + Some(fst + snd, (snd, fst + snd))) (0,1) + + // prueba + let fib10 = fib |> Seq.take 10 |> Seq.toList + printf "Los primeros 10 fib son %A" fib10 + +// ================================================ +// Tipos de datos +// ================================================ + +module EejemploDeTipoDeDatos = + + // Todos los datos son inmutables por defecto + +     // las tuplas son tipos anónimos simples y rápidos +     // - Usamos una coma para crear una tupla + let dosTuplas = 1,2 + let tresTuplas = "a",2,true + + // Combinación de patrones para desempaquetar + let x,y = dosTuplas // asignado x=1 y=2 + + // ------------------------------------ + // Los tipos de registro tienen campos con nombre + // ------------------------------------ + + // Usamos "type" con llaves para definir un tipo de registro + type Persona = {Nombre:string; Apellido:string} + + // Usamos "let" con llaves para crear un registro + let persona1 = {Nombre="John"; Apellido="Doe"} + + // Combinación de patrones para desempaquetar + let {Nombre=nombre} = persona1 // asignado nombre="john" + + // ------------------------------------ + // Los tipos de unión (o variantes) tienen un conjunto de elección +     // Solo un caso puede ser válido a la vez. + // ------------------------------------ + + // Usamos "type" con barra/pipe para definir una unión estándar + type Temp = + | GradosC of float + | GradosF of float + + // Una de estas opciones se usa para crear una + let temp1 = GradosF 98.6 + let temp2 = GradosC 37.0 + + // Coincidencia de patrón en todos los casos para desempaquetar (?) + let imprimirTemp = function + | GradosC t -> printfn "%f gradC" t + | GradosF t -> printfn "%f gradF" t + + imprimirTemp temp1 + imprimirTemp temp2 + + // ------------------------------------ + // Tipos recursivos + // ------------------------------------ + + // Los tipos se pueden combinar recursivamente de formas complejas +    // sin tener que crear subclases + type Empleado = + | Trabajador of Persona + | Gerente of Empleado lista + + let jdoe = {Nombre="John";Apellido="Doe"} + let trabajador = Trabajador jdoe + + // ------------------------------------ + // Modelado con tipados (?) + // ------------------------------------ + + // Los tipos de unión son excelentes para modelar el estado sin usar banderas (?) + type DireccionDeCorreo = + | DireccionDeCorreoValido of string + | DireccionDeCorreoInvalido of string + + let intentarEnviarCorreo correoElectronico = + match correoElectronico with // uso de patrones de coincidencia + | DireccionDeCorreoValido direccion -> () // enviar + | DireccionDeCorreoInvalido direccion -> () // no enviar + + // Combinar juntos, los tipos de unión y tipos de registro +     // ofrece una base excelente para el diseño impulsado por el dominio. +     // Puedes crear cientos de pequeños tipos que reflejarán fielmente +     // el dominio. + + type ArticuloDelCarrito = { CodigoDelProducto: string; Cantidad: int } + type Pago = Pago of float + type DatosActivosDelCarrito = { ArticulosSinPagar: ArticuloDelCarrito lista } + type DatosPagadosDelCarrito = { ArticulosPagados: ArticuloDelCarrito lista; Pago: Pago} + + type CarritoDeCompras = + | CarritoVacio // sin datos + | CarritoActivo of DatosActivosDelCarrito + | CarritoPagado of DatosPagadosDelCarrito + + // ------------------------------------ + // Comportamiento nativo de los tipos + // ------------------------------------ + + // Los tipos nativos tienen el comportamiento más útil "listo para usar", sin ningún código para agregar. +     // * Inmutabilidad +     // * Bonita depuración de impresión +     // * Igualdad y comparación +     // * Serialización + +     // La impresión bonita se usa con %A + printfn "dosTuplas=%A,\nPersona=%A,\nTemp=%A,\nEmpleado=%A" + dosTuplas persona1 temp1 trabajador + + // La igualdad y la comparación son innatas +     // Aquí hay un ejemplo con tarjetas. + type JuegoDeCartas = Trebol | Diamante | Espada | Corazon + type Rango = Dos | Tres | Cuatro | Cinco | Seis | Siete | Ocho + | Nueve | Diez | Jack | Reina | Rey | As + + let mano = [ Trebol,As; Corazon,Tres; Corazon,As; + Espada,Jack; Diamante,Dos; Diamante,As ] + + // orden + List.sort mano |> printfn "la mano ordenada es (de menos a mayor) %A" + List.max mano |> printfn "la carta más alta es%A" + List.min mano |> printfn "la carta más baja es %A" + +// ================================================ +// Patrones activos +// ================================================ + +module EjemplosDePatronesActivos = + + // F# tiene un tipo particular de coincidencia de patrón llamado "patrones activos" +    // donde el patrón puede ser analizado o detectado dinámicamente. + +    // "clips de banana" es la sintaxis de los patrones activos + +    // por ejemplo, definimos un patrón "activo" para que coincida con los tipos de "caracteres" ... + let (|Digito|Latra|EspacioEnBlanco|Otros|) ch = + if System.Char.IsDigit(ch) then Digito + else if System.Char.IsLetter(ch) then Letra + else if System.Char.IsWhiteSpace(ch) then EspacioEnBlanco + else Otros + + // ... y luego lo usamos para hacer que la lógica de análisis sea más clara + let ImprimirCaracter ch = + match ch with + | Digito -> printfn "%c es un Digito" ch + | Letra -> printfn "%c es una Letra" ch + | Whitespace -> printfn "%c es un Espacio en blanco" ch + | _ -> printfn "%c es algo mas" ch + + // ver una lista + ['a';'b';'1';' ';'-';'c'] |> List.iter ImprimirCaracter + + // ----------------------------------------- + // FizzBuzz usando patrones activos + // ----------------------------------------- + + // Puede crear un patrón de coincidencia parcial también +    // Solo usamos un guión bajo en la definición y devolvemos Some si coincide. + let (|MultDe3|_|) i = if i % 3 = 0 then Some MultDe3 else None + let (|MultDe5|_|) i = if i % 5 = 0 then Some MultDe5 else None + + // la función principal + let fizzBuzz i = + match i with + | MultDe3 & MultDe5 -> printf "FizzBuzz, " + | MultDe3 -> printf "Fizz, " + | MultDe5 -> printf "Buzz, " + | _ -> printf "%i, " i + + // prueba + [1..20] |> List.iter fizzBuzz + +// ================================================ +// concisión +// ================================================ + +module EjemploDeAlgoritmo = + + // F# tiene una alta relación señal / ruido, lo que permite leer el código +    // casi como un algoritmo real + + // ------ Ejemplo: definir una función sumaDeCuadrados ------ + let sumaDeCuadrados n = + [1..n] // 1) Tome todos los números del 1 al n + |> List.map cuadrado // 2) Elevar cada uno de ellos al cuadrado + |> List.sum // 3) Realiza su suma + + // prueba + sumaDeCuadrados 100 |> printfn "Suma de cuadrados = %A" + + // ------ Ejemplo: definir una función de ordenación ------ + let rec ordenar lista = + match lista with + // Si la lista está vacía + | [] -> + [] // devolvemos una lista vacía +       // si la lista no está vacía + | primerElemento::otrosElementos -> // tomamos el primer elemento + let elementosMasPequenios = // extraemos los elementos más pequeños + otrosElementos // tomamos el resto + |> List.filter (fun e -> e < primerElemento) + |> ordenar // y los ordenamos + let elementosMasGrandes = // extraemos el mas grande + otrosElementos // de los que permanecen + |> List.filter (fun e -> e >= primerElemento) + |> ordenar // y los ordenamos + // Combinamos las 3 piezas en una nueva lista que devolvemos + List.concat [elementosMasPequenios; [primerElemento]; elementosMasGrandes] + + // prueba + ordenar [1;5;23;18;9;1;3] |> printfn "Ordenado = %A" + +// ================================================ +// Código asíncrono +// ================================================ + +module AsyncExample = + + // F# incluye características para ayudar con el código asíncrono +    // sin conocer la "pirámide del destino" +    // +    // El siguiente ejemplo descarga una secuencia de página web en paralelo. + + open System.Net + open System + open System.IO + open Microsoft.FSharp.Control.CommonExtensions + + // Recuperar el contenido de una URL de forma asincrónica + let extraerUrlAsync url = + async { // La palabra clave "async" y llaves + // crear un objeto "asincrónico" + let solicitud = WebRequest.Create(Uri(url)) + use! respuesta = solicitud.AsyncGetResponse() + // use! es una tarea asincrónica + use flujoDeDatos = resp.GetResponseStream() + // "use" dispara automáticamente la funcion close() + // en los recursos al final de las llaves + use lector = new IO.StreamReader(flujoDeDatos) + let html = lector.ReadToEnd() + printfn "terminó la descarga %s" url + } + + // una lista de sitios para informar + let sitios = ["http://www.bing.com"; + "http://www.google.com"; + "http://www.microsoft.com"; + "http://www.amazon.com"; + "http://www.yahoo.com"] + + // ¡Aqui vamos! + sitios + |> List.map extraerUrlAsync // crear una lista de tareas asíncrona + |> Async.Parallel // decirle a las tareas que se desarrollan en paralelo + |> Async.RunSynchronously // ¡Empieza! + +// ================================================ +// Compatibilidad .NET +// ================================================ + +module EjemploCompatibilidadNet = + + // F# puede hacer casi cualquier cosa que C# pueda hacer, y se ajusta +    // perfectamente con bibliotecas .NET o Mono. + +  // ------- Trabaja con las funciones de las bibliotecas existentes ------- + + let (i1success,i1) = System.Int32.TryParse("123"); + if i1success then printfn "convertido como %i" i1 else printfn "conversion fallida" + + // ------- Implementar interfaces sobre la marcha! ------- + + // Crea un nuevo objeto que implemente IDisposable + let crearRecurso name = + { new System.IDisposable + with member this.Dispose() = printfn "%s creado" name } + + let utilizarYDisponerDeRecursos = + use r1 = crearRecurso "primer recurso" + printfn "usando primer recurso" + for i in [1..3] do + let nombreDelRecurso = sprintf "\tinner resource %d" i + use temp = crearRecurso nombreDelRecurso + printfn "\thacer algo con %s" nombreDelRecurso + use r2 = crearRecurso "segundo recurso" + printfn "usando segundo recurso" + printfn "hecho." + + // ------- Código orientado a objetos ------- + + // F# es también un verdadero lenguaje OO. +    // Admite clases, herencia, métodos virtuales, etc. + + // interfaz de tipo genérico + type IEnumerator<'a> = + abstract member Actual : 'a + abstract MoverSiguiente : unit -> bool + + // Clase base abstracta con métodos virtuales + [] + type Figura() = + // propiedades de solo lectura + abstract member Ancho : int with get + abstract member Alto : int with get + // método no virtual + member this.AreaDelimitadora = this.Alto * this.Ancho + // método virtual con implementación de la clase base + abstract member Imprimir : unit -> unit + default this.Imprimir () = printfn "Soy una Figura" + + // clase concreta que hereda de su clase base y sobrecarga + type Rectangulo(x:int, y:int) = + inherit Figura() + override this.Ancho = x + override this.Alto = y + override this.Imprimir () = printfn "Soy un Rectangulo" + + // prueba + let r = Rectangulo(2,3) + printfn "La anchura es %i" r.Ancho + printfn "El area es %i" r.AreaDelimitadora + r.Imprimir() + + // ------- extensión de método ------- + + // Al igual que en C#, F# puede extender las clases existentes con extensiones de método. + type System.String with + member this.EmpiezaConA = this.EmpiezaCon "A" + + // prueba + let s = "Alice" + printfn "'%s' empieza con una 'A' = %A" s s.EmpiezaConA + + // ------- eventos ------- + + type MiBoton() = + let eventoClick = new Event<_>() + + [] + member this.AlHacerClick = eventoClick.Publish + + member this.PruebaEvento(arg) = + eventoClick.Trigger(this, arg) + + // prueba + let miBoton = new MiBoton() + miBoton.AlHacerClick.Add(fun (sender, arg) -> + printfn "Haga clic en el evento con arg=%O" arg) + + miBoton.PruebaEvento("Hola Mundo!") +``` + +## Más información + +Para más demostraciones de F#, visite el sitio [Try F#](http://www.tryfsharp.org/Learn), o sigue la serie [why use F#](http://fsharpforfunandprofit.com/why-use-fsharp/). + +Aprenda más sobre F# en [fsharp.org](http://fsharp.org/). -- cgit v1.2.3 From abaf836249bf8ab7f2e6d13fa96baca0c7e4e8a1 Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Wed, 19 Sep 2018 13:07:32 -0700 Subject: add part 1 Variables and pattern matching --- es-es/erlang-es.html.markdown | 93 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 es-es/erlang-es.html.markdown diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown new file mode 100644 index 00000000..82a63b23 --- /dev/null +++ b/es-es/erlang-es.html.markdown @@ -0,0 +1,93 @@ +--- +language: Erlang +lang: es-es +contributors: + ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Ernesto Pelayo", "http://github.com/ErnestoPelayo"] +filename: learnerlang.erl +--- +# Erlang +% Signo de porcentaje inicia un comentario de una línea. + +%% Se usarán dos por ciento de caracteres para comentar funciones. + +%%% Se usarán tres por ciento de caracteres para comentar los módulos. + +### Utilizamos tres tipos de puntuación en Erlang. + ++ **Comas (`,`)** argumentos separados en llamadas a funciones, constructores de +datos y patrones. + ++ **Periodos (`.`)** (seguido de espacios en blanco) separa funciones completas y +expresiones en el shell. + ++ **Semicolons (`;`)** cláusulas separadas. Encontramos cláusulas en varios contextos: de definiciones de funciones y en **`case`**,**` if`**, **`try..catch`**, y **` receive`** de expresiones. + + ## 1.-Variables y coincidencia de patrones. + + +- En Erlang, las nuevas variables están vinculadas con una instrucción **`=`**. +>**Num = 42.** + +- Todos los nombres de variables deben comenzar con una letra mayúscula. + +- Erlang tiene variables de asignación única; si intentas asignar un diferente de valor a la variable **`Num`**, obtendrá un error. +Num = 43. **error de excepción**: no coincide con el valor del lado derecho 43 + +- En la mayoría de los idiomas, **`=`** denota una declaración de asignación. En Erlang, sin embargo,**`=`** denota una operación de coincidencia de patrones. + +- Cuando se usa una variable vacía en el del lado izquierdo del operador `=` to está vinculado (asignado), pero cuando está atado variable se usa en el lado izquierdo, se observa el siguiente comportamiento. +>**`Lhs = Rhs`** realmente significa esto: evaluar el lado derecho (**` Rhs`**), y luego coincide con el resultado contra el patrón en el lado izquierdo (**`Lhs`**). +>**Num = 7 * 6.** + +- Número de punto flotante. +Pi = 3.14159. + +- Los átomos se usan para representar diferentes valores constantes no numéricos. + +- Átomos comienza con letras minúsculas, seguido de una secuencia de caracteres + +- alfanuméricos de caracteres o el signo de subrayado (**`_`**) o en (**` @ `**). +>**Hola = hola.** + **OtherNode = ejemplo @ nodo.** + +- Los átomos con valores no alfanuméricos se pueden escribir al encerrar los átomos con apóstrofes. +>**AtomWithSpace = 'algún átomo con espacio'.** + ++ Tuples son similares a las estructuras en C. +>**Point = {point, 10, 45}.** + +- Si queremos extraer algunos valores de una tupla, usamos el patrón de coincidencia + operador **`=`**. +> **{punto, X, Y} = Punto. % X = 10, Y = 45** + +- Podemos usar **`_`** como marcador de posición para variables que no nos interesan. + +- El símbolo **`_`** se llama una variable anónima. A diferencia de las variables regulares,varias apariciones de `_` en el mismo patrón no tienen que vincularse a mismo valor. +>**Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}.** +**{_, {_, {_, who }, _}, _} = Persona. % Who = joe** + ++ Creamos una lista al encerrar los elementos de la lista entre corchetes y separándolos con comas. + ++ Los elementos individuales de una lista pueden ser de cualquier tipo. + +- El primer elemento de una lista es el encabezado de la lista. Si te imaginas eliminar del encabezado de la lista, lo que queda se llama cola de la lista. +>**ThingsToBuy = [{manzanas, 10}, {peras, 6}, {leche, 3}].** + +- Si `T` es una lista, entonces **` [H | T] `** también es una lista, con la cabeza **` H`** y la cola **`T`**. + ++ La barra vertical (**`|`**) separa el encabezado de una lista de su cola. + **`[]`** es la lista vacía. + ++ Podemos extraer elementos de una lista con una operación de coincidencia de + patrones. Si nosotros tiene una lista no vacía **`L`**, luego la expresión **` [X | Y] = L`**, donde **`X`** y **` Y`** son variables independientes, extraerán el encabezado de la lista en **`X`** y la cola de la lista en **`Y`**. +>**[FirstThing | OtherThingsToBuy] = ThingsToBuy.** +**FirstThing = {manzanas, 10}** +**OtherThingsToBuy = [{peras, 6}, {leche, 3}]** + ++ No hay cadenas en Erlang. Las cadenas son realmente solo listas de enteros. + ++ Las cadenas están entre comillas dobles (**`" `**). +>**Nombre = "Hola". +[72, 101, 108, 108, 111] = "Hola".** -- cgit v1.2.3 From b765369b258bb92c2caed28d0eae82e923f2a386 Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Wed, 19 Sep 2018 13:09:24 -0700 Subject: added part 2 Sequential programming. --- es-es/erlang-es.html.markdown | 114 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown index 82a63b23..7ca9c9b0 100644 --- a/es-es/erlang-es.html.markdown +++ b/es-es/erlang-es.html.markdown @@ -91,3 +91,117 @@ Pi = 3.14159. + Las cadenas están entre comillas dobles (**`" `**). >**Nombre = "Hola". [72, 101, 108, 108, 111] = "Hola".** + +## 2. Programación secuencial. + + +- Los módulos son la unidad básica de código en Erlang. Todas las funciones que escribimos son almacenado en módulos. + +- Los módulos se almacenan en archivos con extensiones **`.erl`**. +- Los módulos deben compilarse antes de poder ejecutar el código. Un módulo compilado tiene el extensión **`.beam`**. +>**-módulo (geometría). +-export ([area / 1]). de la lista de funciones exportadas desde el módulo.** + ++ La función **`área`** consta de dos cláusulas. Las cláusulas están separadas por un punto y coma, y ​​la cláusula final termina con punto-espacio en blanco. Cada cláusula tiene una cabeza y un cuerpo; la cabeza consiste en un nombre de función seguido de un patrón (entre paréntesis), y el cuerpo consiste en una secuencia de expresiones, que se evalúan si el patrón en la cabeza es exitoso coincide con los argumentos de llamada. Los patrones se combinan en el orden aparecen en la definición de la función. +>**área ({rectángulo, ancho, Ht}) -> ancho * Ht; +área ({círculo, R}) -> 3.14159 * R * R** . + + ### Compila el código en el archivo geometry.erl. +c (geometría). {ok, geometría} + ++ Necesitamos incluir el nombre del módulo junto con el nombre de la función para identifica exactamente qué función queremos llamar. +>**geometría: área ({rectángulo, 10, 5}). % 50** +**geometría: área ({círculo, 1.4}). % 6.15752** + ++ En Erlang, dos funciones con el mismo nombre y arity diferente (número de argumentos) en el mismo módulo representan funciones completamente diferentes. +>-**module (lib_misc)**. +-**export ([sum / 1])**. + +- función de exportación **`suma`** de arity 1 acepta un argumento: +>**lista de enteros. +suma (L) -> suma (L, 0). +suma ([], N) -> N; +suma ([H | T], N) -> suma (T, H + N).** ++ Funs son funciones **"anónimas"**. Se llaman así porque tienen sin nombre. Sin embargo, pueden asignarse a variables. +Doble = diversión (X) -> 2 * X final. **`Doble`** apunta a una función anónima con el controlador: **#Fun +Doble (2). % 4** + +- Functions acepta funs como sus argumentos y puede devolver funs. +>**Mult = diversión (Times) -> (fun (X) -> X * Times end) end. +Triple = Mult (3). +Triple (5). % 15** + +- Las listas de comprensión son expresiones que crean listas sin tener que usar + funs, mapas o filtros. + - La notación **`[F (X) || X <- L] `** significa" la lista de **`F (X)`** donde se toma **`X`**% de la lista **`L`."** +>**L = [1,2,3,4,5]. +[2 * X || X <- L]. % [2,4,6,8,10]** + +- Una lista de comprensión puede tener generadores y filtros, que seleccionan un subconjunto de los valores generados +>**EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4]** + +- Los protectores son construcciones que podemos usar para aumentar el poder del patrón coincidencia. Usando guardias, podemos realizar pruebas simples y comparaciones en el de variables en un patrón. +Puede usar guardias en la cabeza de las definiciones de funciones donde están introducido por la palabra clave **`when`**, o puede usarlos en cualquier lugar del lenguaje donde se permite una expresión. +>**max (X, Y) cuando X> Y -> X; +max (X, Y) -> Y.** + +- Un guardia es una serie de expresiones de guardia, separadas por comas (**`,`**). +- La guardia **`GuardExpr1, GuardExpr2, ..., GuardExprN`** es verdadera si todos los guardias expresiones **`GuardExpr1`,` GuardExpr2`, ..., `GuardExprN`** evalúan **`true`**. +>**is_cat (A) cuando is_atom (A), A =: = cat -> true; +is_cat (A) -> false. +is_dog (A) cuando is_atom (A), A =: = dog -> true; +is_dog (A) -> false.** + +No nos detendremos en el operador **`=: =`** aquí; Solo tenga en cuenta que está acostumbrado a comprueba si dos expresiones de Erlang tienen el mismo valor * y * del mismo tipo. Contrasta este comportamiento con el del operador **`==`**: + +>**1 + 2 =: = 3.% true +1 + 2 =: = 3.0. % false +1 + 2 == 3.0. % true** + + Una secuencia de guardia es una guardia individual o una serie de guardias, separadas por punto y coma (**`;`**). La secuencia de guardia **`G1; G2; ...; Gn`** es verdadero si en menos uno de los guardias **`G1`,` G2`, ..., `Gn`** se evalúa como **` true`**. +>**is_pet (A) cuando is_atom (A), (A =: = dog); (A =: = cat) -> true; +is_pet (A) -> false.** + +- **Advertencia**: no todas las expresiones de Erlang válidas se pueden usar como expresiones de guarda; en particular, nuestras funciones **`is_cat`** y **`is_dog`** no se pueden usar dentro del secuencia de protección en la definición de **`is_pet`**. Para una descripción de expresiones permitidas en secuencias de guarda, consulte la sección específica en el manual de referencia de Erlang: +### http://erlang.org/doc/reference_manual/expressions.html#guards + +- Los registros proporcionan un método para asociar un nombre con un elemento particular en un de tupla De las definiciones de registros se pueden incluir en los archivos de código fuente de Erlang o poner en archivos con la extensión **`.hrl`**, que luego están incluidos en el código fuente de Erlang de archivos. + +>**-record (todo, { + status = recordatorio,% valor predeterminado + quien = joe, + texto +}).** + +- Tenemos que leer las definiciones de registro en el shell antes de que podamos definir un + de registro. Usamos la función shell **`rr`** (abreviatura de los registros de lectura) para hacer esto. + +>**rr ("records.hrl").** % [que hacer] + +- **Creando y actualizando registros:** +>**X = #todo {}. +% #todo {status = recordatorio, who = joe, text = undefined} +X1 = #todo {estado = urgente, texto = "Corregir errata en el libro"}. +% #todo {status = urgent, who = joe, text = "Corregir errata en el libro"} +X2 = X1 # todo {estado = hecho}. +% #todo {status = done, who = joe, text = "Corregir errata en el libro"} +expresiones `case`**. + +**`filter`** devuelve una lista de todos los elementos **` X`** en una lista **`L`** para la cual **` P (X) `** es true. +>**filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4]** + +expresiones **`if`**. +>**max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil + end.** + +**Advertencia:** al menos uno de los guardias en la expresión **`if`** debe evaluar a **`true`**; de lo contrario, se generará una excepción. -- cgit v1.2.3 From d875cbabe402c3355d5bd49801adcc4f99edf9a8 Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Wed, 19 Sep 2018 13:10:30 -0700 Subject: added part 3 Exceptions --- es-es/erlang-es.html.markdown | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown index 7ca9c9b0..11c83562 100644 --- a/es-es/erlang-es.html.markdown +++ b/es-es/erlang-es.html.markdown @@ -205,3 +205,26 @@ expresiones **`if`**. end.** **Advertencia:** al menos uno de los guardias en la expresión **`if`** debe evaluar a **`true`**; de lo contrario, se generará una excepción. + +## 3. Excepciones. + + +- El sistema genera excepciones cuando se encuentran errores internos o explícitamente en el código llamando **`throw (Exception)`**, **`exit (Exception)`**, o **`erlang: error (Exception)`**. +>**generate_exception (1) -> a; +generate_exception (2) -> throw (a); +generate_exception (3) -> exit (a); +generate_exception (4) -> {'EXIT', a}; +generate_exception (5) -> erlang: error (a).** + +- Erlang tiene dos métodos para atrapar una excepción. Una es encerrar la llamada a de la función que genera la excepción dentro de una expresión **`try ... catch`**. +>**receptor (N) -> + prueba generar_excepción (N) de + Val -> {N, normal, Val} + captura + throw: X -> {N, atrapado, arrojado, X}; + exit: X -> {N, atrapado, salido, X}; + error: X -> {N, atrapado, error, X} + end.** + +- El otro es encerrar la llamada en una expresión **`catch`**. Cuando atrapas un de excepción, se convierte en una tupla que describe el error. +>**catcher (N) -> catch generate_exception (N).** -- cgit v1.2.3 From 368c855ed6f154b5f37edf1d1d098440c189a534 Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Wed, 19 Sep 2018 13:12:27 -0700 Subject: added part 4 Concurrency --- es-es/erlang-es.html.markdown | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown index 11c83562..e375cc04 100644 --- a/es-es/erlang-es.html.markdown +++ b/es-es/erlang-es.html.markdown @@ -228,3 +228,36 @@ generate_exception (5) -> erlang: error (a).** - El otro es encerrar la llamada en una expresión **`catch`**. Cuando atrapas un de excepción, se convierte en una tupla que describe el error. >**catcher (N) -> catch generate_exception (N).** + +## 4. Concurrencia + +- Erlang se basa en el modelo de actor para concurrencia. Todo lo que necesitamos para escribir de programas simultáneos en Erlang son tres primitivos: procesos de desove, de envío de mensajes y recepción de mensajes. + +- Para comenzar un nuevo proceso, usamos la función **`spawn`**, que toma una función como argumento. + +>**F = diversión () -> 2 + 2 final. % #Fun +spawn (F). % <0.44.0>** + +- **`spawn`** devuelve un pid (identificador de proceso); puedes usar este pid para enviar de mensajes al proceso. Para pasar mensajes, usamos el operador **`!`**. + +- Para que todo esto sea útil, debemos poder recibir mensajes. Esto es logrado con el mecanismo **`receive`**: + +>**-module (calcular Geometría). +-compile (export_all). +calculateArea () -> + recibir + {rectángulo, W, H} -> + W * H; + {circle, R} -> + 3.14 * R * R; + _ -> + io: format ("Solo podemos calcular el área de rectángulos o círculos") + end.** + +- Compile el módulo y cree un proceso que evalúe **`calculateArea`** en cáscara. +>**c (calcular Geometría). +CalculateArea = spawn (calcular Geometría, calcular Área, []). +CalculateArea! {círculo, 2}. % 12.56000000000000049738** + +- El shell también es un proceso; puedes usar **`self`** para obtener el pid actual. +**self(). % <0.41.0>** -- cgit v1.2.3 From 03437f5b0de73532c2933a12419a6020113bbddb Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Wed, 19 Sep 2018 13:14:02 -0700 Subject: added part 5 Testing with EUnit --- es-es/erlang-es.html.markdown | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown index e375cc04..820ee1da 100644 --- a/es-es/erlang-es.html.markdown +++ b/es-es/erlang-es.html.markdown @@ -261,3 +261,32 @@ CalculateArea! {círculo, 2}. % 12.56000000000000049738** - El shell también es un proceso; puedes usar **`self`** para obtener el pid actual. **self(). % <0.41.0>** + +## 5. Prueba con EUnit + +- Las pruebas unitarias se pueden escribir utilizando los generadores de prueba de EUnits y afirmar macros +>**-módulo (fib). +-export ([fib / 1]). +-include_lib ("eunit / include / eunit.hrl").** + +>**fib (0) -> 1; +fib (1) -> 1; +fib (N) when N> 1 -> fib (N-1) + fib (N-2).** + +>**fib_test_ () -> + [? _assert (fib (0) =: = 1), + ? _assert (fib (1) =: = 1), + ? _assert (fib (2) =: = 2), + ? _assert (fib (3) =: = 3), + ? _assert (fib (4) =: = 5), + ? _assert (fib (5) =: = 8), + ? _assertException (error, function_clause, fib (-1)), + ? _assert (fib (31) =: = 2178309) + ]** + +- EUnit exportará automáticamente a una función de prueba () para permitir la ejecución de las pruebas en el shell Erlang +fib: test () + +- La popular barra de herramientas de construcción de Erlang también es compatible con EUnit +**`` ` de la unidad de barras de refuerzo + ``** -- cgit v1.2.3 From cd6abe0bfcf6f34cec65b12324cebee666e0a19a Mon Sep 17 00:00:00 2001 From: Anatolij Date: Thu, 20 Sep 2018 09:19:39 +0200 Subject: The source code can be run by Rust Playground The source code can be run by Rust Playground without warnings --- rust.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/rust.html.markdown b/rust.html.markdown index 6b75fa87..1c0e324c 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -41,6 +41,7 @@ Rust not only fast, but also easy and efficient to code in. // 1. Basics // /////////////// +#[allow(dead_code)] // Functions // `i32` is the type for 32-bit signed integers fn add2(x: i32, y: i32) -> i32 { @@ -48,6 +49,9 @@ fn add2(x: i32, y: i32) -> i32 { x + y } +#[allow(unused_variables)] +#[allow(unused_assignments)] +#[allow(dead_code)] // Main function fn main() { // Numbers // @@ -256,11 +260,13 @@ fn main() { // `while` loop while 1 == 1 { println!("The universe is operating normally."); + break; } // Infinite loop loop { println!("Hello!"); + break; } ///////////////////////////////// -- cgit v1.2.3 From 1a9378ad68a048f5de37a934154533475cd54035 Mon Sep 17 00:00:00 2001 From: Anatolij Date: Thu, 20 Sep 2018 09:29:38 +0200 Subject: Create traslation rust.html.markdown to Russian Implement translation to Russian --- ru-ru/rust-ru.html.markdown | 311 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 311 insertions(+) create mode 100644 ru-ru/rust-ru.html.markdown diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown new file mode 100644 index 00000000..ac221ab6 --- /dev/null +++ b/ru-ru/rust-ru.html.markdown @@ -0,0 +1,311 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +filename: learnrust.rs +--- + +Rust сочетает в себе низкоуровневый контроль над производительностью с удобством высокого уровня и предоставляет гарантии +безопасности. +Он достигает этих целей, не требуя сборщика мусора или времени выполнения, что позволяет использовать библиотеки Rust как замену +для C-библиотек. + +Первый выпуск Rust, 0.1, произошел в январе 2012 года, и в течение 3 лет развитие продвигалось настолько быстро, что до +недавнего времени использование стабильных выпусков было затруднено, и вместо этого общий совет заключался в том, чтобы +использовать последние сборки. + +15 мая 2015 года был выпущен Rust 1.0 с полной гарантией обратной совместимости. Усовершенствования времени компиляции и +других аспектов компилятора в настоящее время доступны в ночных сборках. Rust приняла модель выпуска на поезде с регулярными выпусками каждые шесть недель. Rust 1.1 beta был доступен одновременно с выпуском Rust 1.0. + +Хотя Rust является языком относительно низкого уровня, Rust имеет некоторые функциональные концепции, которые обычно +встречаются на языках более высокого уровня. Это делает Rust не только быстрым, но и простым и эффективным для ввода кода. + + +```rust +// Это однострочный комментарии +// + +/// Так выглядит комментарий для документации +/// # Examples +/// +/// +/// let seven = 7 +/// + +/////////////// +// 1. Основы // +/////////////// + +// Функции +// `i32` это целочисленный знаковый тип 32-bit +#[allow(dead_code)] +fn add2(x: i32, y: i32) -> i32 { + // метод возвращает сумму x и y + x + y +} + +// Главная функция программы +#[allow(unused_variables)] +#[allow(unused_assignments)] +#[allow(dead_code)] +fn main() { + // Числа // + + // неизменяемая переменная + let x: i32 = 1; + + // Суффиксы целое/дробное + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Автоматическое выявление типа данных + // В большинстве случаев компилятор Rust может вычислить + // тип переменной, поэтому + // вам не нужно писать явные аннотации типа. + + let implicit_x = 1; + let implicit_f = 1.3; + + // Арифметика + let sum = x + y + 13; + + // Изменяемая переменная + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Строки // + + // Строковые литералы + let x: &str = "hello world!"; + + // Печать на консоль + println!("{} {}", f, x); // 1.3 hello world + + // `String` – изменяемя строка + let s: String = "hello world".to_string(); + + // Строковый срез - неизменяемый вид в строки + // Это в основном неизменяемая пара указателей на строку - + // Это указатель на начало и конец строкового буфера + + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hello world hello world + + // Vectors/arrays // + + // фиксированный массив + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // динамический массив + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // Срез - неизменяемое представление значений вектора + let slice: &[i32] = &vector; + + // Используйте шаблон `{:?}`для печати отладочной информации структур с данными + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Кортежи // + + // Кортеж - это фиксированный набор. + // В нём могут находиться значения разных типов данных. + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // Инициализация группы переменных `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Доступ по индексу + println!("{}", x.1); // hello + + ////////////// + // 2. Типы // + ////////////// + + // Struct + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // Структуры могут быть с безымянными полями ‘tuple struct’ + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // Перечисление + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // Перечисление с полями + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // Обобщенные типы данных // + + struct Foo { bar: T } + + // Частоиспользуемое перечисление стандартной библиотеки `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // Методы // + + impl Foo { + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Типаж + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + ///////////////////////// + // 3. Поиск по шаблону // + ///////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // Более сложный пример + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } + + ///////////////////// + // 4. Управление ходом выполнения программы // + ///////////////////// + + // `for` loops/iteration + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Отрезки + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // prints `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` as expression + let value = if true { + "good" + } else { + "bad" + }; + + // `while` loop + while 1 == 1 { + println!("The universe is operating normally."); + break; + } + + // Infinite loop + loop { + println!("Hello!"); + break; + } + + ///////////////////////////////// + // 5. Защита памяти и указатели // + ///////////////////////////////// + + // Владеющий указатель – такой указатель может быть только один + // Это значит, что при вызоде из блока переменная автоматически становится недействительной. + let mut mine: Box = Box::new(3); + *mine = 5; // dereference + // Здесь, `now_its_mine` получает во владение `mine`. Т.е. `mine` была перемещена. + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); + + // Ссылки - это неизменяемые указатели + // Если ссылка получает значения, то говорят, что она заимствует это значение. + // Такое значение не может быть изменено или перемещено. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); + println!("{}", *ref_var); + // var = 5; // не скомпилируется + // *ref_var = 6; // и это + + // Изменяемые ссылки + // + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' используется для изменения значения + + println!("{}", *ref_var2); // 6 , // var2 would not compile. + // ref_var2 имеет тип &mut i32, т.е. он содержит ссылку на i32, а не значение. + // var2 = 2; // не скомпилируется, т.к. эта переменная уже была заимствована ранее +} + +``` + +## Более подробная информация о языке + +Уже есть хорошие книги для изучающих Rust. Основным источником остаётся +[The Rust Programming Language](http://doc.rust-lang.org/book/index.html) + +Для компиляции программ при изучении языка весьма удобно использовать +[Rust playpen](http://play.rust-lang.org). +Множество ресурсов на разных языках можно найти в [этом проекте](https://github.com/ctjhoa/rust-learning). -- cgit v1.2.3 From 501828c89180d88183aa05749911f4e660878c23 Mon Sep 17 00:00:00 2001 From: Anatolij Date: Thu, 20 Sep 2018 13:04:31 +0200 Subject: Add gescription related break statement Insert description related to break statement. --- rust.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 1c0e324c..71bc16b5 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -260,13 +260,16 @@ fn main() { // `while` loop while 1 == 1 { println!("The universe is operating normally."); - break; + // break statement gets out of the while loop. + // It avoids useless iterations. + break } // Infinite loop loop { println!("Hello!"); - break; + // break statement gets out of the loop + break } ///////////////////////////////// -- cgit v1.2.3 From 1ed457fec5848d255e3838bd9256a984130e7da1 Mon Sep 17 00:00:00 2001 From: Anatolij Date: Thu, 20 Sep 2018 13:13:50 +0200 Subject: Fix all requarements related to metadata I put in all into about this document and myself --- ru-ru/rust-ru.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown index ac221ab6..3e3eb0fd 100644 --- a/ru-ru/rust-ru.html.markdown +++ b/ru-ru/rust-ru.html.markdown @@ -1,8 +1,12 @@ --- language: rust +filename: learnrust-ru.rs contributors: - ["P1start", "http://p1start.github.io/"] -filename: learnrust.rs +translators: + - ["Anatolii Kosorukov", "https://github.com/java1cprog"] +lang: ru-ru + --- Rust сочетает в себе низкоуровневый контроль над производительностью с удобством высокого уровня и предоставляет гарантии -- cgit v1.2.3 From 6f61eabb740194899ac9d59785a247a6f2a32ec4 Mon Sep 17 00:00:00 2001 From: Anatolij Date: Thu, 20 Sep 2018 13:31:37 +0200 Subject: add line after language: rust I add line after language: rust --- ru-ru/rust-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown index 3e3eb0fd..7bd2809a 100644 --- a/ru-ru/rust-ru.html.markdown +++ b/ru-ru/rust-ru.html.markdown @@ -1,5 +1,6 @@ --- language: rust + filename: learnrust-ru.rs contributors: - ["P1start", "http://p1start.github.io/"] -- cgit v1.2.3 From 681bf26320b3540e65d6afa159d3374290c42e69 Mon Sep 17 00:00:00 2001 From: Lorenzo Bragaglia Date: Thu, 20 Sep 2018 00:10:08 +0200 Subject: [fsharp/en] Add note on equality operator Add a note pointing out the use of single char "=" equality operator. --- fsharp.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index dd85552d..59461eed 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -34,7 +34,7 @@ let myFloat = 3.14 let myString = "hello" // note that no types needed // ------ Lists ------ -let twoToFive = [2; 3; 4; 5] // Square brackets create a list with +let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. let oneToFive = 1 :: twoToFive // :: creates list with new 1st element // The result is [1; 2; 3; 4; 5] @@ -53,7 +53,8 @@ add 2 3 // Now run the function. // to define a multiline function, just use indents. No semicolons needed. let evens list = - let isEven x = x % 2 = 0 // Define "isEven" as a sub function + let isEven x = x % 2 = 0 // Define "isEven" as a sub function. Note + // that equality operator is single char "=". List.filter isEven list // List.filter is a library function // with two parameters: a boolean function // and a list to work on -- cgit v1.2.3 From 92dff0c07c2b6ae3d14e01046302168a86352a33 Mon Sep 17 00:00:00 2001 From: Stig Palmquist Date: Mon, 24 Sep 2018 23:42:56 +0200 Subject: fixed small inconsistency --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 76e7735b..28b5173b 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -502,7 +502,7 @@ nil ; false; also, the empty list: () (fact 5) ; => 120 -(loop :for x :across "abc" :collect x) +(loop :for x :across "abcd" :collect x) ; => (#\a #\b #\c #\d) (dolist (i '(1 2 3 4)) -- cgit v1.2.3 From 2d8ec9de82d7094690e59ac8800cb013865ab728 Mon Sep 17 00:00:00 2001 From: abz401 Date: Tue, 25 Sep 2018 22:56:01 +0200 Subject: fixed small typos --- de-de/git-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index a0ed120f..d2222d2c 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -10,7 +10,7 @@ lang: de-de Git ist eine verteilte Versions- und Quellcodeverwaltung. -Es nimmt Schnappschüsse der Projekte, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können. +Es nimmt Schnappschüsse der Projekte auf, um mit diesen Schnappschüssen verschiedene Versionen unterscheiden und den Quellcode verwalten zu können. Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* oder *Head* sind idiomatische Bestandteile im Umgang mit Git. Sie wurden nicht übersetzt. @@ -43,7 +43,7 @@ Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichn ### Repository (Repo) -Ein Satz von Dateien, Verzeichnisen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben. +Ein Satz von Dateien, Verzeichnissen, Historieneinträgen, Commits und Heads. Stell es dir wie eine Quellcode-Datenstruktur vor, unter anderem mit der Eigenschaft, dass alle *Elemente* dir Zugriff auf die Revisionshistorie geben. Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichnis. @@ -66,7 +66,7 @@ Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. W ### Branch -Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf Stand gebracht und zeigt dann auf den neuen letzten Commit. +Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, den du gemacht hast. Während des Commits wird der Pointer automatisch auf diesen Stand gebracht und zeigt dann auf den neuen letzten Commit. ### HEAD und head (Teil des .git-Verzeichnisses) @@ -215,7 +215,7 @@ $ git commit --amend -m "Correct message" ### diff -Zeigt die Unterschiede zwischen Dateien von Arbeitsverzeichnisse, dem Index und Commits an. +Zeigt die Unterschiede zwischen Dateien vom Arbeitsverzeichnis, dem Index und Commits an. ```bash # Unterschiede zwischen deinem Arbeitsverzeichnis und dem Index anzeigen @@ -330,7 +330,7 @@ $ git push origin master ### rebase (mit Vorsicht einsetzen) -Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden. +Nimm alle Änderungen, die in einem Branch durch Commits vorgenommen wurden, und übertrage sie auf einen anderen Branch. Achtung: Führe keinen Rebase von Commits durch, die auf ein öffentliches Repo gepusht wurden! ```bash # Rebase "experimentBranch" in den "master"-Branch -- cgit v1.2.3 From 6198be809290c8e4abd7ef92815d94ea7ef697c6 Mon Sep 17 00:00:00 2001 From: Joshua Adams Date: Thu, 27 Sep 2018 10:58:55 -0600 Subject: added full screen movement formating more formatting --- vim.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/vim.html.markdown b/vim.html.markdown index d5c4e865..0eb2c37e 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -34,6 +34,11 @@ specific points in the file, and for fast editing. k # Move up one line l # Move right one character + Ctrl+B # Move back one full screen + Ctrl+F # Move forward one full screen + Ctrl+D # Move forward 1/2 a screen + Ctrl+U # Move back 1/2 a screen + # Moving within the line 0 # Move to beginning of line -- cgit v1.2.3 From 61582f64149f6d5bd00880dfebd7e2b4904a6d77 Mon Sep 17 00:00:00 2001 From: Peter Kehl Date: Fri, 28 Sep 2018 17:02:14 -0700 Subject: Changed a name in a code example to make it British English-friendly The previous name is considered rude by Brits --- clojure.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clojure.html.markdown b/clojure.html.markdown index 7830f228..c94625d6 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -150,7 +150,7 @@ x ; => 1 ; You can also use this shorthand to create functions: (def hello2 #(str "Hello " %1)) -(hello2 "Fanny") ; => "Hello Fanny" +(hello2 "Julie") ; => "Hello Julie" ; You can have multi-variadic functions, too (defn hello3 -- cgit v1.2.3 From 7ac9d6383f521fcf76c1f12e9d967309b61ed9fd Mon Sep 17 00:00:00 2001 From: "[Ernesto]" <[ernesto.p@itmexicali.edu.mx]> Date: Sun, 30 Sep 2018 08:56:43 -0700 Subject: added changes --- es-es/erlang-es.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/es-es/erlang-es.html.markdown b/es-es/erlang-es.html.markdown index 820ee1da..bc6317a5 100644 --- a/es-es/erlang-es.html.markdown +++ b/es-es/erlang-es.html.markdown @@ -1,12 +1,13 @@ --- -language: Erlang +language: erlang lang: es-es contributors: - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] translators: - ["Ernesto Pelayo", "http://github.com/ErnestoPelayo"] -filename: learnerlang.erl +filename: learnerlang-es.erl --- + # Erlang % Signo de porcentaje inicia un comentario de una línea. -- cgit v1.2.3 From 9f337dd02823f845ca913beb44464f269340c7dd Mon Sep 17 00:00:00 2001 From: Rahiel Kasim Date: Mon, 1 Oct 2018 09:53:22 +0200 Subject: [php/en]: typo --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index d4fbaa32..6542035f 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -443,7 +443,7 @@ echo $function_name(1, 2); // => 3 // Or, use call_user_func(callable $callback [, $parameter [, ... ]]); -// You can get the all the parameters passed to a function +// You can get all the parameters passed to a function function parameters() { $numargs = func_num_args(); if ($numargs > 0) { -- cgit v1.2.3 From fbbd0543018ef573deac5074bc7c28d7888513bf Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 1 Oct 2018 17:00:02 -0300 Subject: Small typos --- pt-br/latex-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown index a9ed566e..103af28e 100644 --- a/pt-br/latex-pt.html.markdown +++ b/pt-br/latex-pt.html.markdown @@ -30,7 +30,7 @@ $ Todo comando LaTeX começa com uma barra invertida (\) % Em seguida definimos os pacotes que o documento usa. % Se você quiser incluir gráficos, texto colorido, ou código fonte de outra % linguagem em outro arquivo em seu documento, você precisa ampliar as -% capacidade do LaTeX. Isso é feito adicionando-se pacotes. +% capacidades do LaTeX. Isso é feito adicionando-se pacotes. % Serão incluídos os pacotes float e caption para imagens e hyperref % para links. \usepackage{caption} @@ -46,7 +46,7 @@ Svetlana Golubeva} \date{\today} \title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!} -% Agora estamos pronto para começar o documento +% Agora estamos prontos para começar o documento % Tudo antes dessa linha é chamado "preâmbulo". \begin{document} % Se informarmos os campos author (autores), date (data), "title" (título), @@ -55,7 +55,7 @@ Svetlana Golubeva} % Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso, % o documento deve ser compilado duas vezes, para que tudo apareça na ordem % correta. -% É uma voa prática separar a tabela de conteúdo do corpo do documento. Para +% É uma boa prática separar a tabela de conteúdo do corpo do documento. Para % isso usa-se o comando \newpage \newpage \tableofcontents -- cgit v1.2.3 From 73ec94dc7b93fc9408ef4a4162cef211829fe971 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 1 Oct 2018 17:03:32 -0300 Subject: Small typos --- pt-br/pyqt-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown index 10d55784..40fe82d5 100644 --- a/pt-br/pyqt-pt.html.markdown +++ b/pt-br/pyqt-pt.html.markdown @@ -10,7 +10,7 @@ lang: pt-br --- **Qt** é amplamente conhecido como um framework para desenvolvimento de -software multi-plataforma que pode rodar em vários outras plataformas de +software multi-plataforma que pode rodar em várias outras plataformas de softwares e hardwares com pouca ou nenhuma alteração no código, enquanto mantém o poder e a velocidade de uma aplicação nativa. Embora o **Qt** tenha sido originalmente escrito em *C++*. -- cgit v1.2.3 From 1ab053de7d42df484821c523025bef28b05b9e25 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 1 Oct 2018 17:07:53 -0300 Subject: Small typos --- pt-br/rust-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown index 8134d3c5..b2bab214 100644 --- a/pt-br/rust-pt.html.markdown +++ b/pt-br/rust-pt.html.markdown @@ -11,7 +11,7 @@ Rust é uma linguagem de programação desenvolvida pelo Mozilla Research. Rust combina controle de baixo nível sobre o desempenho com facilidades de alto nível e garantias de segurança. -Ele atinge esse objetico sem necessitar de um coletor de lixo ou um processo +Ele atinge esse objetivo sem necessitar de um coletor de lixo ou um processo *runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas em C. @@ -27,7 +27,7 @@ noite. Rust adotou um modelo de versões *train-based* com novas versões regularmente liberadas a cada seis semanas. A versão 1.1 beta de Rust foi disponibilizada ao mesmo tempo que a versão 1.0. -Apesar de Rust ser uma linguagem mais e baixo nível, Rust tem alguns conceitos +Apesar de Rust ser uma linguagem mais de baixo nível, Rust tem alguns conceitos funcionais geralmente encontradas em linguagens de alto nível. Isso faz Rust não apenas rápido, mas também fácil e eficiente para programar. @@ -68,7 +68,7 @@ fn main() { // Em geral, o compilador Rust consegue inferir qual o tipo de uma // variável, então você não tem que escrever uma anotação explícita de tipo. // Ao longo desse tutorial, os tipos serão explicitamente anotados em - // muitos lugares, mas apenas com propóstico demonstrativo. A inferência de + // muitos lugares, mas apenas com propósito demonstrativo. A inferência de // tipos pode gerenciar isso na maioria das vezes. let implicit_x = 1; let implicit_f = 1.3; -- cgit v1.2.3 From 26c1a0326fb2c276cdacb2b0665c1a666fe8377b Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 1 Oct 2018 17:10:41 -0300 Subject: Small typos --- pt-br/vim-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/vim-pt.html.markdown b/pt-br/vim-pt.html.markdown index 51eddb48..d7617bbe 100644 --- a/pt-br/vim-pt.html.markdown +++ b/pt-br/vim-pt.html.markdown @@ -13,7 +13,7 @@ filename: LearnVim-pt.txt [Vim](http://www.vim.org) (Vi IMproved - Vi Melhorado) é um clone do editor vi para Unix. Ele é um editor de texto projetado para ter velocidade e produtividade, e está presente -na maioria dos systemas UNIX. O editor tem um grande número de atalhos de teclado +na maioria dos sistemas UNIX. O editor tem um grande número de atalhos de teclado para agilizar a navegação para pontos específicos no arquivo, além de edição rápida. ## Navegação do Vim: o básico @@ -25,7 +25,7 @@ para agilizar a navegação para pontos específicos no arquivo, além de ediç :wq # Salva o arquivo e fecha o vim :q! # Fecha o vim e descarta as alterações no arquivo # ! *força* :q a executar, fechando o vim sem salvar antes - :x # Salvar o arquivo e fechao vim (atalho para :wq) + :x # Salva o arquivo e fecha o vim (atalho para :wq) u # Desfazer CTRL+R # Refazer @@ -62,7 +62,7 @@ para agilizar a navegação para pontos específicos no arquivo, além de ediç # Movendo por palavras - w # Move o cursor uma palavra a diante + w # Move o cursor uma palavra adiante b # Move o cursor uma palavra atrás e # Move o cursor ao fim da palavra atual -- cgit v1.2.3 From c6691f31004ffa6fc2be0bccd25f210fccfd2377 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Mon, 1 Oct 2018 17:16:56 -0300 Subject: Small typos --- pt-br/go-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index c7339831..31473ee1 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -16,7 +16,7 @@ A linguagem Go foi criada a partir da necessidade de ver trabalho feito. Não forma de resolver os problemas do mundo real. Tem conceitos familiares de linguagens imperativas com tipagem estática. É -rápida a compilar e rápida a executar, acrescentando mecanismos de concorrência +rápida para compilar e rápida para executar, acrescentando mecanismos de concorrência fáceis de entender para tirar partido dos CPUs multi-core de hoje em dia, e tem recursos para ajudar com a programação em larga escala. @@ -39,10 +39,10 @@ import ( ) // Definição de uma função. Main é especial. É o ponto de entrada para o -// programa executável. Goste-se ou não, a linguagem Go usa chavetas. +// programa executável. Goste-se ou não, a linguagem Go usa chaves. func main() { // A função Println envia uma linha para stdout. - // É necessário qualifica-la com o nome do pacote, fmt. + // É necessário qualificá-la com o nome do pacote, fmt. fmt.Println("Olá Mundo!") // Chama outra função dentro deste pacote. -- cgit v1.2.3 From e5190aefb1046ebd0174024b1ac437f0bd5c2e80 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Mon, 1 Oct 2018 19:48:57 -0300 Subject: [asymptotic-notation/pt-br] Small typo --- pt-br/asymptotic-notation-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown index aecc2194..2f179f96 100644 --- a/pt-br/asymptotic-notation-pt.html.markdown +++ b/pt-br/asymptotic-notation-pt.html.markdown @@ -88,7 +88,7 @@ Função Exponencial - a^n, onde *a* é uma constante Big-O, também escrita como O, é uma Notação Assintótica para o pior caso. Digamos *f(n)* seja o tempo de exeução de um algoritmo e *g(n)) um tempo de complexidade -arbritário que você quer relacionar com seu algoritmo. *f(n)* é O(g(n)), se, para +arbitrário que você quer relacionar com seu algoritmo. *f(n)* é O(g(n)), se, para quando constante real c (c > 0), *f(n)* <= *c g(n)* para todo tamanho de entrada n (n > 0). -- cgit v1.2.3 From b3796a94a91897b8bd80e05401641bdd17d655f0 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Mon, 1 Oct 2018 19:56:14 -0300 Subject: [bash/pt-br] Small typo --- pt-br/bash-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown index ae18435a..3a48d994 100644 --- a/pt-br/bash-pt.html.markdown +++ b/pt-br/bash-pt.html.markdown @@ -16,7 +16,7 @@ lang: pt-br Tutorial de shell em português -Bash é o nome do shell do Unix, que também é distribuido como shell do sistema +Bash é o nome do shell do Unix, que também é distribuído como shell do sistema operacional GNU e como shell padrão para Linux e Mac OS X. Praticamente todos os exemplos abaixo podem fazer parte de um shell script e pode ser executados diretamente no shell. -- cgit v1.2.3 From 260e40ceca594fb17b2902eb8fd4609803a1dafb Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Mon, 1 Oct 2018 20:05:13 -0300 Subject: [c++/pt-br] Better translation --- pt-br/c++-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index cd4adde7..2c15e92c 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -564,15 +564,15 @@ void doSomethingWithAFile(const std::string& filename) // Isto tem _grandes_ vantagens: // 1. Não importa o que aconteça, -// o recurso (neste caso, o identificador de ficheiro) irá ser limpo. +// o recurso (neste caso, o identificador de ficheiro) será limpo. // Depois de escrever o destruidor corretamente, // É _impossível_ esquecer de fechar e vazar o recurso // 2. Nota-se que o código é muito mais limpo. // As alças destructor fecham o arquivo por trás das cenas // sem que você precise se preocupar com isso. // 3. O código é seguro de exceção. -// Uma exceção pode ser jogado em qualquer lugar na função e a limpeza -// irá ainda ocorrer. +// Uma exceção pode ser lançada em qualquer lugar na função e a limpeza +// ainda irá ocorrer. // Todos códigos C++ usam RAII extensivamente para todos os recursos. // Outros exemplos incluem -- cgit v1.2.3 From 3f3d5763dd9da4fa6fb7a32d386dbfd707895c77 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Mon, 1 Oct 2018 20:10:17 -0300 Subject: [c/pt-br] Small typo --- pt-br/c-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index d594b7b9..e1c27958 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -538,7 +538,7 @@ int area(retan r) return r.largura * r.altura; } -// Se você tiver structus grande, você pode passá-las "por ponteiro" +// Se você tiver structs grandes, você pode passá-las "por ponteiro" // para evitar cópia de toda a struct: int area(const retan *r) { -- cgit v1.2.3 From e58b0d88adaacf8d5cea1e9fe80381a0182368ab Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Mon, 1 Oct 2018 20:15:55 -0300 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index b6e95d36..be14a1c8 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -834,7 +834,7 @@ on a new line! ""Wow!"", the masses cried"; bool Broken { get; } // interfaces can contain properties as well as methods & events } - // Class can inherit only one other class, but can implement any amount of interfaces + // Classes podem herdar apenas de uma outra classe, mas podem implementar qualquer quantidade de interfaces. class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; -- cgit v1.2.3 From 4f89d81856d85055f93a565da4a39a6e5abaeccf Mon Sep 17 00:00:00 2001 From: Gabriele Luz Date: Mon, 1 Oct 2018 22:00:47 -0300 Subject: Translates `media queries` section to pt-br --- pt-br/css-pt.html.markdown | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index 956b3614..c73669d0 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -9,6 +9,8 @@ contributors: - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] + - ["Gabriele Luz", "https://github.com/gabrieleluz"] + lang: pt-br --- @@ -236,6 +238,45 @@ A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada * `B` é o próximo. * `D` é a última. +## Media Queries +Media queries são recursos do CSS3 que permitem especificar quando determinadas regras de CSS devem ser aplicadas; é possível aplicar regras diferentes quando a página é impressa, quando a tela possui determinadas dimensões ou densidade de pixels e quando é lida por um leitor de tela. Media queries não adicionam especificidade ao seletor. + +```css +/* Uma regra que será aplicada a todos os dispositivos */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* Altera a cor do h1 para utilizar menos tinta durante a impressão */ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* Altera o tamanho da fonte quando exibida numa tela com pelo menos 480px de largura */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` +Media queries podem incluir os seguintes atributos: `width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. A maioria desses atributos pode ser prefixada com `min-` ou `max-`. + +O atributo `resolution` não é suportado em dispositivos mais antigos. Em vez disso, use `device-pixel-ratio`. + +Muitos smartphones e tablets tentarão renderizar a página como se estivesse num desktop a menos que você utilize a meta-tag `viewport`. + +```html + + + +``` + ## Compatibilidade A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso. -- cgit v1.2.3 From 9438e56ae90755582be35b6756e5b97dd5d1334a Mon Sep 17 00:00:00 2001 From: Muhammad Rifqi Fatchurrahman Date: Wed, 3 Oct 2018 00:56:58 +0700 Subject: [Kotlin/en] add kotlin operator overloading --- kotlin.html.markdown | 73 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 3 deletions(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 86d1baa0..6ff7c1dc 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -65,7 +65,7 @@ fun helloWorld(val name : String) { A template expression starts with a dollar sign ($). */ val fooTemplateString = "$fooString has ${fooString.length} characters" - println(fooTemplateString) // => My String Is Here! has 18 characters + println(fooTemplateString) // => My String Is Here! has 18 characters /* For a variable to hold null it must be explicitly specified as nullable. @@ -175,12 +175,12 @@ fun helloWorld(val name : String) { // Objects can be destructured into multiple variables. val (a, b, c) = fooCopy println("$a $b $c") // => 1 100 4 - + // destructuring in "for" loop for ((a, b, c) in listOf(fooData)) { println("$a $b $c") // => 1 100 4 } - + val mapData = mapOf("a" to 1, "b" to 2) // Map.Entry is destructurable as well for ((key, value) in mapData) { @@ -347,6 +347,8 @@ fun helloWorld(val name : String) { println(EnumExample.A) // => A println(ObjectExample.hello()) // => hello + + testOperator() } // Enum classes are similar to Java enum types. @@ -376,6 +378,71 @@ throws an exception if the value is null. */ var b: String? = "abc" val l = b!!.length + +/* You can add many custom operations using symbol like +, to particular instance +by overloading the built-in kotlin operator, using "operator" keyword + +below is the sample class to add some operator, and the most basic example +*/ +data class SomeClass(var savedValue: Int = 0) + +// instance += valueToAdd +operator fun SomeClass.plusAssign(valueToAdd: Int) { + this.savedValue += valueToAdd +} + +// -instance +operator fun SomeClass.unaryMinus() = SomeClass(-this.savedValue) + +// ++instance or instance++ +operator fun SomeClass.inc() = SomeClass(this.savedValue + 1) + +// instance * other +operator fun SomeClass.times(other: SomeClass) = + SomeClass(this.savedValue * other.savedValue) + +// an overload for multiply +operator fun SomeClass.times(value: Int) = SomeClass(this.savedValue * value) + +// other in instance +operator fun SomeClass.contains(other: SomeClass) = + other.savedValue == this.savedValue + +// instance[dummyIndex] = valueToSet +operator fun SomeClass.set(dummyIndex: Int, valueToSet: Int) { + this.savedValue = valueToSet + dummyIndex +} + +// instance() +operator fun SomeClass.invoke() { + println("instance invoked by invoker") +} + +/* return type must be Integer, +so that, it can be translated to "returned value" compareTo 0 + +for equality (==,!=) using operator will violates overloading equals function, +since it is already defined in Any class +*/ +operator fun SomeClass.compareTo(other: SomeClass) = + this.savedValue - other.savedValue + +fun testOperator() { + var x = SomeClass(4) + + println(x) // => "SomeClass(savedValue=4)" + x += 10 + println(x) // => "SomeClass(savedValue=14)" + println(-x) // => "SomeClass(savedValue=-14)" + println(++x) // => "SomeClass(savedValue=15)" + println(x * SomeClass(3)) // => "SomeClass(savedValue=45)" + println(x * 2) // => "SomeClass(savedValue=30)" + println(SomeClass(15) in x) // => true + x[2] = 10 + println(x) // => "SomeClass(savedValue=12)" + x() // => "instance invoked by invoker" + println(x >= 15) // => false +} ``` ### Further Reading -- cgit v1.2.3 From e533369df895fc5f2fd3a034b0fb53d84672f877 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Tue, 2 Oct 2018 13:55:35 -0700 Subject: [pascal/en] add functions/procedures --- pascal.html.markdown | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/pascal.html.markdown b/pascal.html.markdown index 6877afef..4144f900 100644 --- a/pascal.html.markdown +++ b/pascal.html.markdown @@ -3,6 +3,7 @@ language: Pascal filename: learnpascal.pas contributors: - ["Ganesha Danu", "http://github.com/blinfoldking"] + - ["Keith Miyake", "https://github.com/kaymmm"] --- @@ -92,5 +93,46 @@ End. ``` ```pascal +program Functional_Programming; -``` \ No newline at end of file +Var + i, dummy : integer; + +function factorial_recursion(const a: integer) : integer; +{ recursively calculates the factorial of integer parameter a } + +// Declare local variables within the function +// e.g.: +// Var +// local_a : integer; + +Begin + If a >= 1 Then + // return values from functions by assigning a value to the function name + factorial_recursion := a * factorial_recursion(a-1) + Else + factorial_recursion := 1; +End; // terminate a function using a semicolon after the End statement. + +procedure get_integer(var i : integer; dummy : integer); +{ get user input and store it in the integer parameter i. + parameters prefaced with 'var' are variable, meaning their value can change + outside of the parameter. Value parameters (without 'var') like 'dummy' are + static and changes made within the scope of the function/procedure do not + affect the variable passed as a parameter } + +Begin + write('Enter an integer: '); + readln(i); + dummy := 4; // dummy will not change value outside of the procedure +End; + +Begin // main program block + dummy := 3; + get_integer(i, dummy); + writeln(i, '! = ', factorial_recursion(i)); + // outputs i! + writeln('dummy = ', dummy); // always outputs '3' since dummy is unchanged. +End. + +``` -- cgit v1.2.3 From 088111396a0dff9a5dff7837e1ae74aa9314b620 Mon Sep 17 00:00:00 2001 From: Tucker Boniface Date: Tue, 2 Oct 2018 19:19:18 -0700 Subject: [bash/en] clarify quoted delimiter for heredocs (fixes #3061) --- bash.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/bash.html.markdown b/bash.html.markdown index cb805da7..1f59636e 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -256,6 +256,7 @@ print("#stderr", file=sys.stderr) for line in sys.stdin: print(line, file=sys.stdout) EOF +# Variables will be expanded if the first "EOF" is not quoted # Run the hello.py Python script with various stdin, stdout, and # stderr redirections: -- cgit v1.2.3 From 843626f3d30a06cc1c8b342c155a5dc8af24fbd1 Mon Sep 17 00:00:00 2001 From: Tucker Boniface Date: Tue, 2 Oct 2018 19:23:45 -0700 Subject: [bash/en] add `cd` and `cd -` uses --- bash.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index cb805da7..e609260f 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -228,10 +228,13 @@ mv s0urc3.txt dst.txt # sorry, l33t hackers... # Since bash works in the context of a current directory, you might want to # run your command in some other directory. We have cd for changing location: cd ~ # change to home directory +cd # also goes to home directory cd .. # go up one directory # (^^say, from /home/username/Downloads to /home/username) cd /home/username/Documents # change to specified directory cd ~/Documents/.. # still in home directory..isn't it?? +cd - # change to last directory +# => /home/username/Documents # Use subshells to work across directories (echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") -- cgit v1.2.3 From 9152fe00e54b51ddebaeed9929a3027547cb16a5 Mon Sep 17 00:00:00 2001 From: Tucker Boniface Date: Tue, 2 Oct 2018 19:22:56 -0700 Subject: [bash/en] clarify range of substring --- bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index cb805da7..be879538 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -75,7 +75,7 @@ echo ${Variable/Some/A} # => A string # Substring from a variable Length=7 echo ${Variable:0:$Length} # => Some st -# This will return only the first 7 characters of the value +# This will return 7 characters of the string, starting from the first char # Default value for variable echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} -- cgit v1.2.3 From 2d1461d27fc9f23eae15062c9f799b23e86876cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?An=C4=B1l=20Anar?= Date: Wed, 3 Oct 2018 15:21:23 +0200 Subject: Fix purescript array of ints/numbers Fixes #2026. --- purescript.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/purescript.html.markdown b/purescript.html.markdown index df0cb66e..6b74ac64 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -71,7 +71,8 @@ world""" -- "Hello\nworld" -- -- 2. Arrays are Javascript arrays, but must be homogeneous -[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8] +[1,1,2,3,5,8] :: Array Int -- [1,1,2,3,5,8] +[1.2,2.0,3.14] :: Array Number -- [1.2,2.0,3.14] [true, true, false] :: Array Boolean -- [true,true,false] -- [1,2, true, "false"] won't work -- `Cannot unify Prim.Int with Prim.Boolean` -- cgit v1.2.3 From f8ff01a17eff289e6e5e84a129dd29fa9a8bcdff Mon Sep 17 00:00:00 2001 From: Wayne Boka Date: Wed, 3 Oct 2018 16:23:54 -0400 Subject: Add Readonly Examples In references to #2702. Making another commit due to several extra files getting committed. --- typescript.html.markdown | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index acc258b4..db6579e2 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -178,6 +178,37 @@ let greeting = `Hi ${name}, how are you?` let multiline = `This is an example of a multiline string`; +// READONLY: New Feature in TypeScript 3.1 +interface Person { + readonly name: string; + readonly age: number; +} + +var p1: Person = { name: "Tyrone", age: 42 }; +p1.age = 25; // Error, p1.x is read-only + +var p2 = { name: "John", age: 60 }; +var p3: Person = p2; // Ok, read-only alias for p2 +p3.x = 35; // Error, p3.x is read-only +p2.x = 45; // Ok, but also changes p3.x because of aliasing + +class Car { + readonly make: string; + readonly model: string; + readonly year = 2018; + + constructor() { + this.make = "Unknown Make"; // Assignment permitted in constructor + this.model = "Unknown Model"; // Assignment permitted in constructor + } +} + +let numbers: Array = [0, 1, 2, 3, 4]; +let moreNumbers: ReadonlyArray = numbers; +moreNumbers[5] = 5; // Error, elements are read-only +moreNumbers.push(5); // Error, no push method (because it mutates array) +moreNumbers.length = 3; // Error, length is read-only +numbers = moreNumbers; // Error, mutating methods are missing ``` ## Further Reading -- cgit v1.2.3 From c3c6e3b08d9129d52a7349d0656569022ffa2f9b Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Wed, 3 Oct 2018 17:19:01 -0700 Subject: [ruby/en] fixes 3402 (spring cleanup) --- ruby.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 2f4d0934..2635309b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -17,6 +17,7 @@ contributors: - ["Jake Faris", "https://github.com/farisj"] - ["Corey Ward", "https://github.com/coreyward"] - ["Jannik Siebert", "https://github.com/janniks"] + - ["Keith Miyake", "https://github.com/kaymmm"] --- ```ruby @@ -83,9 +84,9 @@ false.class #=> FalseClass # Combined comparison operator (returns `1` when the first argument is greater, # `-1` when the second argument is greater, and `0` otherwise) -1 <=> 10 #=> -1 -10 <=> 1 #=> 1 -1 <=> 1 #=> 0 +1 <=> 10 #=> -1 (1 < 10) +10 <=> 1 #=> 1 (10 > 1) +1 <=> 1 #=> 0 (1 == 1) # Logical operators true && false #=> false @@ -188,8 +189,11 @@ array[2, 3] #=> [3, 4, 5] array[1..3] #=> [2, 3, 4] # You can reverse an Array. +# Return a new array with reversed values +[1,2,3].reverse #=> [3,2,1] +# Reverse an array in place to update variable with reversed values a = [1,2,3] -a.reverse! #=> [3,2,1] +a.reverse! #=> a==[3,2,1] because of the bang ('!') call to reverse # Like arithmetic, [var] access is just syntactic sugar # for calling a method '[]' on an object. -- cgit v1.2.3 From 97e3cc7df3641eb6143fb1463ed0ad73866d0b82 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Wed, 3 Oct 2018 19:52:42 -0700 Subject: [textile/en] add textile --- textile.html.markdown | 505 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 505 insertions(+) create mode 100644 textile.html.markdown diff --git a/textile.html.markdown b/textile.html.markdown new file mode 100644 index 00000000..d0785a91 --- /dev/null +++ b/textile.html.markdown @@ -0,0 +1,505 @@ +--- +language: textile +contributors: + - ["Keith Miyake", "https://github.com/kaymmm"] +filename: learn-textile.textile +--- + + +Textile is a lightweight markup language that uses a text formatting syntax to +convert plain text into structured HTML markup. The syntax is a shorthand +version of HTML that is designed to be easy to read and write. Textile is used +for writing articles, forum posts, readme documentation, and any other type of +written content published online. + +- [Comments](#comments) +- [Paragraphs](#paragraphs) +- [Headings](#headings) +- [Simple Text Styles](#simple-text-styles) +- [Lists](#lists) +- [Code blocks](#code-blocks) +- [Horizontal rule](#horizontal-rule) +- [Links](#links) +- [Images](#images) +- [Footnotes and Endnotes](#footnotes-and-endnotes) +- [Tables](#tables) +- [Character Conversions](#character-conversions) +- [CSS](#css) +- [Spans and Divs](#spans-and-divs) +- [Additional Info](#additional-info) + +## Comments + +```textile +###. Comments begin with three (3) '#' signs followed by a full-stop period '.'. +Comments can span multiple lines until a blank line is reached. + +###.. +Multi-line comments (including blank lines) are indicated by three (3) '#' +signs followed by two (2) full-stop periods '..'. + +This line is also part of the above comment. + +The comment continues until the next block element is reached + +p. This line is not commented + + + +``` + +## Paragraphs + +```textile +###. Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. They can also be indicated explicitly with a 'p. ' + +This is a paragraph. I'm typing in a paragraph isn't this fun? + +Now I'm in paragraph 2. +I'm still in paragraph 2 too! +Line breaks without blank spaces are equivalent to a
in XHTML. + +p. I'm an explicitly defined paragraph + + Lines starting with a blank space are not wrapped in

..

tags. + +###. Paragraphs (and all block elements) can be aligned using shorthand: + +p<. Left aligned paragraph (default). + +p>. Right aligned paragraph. + +p=. Centered paragraph. + +p<>. Justified paragraph. + +h3>. Right aligned

+ + +###. Paragraphs can be indented using a parentheses for each em +Indentation utilizes padding-[left/right] css styles. + +p(. Left indent 1em. + +p((. Left indent 2em. + +p))). Right indent 3em. + +h2). This is equivalent to

..

+ + +###. Block quotes use the tag 'bq.' + +bq. This is a block quote. + +bq.:http://someurl.com You can include a citation URL immediately after the '.' + +bq.. Multi-line blockquotes containing + +blank lines are indicated using two periods + +p. Multi-line blockquotes continue until a new block element is reached. + +bq. You can add a footer to a blockquote using html: +
citation text
+ + +###. Preformatted text blocks: + +pre. This text is preformatted. <= those two spaces will carry through. + +pre.. This is a multi-line preformatted… + +…text block that includes blank lines + +p. End a multi-line preformatted text block with a new block element. + +``` + +## Headings + +You can create HTML elements `

` through `

` easily by prepending the +text you want to be in that element by 'h#.' where # is the level 1-6. +A blank line is required after headings. + + +```textile +h1. This is an

+ +h2. This is an

+ +h3. This is an

+ +h4. This is an

+ +h5. This is an

+ +h6. This is an
+ +``` + + +## Simple text styles + +```textile +###. Bold and strong text are indicated using asterisks: + +*This is strong text* +**This is bold text** +This is [*B*]old text within a word. + +*Strong* and **Bold** usually display the same in browsers +but they use different HTML markup, thus the distinction. + +###. Italics and emphasized text are indicated using underscores. + +_This is Emphasized text_ +__This is Italics text__ +This is It[_al_]ics within a word. + +_Emphasized_ and __Italics__ text typically display the same in browsers, +but again, they use different HTML markup and thus the distinction. + +###. Superscripts and Subscripts use carats and tildes: + +Superscripts are 2 ^nd^ to none, but subscripts are CO ~2~ L too. +Note the spaces around the superscripts and subscripts. + +To avoid the spaces, add square brackets around them: +2[^nd^] and CO[~2~]L + +###. Insertions and deletions are indicated using -/+ symbols: +This is -deleted- text and this is +inserted+ text. + +###. Citations are indicated using double '?': + +??This is a cool citation?? + +``` + +## Lists + +```textile +###. Unordered lists can be made using asterisks '*' to indicate levels: + +* Item +** Sub-Item +* Another item +** Another sub-item +** Yet another sub-item +*** Three levels deep + +###. Ordered lists are done with a pound sign '#': + +# Item one +# Item two +## Item two-a +## Item two-b +# Item three +** Mixed unordered list within ordered list + +###. Ordered lists can start above 1 and can continue after another block: + +#5 Item 5 +# Item 6 + +additional paragraph + +#_ Item 7 continued from above +# Item 8 + +###. Definition lists are indicated with a dash and assignment: + +- First item := first item definition +- Second := second def. +- Multi-line := +Multi-line +definition =: +``` + +## Code blocks + +```textile +Code blocks use the 'bc.' shorthand: + +bc. This is code + So is this + +This is outside of the code block + +bc.. This is a multi-line code block + +Blank lines are included in the multi-line code block + +p. End a multi-line code block with any block element + +p. Indicate @inline code@ using the '@' symbol. + +``` + +## Horizontal rule + +Horizontal rules (`
`) are easily added with two hyphens + +```textile +-- +``` + +## Links + +```textile +###. Link text is in quotes, followed by a colon and the URL: + +"Link text":http://linkurl.com/ plain text. + +"Titles go in parentheses at the end of the link text"(mytitle):http://url.com +###. produces ... + +###. Use square brackets when the link text or URL might be ambiguous: +["Textile on Wikipedia":http://en.wikipedia.org/wiki/Textile_(markup_language)] + +###. Named links are useful if the same URL is referenced multiple times. +Multiple "references":txstyle to the "txstyle":txstyle website. + +[txstyle]https://txstyle.org/ + +``` + +## Images + +```textile +###. Images can be included by surrounding its URL with exclamation marks (!) +Alt text is included in parenthesis after the URL, and they can be linked too: + +!http://imageurl.com! + +!http://imageurl.com(image alt-text)! + +!http://imageurl.com(alt-text)!:http://image-link-url.com + +``` + +## Footnotes and Endnotes + +```textile +A footnote is indicated with the reference id in square brackets.[1] + +fn1. Footnote text with a "link":http://link.com. + +A footnote without a link.[2!] + +fn2. The corresponding unlinked footnote. + +A footnote with a backlink from the footnote back to the text.[3] + +fn3^. This footnote links back to the in-text citation. + + +Endnotes are automatically numbered[#first] and are indicated using square[#second] +brackets and a key value[#first]. They can also be unlinked[#unlinkednote!] + +###. Give the endnotes text: + +note#first. This is the first endnote text. + +note#second. This is the second text. + +note#unlinkednote. This one isn't linked from the text. + +### Use the notelist block to place the list of notes in the text: +This list will start with #1. Can also use alpha or Greeks. +notelist:1. ###. start at 1 (then 2, 3, 4...) +notelist:c. ###. start at c (then d, e, f...) +notelist:α. ###. start at α (then β, γ, δ...) + +###. The notelist syntax is as follows: + +notelist. Notes with backlinks to every citation made to them. +notelist+. Notes with backlinks to every citation made to them, + followed by the unreferenced notes. +notelist^. Notes with one backlink to the first citation made to each note. +notelist^+. Notes with one backlink to the first citation made to each note, + followed by unreferenced notes. +notelist!. Notes with no backlinks to the citations. +notelist!+. Notes with no backlinks to the citations, followed by + unreferenced notes. +``` + +## Tables + + +```textile +###. Tables are simple to define using the pipe '|' symbol + +| A | simple | table | row | +| And | another | table | row | +| With an | | empty | cell | + +###. Headers are preceded by '|_.' +|_. First Header |_. Second Header | +| Content Cell | Content Cell | + +###. The tag is added when |^. above and |-. below the heading are used. + +|^. +|_. First Header |_. Second Header | +|-. +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +###. The tag is added when |~. above and |-. below the footer are used. + +|~. +|\2=. A footer, centered & across two columns | +|-. +| Content Cell | Content Cell | +| Content Cell | Content Cell | + +###. Attributes are be applied either to individual cells, rows, or to +the entire table. Cell attributes are placed within each cell: + +|a|{color:red}. styled|cell| + +###. Row attributes are placed at the beginning of a row, +followed by a dot and a space: + +(rowclass). |a|classy|row| + +###. Table attributes are specified by placing the special 'table.' block +modifier immediately before the table: + +table(tableclass). +|a|classy|table| +|a|classy|table| + +###. Spanning rows and colums: +A backslash \ is used for a column span: + +|\2. spans two cols | +| col 1 | col 2 | + +###. A forward slash / is used for a row span: + +|/3. spans 3 rows | row a | +| row b | +| row c | + +###. Vertical alignments within a table cell: + +|^. top alignment| +|-. middle alignment| +|~. bottom alignment| + +###. Horizontal alignments within a table cell + +|:\1. |400| +|=. center alignment | +| no alignment | +|>. right alignment | + +``` +or, for the same results + +```textile +Col 1 | Col2 | Col3 +:-- | :-: | --: +Ugh this is so ugly | make it | stop +``` + + +## Character Conversions + +### Registered, Trademark, Copyright Symbols + +```textile +RegisteredTrademark(r), Trademark(tm), Copyright (c) +``` + +### Acronyms + +```textile +###. Acronym definitions can be provided in parentheses: + +EPA(Environmental Protection Agency) and CDC(Center for Disease Control) +``` + +### Angle Brackets and Ampersand + +```textile +### Angled brackets < and > and ampersands & are automatically escaped: +< => < +> => > +& => & +``` + +### Ellipses + +```textile +p. Three consecutive periods are translated into ellipses...automatically +``` + +### Em and En dashes + +```textile +###. En dashes (short) is a hyphen surrounded by spaces: + +This line uses an en dash to separate Oct - Nov 2018. + +###. Em dashes (long) are two hyphens with or without spaces: + +This is an em dash--used to separate clauses. +But we can also use it with spaces -- which is a less-used convention. +That last hyphen between 'less' and 'used' is not converted between words. +``` + +## Fractions and other Math Symbols + +```textile +One quarter: (1/4) => ¼ +One half: (1/2) => ½ +Three quarters: (3/4) => ¾ +Degree: (o) => ° +Plus/minus: (+/-) => ± +``` +### Multiplication/Dimension + +```textile +p. Numbers separated by the letter 'x' translate to the multiplication +or dimension symbol '×': +3 x 5 => 3 × 5 +``` + +### Quotes and Apostrophes + +```textile +###. Straight quotes and apostrophes are automatically converted to +their curly equivalents: + +"these", 'these', and this'n are converted to their HTML entity equivalents. +Leave them straight using '==' around the text: =="straight quotes"==. +``` + +## CSS + +```textile +p{color:blue}. CSS Styles are enclosed in curly braces '{}' +p(my-class). Classes are enclosed in parenthesis +p(#my-id). IDs are enclosed in parentheses and prefaced with a pound '#'. +``` + +## Spans and Divs + +```textile +%spans% are enclosed in percent symbols +div. Divs are indicated by the 'div.' shorthand +``` +--- + +## For More Info + +* TxStyle Textile Documentation: [https://txstyle.org/](https://txstyle.org/) +* promptworks Textile Reference Manual: [https://www.promptworks.com/textile](https://www.promptworks.com/textile) +* Redmine Textile Formatting: [http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile](http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile) -- cgit v1.2.3 From 29422fb84da250c9aea4259f8d4009e8a6728b08 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 4 Oct 2018 12:18:50 -0700 Subject: [pascal/en] add additional data types and arrays --- pascal.html.markdown | 86 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 77 insertions(+), 9 deletions(-) diff --git a/pascal.html.markdown b/pascal.html.markdown index 4144f900..28dcc10f 100644 --- a/pascal.html.markdown +++ b/pascal.html.markdown @@ -25,6 +25,10 @@ to compile and run a pascal program you could use a free pascal compiler. [Downl //name of the program program learn_pascal; //<-- dont forget a semicolon +const + { + this is where you should declare constant values + } type { this is where you should delcare a custom @@ -55,17 +59,71 @@ var //or this var a,b : integer; ``` + ```pascal program Learn_More; //Lets learn about data types and their operations +const + PI = 3.141592654; + GNU = 'GNU's Not Unix'; + // constants are conventionally named using CAPS + // their values are fixed and cannot be changed during runtime + // holds any standard data type (integer, real, boolean, char, string) + +type + ch_array : array [0..255] of char; + // arrays are new 'types' specifying the length and data type + // this defines a new data type that contains 255 characters + // (this is functionally equivalent to a string[256] variable) + md_array : array of array of integer; + // nested arrays are equivalent to multidimensional arrays + // can define zero (0) length arrays that are dynamically sized + // this is a 2-dimensional array of integers + //Declaring variables -var - int : integer; // a variable that contains an integer number data types - ch : char; // a variable that contains a character data types - str : string; // a variable that contains a string data types - r : real; // a variable that contains a real number data types - bool : boolean; //a variables that contains a Boolean(True/False) value data types +var + int, c, d : integer; + // three variables that contain integer numbers + // integers are 16-bits and limited to the range [-32,768..32,767] + r : real; + // a variable that contains a real number data types + // reals can range between [3.4E-38..3.4E38] + bool : boolean; + // a variable that contains a Boolean(True/False) value + ch : char; + // a variable that contains a character value + // char variables are stored as 8-bit data types so no UTF + str : string; + // a non-standard variable that contains a string value + // strings are an extension included in most Pascal compilers + // they are stored as an array of char with default length of 255. + s : string[50]; + // a string with maximum length of 50 chars. + // you can specify the length of the string to minimize memory usage + my_str: ch_array; + // you can declare variables of custom types + my_2d : md_array; + // dynamically sized arrays need to be sized before they can be used. + + // additional integer data types + b : byte; // range [0..255] + shi : shortint; // range [-128..127] + smi : smallint; // range [-32,768..32,767] (standard Integer) + w : word; // range [0..65,535] + li : longint; // range [-2,147,483,648..2,147,483,647] + lw : longword; // range [0..4,294,967,295] + c : cardinal; // longword + i64 : int64; // range [-9223372036854775808..9223372036854775807] + qw : qword; // range [0..18,446,744,073,709,551,615] + + // additional real types + rr : real; // range depends on platform (i.e., 8-bit, 16-bit, etc.) + rs : single; // range [1.5E-45..3.4E38] + rd : double; // range [5.0E-324 .. 1.7E308] + re : extended; // range [1.9E-4932..1.1E4932] + rc : comp; // range [-2E64+1 .. 2E63-1] + Begin int := 1;// how to assign a value to a variable r := 3.14; @@ -76,19 +134,28 @@ Begin //arithmethic operation int := 1 + 1; // int = 2 overwriting the previous assignment int := int + 1; // int = 2 + 1 = 3; - int := 4 div 2; //int = 2 a division operation which the result will be floored + int := 4 div 2; //int = 2 division operation where result will be floored int := 3 div 2; //int = 1 int := 1 div 2; //int = 0 bool := true or false; // bool = true bool := false and true; // bool = false bool := true xor true; // bool = false - + r := 3 / 2; // a division operator for real - r := int; // you can assign an integer to a real variable but not the otherwise + r := int; // can assign an integer to a real variable but not the reverse c := str[1]; // assign the first letter of str to c str := 'hello' + 'world'; //combining strings + + my_str[0] := 'a'; // array assignment needs an index + + setlength(my_2d,10,10); // initialize dynamically sized arrays: 10×10 array + for c := 0 to 9 do // arrays begin at 0 and end at length-1 + for d := 0 to 9 do // for loop counters need to be declared variables + my_2d[c,d] := c * d; + // address multidimensional arrays with a single set of brackets + End. ``` @@ -136,3 +203,4 @@ Begin // main program block End. ``` + -- cgit v1.2.3 From f894add86a84b378529b53813fb28fb31efe9628 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 4 Oct 2018 12:34:19 -0700 Subject: [julia/en] fix for #1483 --- julia.html.markdown | 154 ++++++++++++++++++++++++++-------------------------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 15c09da4..839e414d 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -114,12 +114,12 @@ println("I'm Julia. Nice to meet you!") # => I'm Julia. Nice to meet you! #################################################### # You don't declare variables before assigning to them. -some_var = 5 # => 5 -some_var # => 5 +someVar = 5 # => 5 +someVar # => 5 # Accessing a previously unassigned variable is an error try - some_other_var # => ERROR: UndefVarError: some_other_var not defined + someOtherVar # => ERROR: UndefVarError: someOtherVar not defined catch e println(e) end @@ -286,62 +286,62 @@ d # => 5 e # => 4 # Dictionaries store mappings -empty_dict = Dict() # => Dict{Any,Any} with 0 entries +emptyDict = Dict() # => Dict{Any,Any} with 0 entries # You can create a dictionary using a literal -filled_dict = Dict("one" => 1, "two" => 2, "three" => 3) +filledDict = Dict("one" => 1, "two" => 2, "three" => 3) # => Dict{String,Int64} with 3 entries: # => "two" => 2, "one" => 1, "three" => 3 # Look up values with [] -filled_dict["one"] # => 1 +filledDict["one"] # => 1 # Get all keys -keys(filled_dict) +keys(filledDict) # => Base.KeySet for a Dict{String,Int64} with 3 entries. Keys: # => "two", "one", "three" # Note - dictionary keys are not sorted or in the order you inserted them. # Get all values -values(filled_dict) +values(filledDict) # => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: # => 2, 1, 3 # Note - Same as above regarding key ordering. # Check for existence of keys in a dictionary with in, haskey -in(("one" => 1), filled_dict) # => true -in(("two" => 3), filled_dict) # => false -haskey(filled_dict, "one") # => true -haskey(filled_dict, 1) # => false +in(("one" => 1), filledDict) # => true +in(("two" => 3), filledDict) # => false +haskey(filledDict, "one") # => true +haskey(filledDict, 1) # => false # Trying to look up a non-existent key will raise an error try - filled_dict["four"] # => ERROR: KeyError: key "four" not found + filledDict["four"] # => ERROR: KeyError: key "four" not found catch e println(e) end # Use the get method to avoid that error by providing a default value -# get(dictionary, key, default_value) -get(filled_dict, "one", 4) # => 1 -get(filled_dict, "four", 4) # => 4 +# get(dictionary, key, defaultValue) +get(filledDict, "one", 4) # => 1 +get(filledDict, "four", 4) # => 4 # Use Sets to represent collections of unordered, unique values -empty_set = Set() # => Set(Any[]) +emptySet = Set() # => Set(Any[]) # Initialize a set with values -filled_set = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) +filledSet = Set([1, 2, 2, 3, 4]) # => Set([4, 2, 3, 1]) # Add more values to a set -push!(filled_set, 5) # => Set([4, 2, 3, 5, 1]) +push!(filledSet, 5) # => Set([4, 2, 3, 5, 1]) # Check if the values are in the set -in(2, filled_set) # => true -in(10, filled_set) # => false +in(2, filledSet) # => true +in(10, filledSet) # => false # There are functions for set intersection, union, and difference. -other_set = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) -intersect(filled_set, other_set) # => Set([4, 3, 5]) -union(filled_set, other_set) # => Set([4, 2, 3, 5, 6, 1]) +otherSet = Set([3, 4, 5, 6]) # => Set([4, 3, 5, 6]) +intersect(filledSet, otherSet) # => Set([4, 3, 5]) +union(filledSet, otherSet) # => Set([4, 2, 3, 5, 6, 1]) setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) #################################################### @@ -349,15 +349,15 @@ setdiff(Set([1,2,3,4]), Set([2,3,5])) # => Set([4, 1]) #################################################### # Let's make a variable -some_var = 5 +someVar = 5 # Here is an if statement. Indentation is not meaningful in Julia. -if some_var > 10 - println("some_var is totally bigger than 10.") -elseif some_var < 10 # This elseif clause is optional. - println("some_var is smaller than 10.") +if someVar > 10 + println("someVar is totally bigger than 10.") +elseif someVar < 10 # This elseif clause is optional. + println("someVar is smaller than 10.") else # The else clause is optional too. - println("some_var is indeed 10.") + println("someVar is indeed 10.") end # => prints "some var is smaller than 10" @@ -434,8 +434,8 @@ add(5, 6) # => 11 # Compact assignment of functions -f_add(x, y) = x + y # => f_add (generic function with 1 method) -f_add(3, 4) # => 7 +fAdd(x, y) = x + y # => fAdd (generic function with 1 method) +fAdd(3, 4) # => 7 # Function can also return multiple values as tuple fn(x, y) = x + y, x - y # => fn (generic function with 1 method) @@ -478,67 +478,67 @@ catch e end # You can define functions that take keyword arguments -function keyword_args(;k1=4, name2="hello") # note the ; +function keywordArgs(;k1=4, name2="hello") # note the ; return Dict("k1" => k1, "name2" => name2) end -# => keyword_args (generic function with 1 method) +# => keywordArgs (generic function with 1 method) -keyword_args(name2="ness") # => ["name2"=>"ness", "k1"=>4] -keyword_args(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] -keyword_args() # => ["name2"=>"hello", "k1"=>4] +keywordArgs(name2="ness") # => ["name2"=>"ness", "k1"=>4] +keywordArgs(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] +keywordArgs() # => ["name2"=>"hello", "k1"=>4] # You can combine all kinds of arguments in the same function -function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") - println("normal arg: $normal_arg") - println("optional arg: $optional_positional_arg") - println("keyword arg: $keyword_arg") +function allTheArgs(normalArg, optionalPositionalArg=2; keywordArg="foo") + println("normal arg: $normalArg") + println("optional arg: $optionalPositionalArg") + println("keyword arg: $keywordArg") end -# => all_the_args (generic function with 2 methods) +# => allTheArgs (generic function with 2 methods) -all_the_args(1, 3, keyword_arg=4) +allAheArgs(1, 3, keywordArg=4) # => normal arg: 1 # => optional arg: 3 # => keyword arg: 4 # Julia has first class functions -function create_adder(x) +function createAdder(x) adder = function (y) return x + y end return adder end -# => create_adder (generic function with 1 method) +# => createAdder (generic function with 1 method) # This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true -# This function is identical to create_adder implementation above. -function create_adder(x) +# This function is identical to createAdder implementation above. +function createAdder(x) y -> x + y end -# => create_adder (generic function with 1 method) +# => createAdder (generic function with 1 method) # You can also name the internal function, if you want -function create_adder(x) +function createAdder(x) function adder(y) x + y end adder end -# => create_adder (generic function with 1 method) +# => createAdder (generic function with 1 method) -add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) +add10 = createAdder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) # (generic function with 1 method) -add_10(3) # => 13 +add10(3) # => 13 # There are built-in higher order functions -map(add_10, [1,2,3]) # => [11, 12, 13] +map(add10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions -[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[add10(i) for i = [1, 2, 3]] # => [11, 12, 13] +[add10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### @@ -616,7 +616,7 @@ supertype(SubString) # => AbstractString # <: is the subtyping operator struct Lion <: Cat # Lion is a subtype of Cat - mane_color + maneColor roar::AbstractString end @@ -627,7 +627,7 @@ Lion(roar::AbstractString) = Lion("green", roar) # This is an outer constructor because it's outside the type definition struct Panther <: Cat # Panther is also a subtype of Cat - eye_color + eyeColor Panther() = new("green") # Panthers will only have this constructor, and no default constructor. end @@ -669,14 +669,14 @@ Lion <: Cat # => true Panther <: Cat # => true # Defining a function that takes Cats -function pet_cat(cat::Cat) +function petCat(cat::Cat) println("The cat says $(meow(cat))") end -# => pet_cat (generic function with 1 method) +# => petCat (generic function with 1 method) -pet_cat(Lion("42")) # => The cat says 42 +petCat(Lion("42")) # => The cat says 42 try - pet_cat(tigger) # => ERROR: MethodError: no method matching pet_cat(::Tiger) + petCat(tigger) # => ERROR: MethodError: no method matching petCat(::Tiger) catch e println(e) end @@ -695,7 +695,7 @@ fight(tigger, Panther()) # => The orange tiger wins! fight(tigger, Lion("ROAR")) # => The orange tiger wins! # Let's change the behavior when the Cat is specifically a Lion -fight(t::Tiger, l::Lion) = println("The $(l.mane_color)-maned lion wins!") +fight(t::Tiger, l::Lion) = println("The $(l.maneColor)-maned lion wins!") # => fight (generic function with 2 methods) fight(tigger, Panther()) # => The orange tiger wins! @@ -744,14 +744,14 @@ fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie # Under the hood # You can take a look at the llvm and the assembly code generated. -square_area(l) = l * l # square_area (generic function with 1 method) +squareArea(l) = l * l # squareArea (generic function with 1 method) -square_area(5) # => 25 +squareArea(5) # => 25 -# What happens when we feed square_area an integer? -code_native(square_area, (Int32,), syntax = :intel) +# What happens when we feed squareArea an integer? +codeNative(squareArea, (Int32,), syntax = :intel) # .text - # ; Function square_area { + # ; Function squareArea { # ; Location: REPL[116]:1 # Prologue # push rbp # mov rbp, rsp @@ -765,9 +765,9 @@ code_native(square_area, (Int32,), syntax = :intel) # nop dword ptr [rax + rax] # ;} -code_native(square_area, (Float32,), syntax = :intel) +codeNative(squareArea, (Float32,), syntax = :intel) # .text - # ; Function square_area { + # ; Function squareArea { # ; Location: REPL[116]:1 # push rbp # mov rbp, rsp @@ -780,9 +780,9 @@ code_native(square_area, (Float32,), syntax = :intel) # nop word ptr [rax + rax] # ;} -code_native(square_area, (Float64,), syntax = :intel) +codeNative(squareArea, (Float64,), syntax = :intel) # .text - # ; Function square_area { + # ; Function squareArea { # ; Location: REPL[116]:1 # push rbp # mov rbp, rsp @@ -798,12 +798,12 @@ code_native(square_area, (Float64,), syntax = :intel) # Note that julia will use floating point instructions if any of the # arguments are floats. # Let's calculate the area of a circle -circle_area(r) = pi * r * r # circle_area (generic function with 1 method) -circle_area(5) # 78.53981633974483 +circleArea(r) = pi * r * r # circleArea (generic function with 1 method) +circleArea(5) # 78.53981633974483 -code_native(circle_area, (Int32,), syntax = :intel) +codeNative(circleArea, (Int32,), syntax = :intel) # .text - # ; Function circle_area { + # ; Function circleArea { # ; Location: REPL[121]:1 # push rbp # mov rbp, rsp @@ -832,9 +832,9 @@ code_native(circle_area, (Int32,), syntax = :intel) # nop dword ptr [rax] # ;} -code_native(circle_area, (Float64,), syntax = :intel) +codeNative(circleArea, (Float64,), syntax = :intel) # .text - # ; Function circle_area { + # ; Function circleArea { # ; Location: REPL[121]:1 # push rbp # mov rbp, rsp -- cgit v1.2.3 From 3499b8358988307eb97481427e345c8fa94e57fc Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 4 Oct 2018 15:51:04 -0700 Subject: [julia/en] camelCase functions => snake_case --- julia.html.markdown | 74 ++++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 839e414d..7914f154 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -434,8 +434,8 @@ add(5, 6) # => 11 # Compact assignment of functions -fAdd(x, y) = x + y # => fAdd (generic function with 1 method) -fAdd(3, 4) # => 7 +f_add(x, y) = x + y # => f_add (generic function with 1 method) +f_add(3, 4) # => 7 # Function can also return multiple values as tuple fn(x, y) = x + y, x - y # => fn (generic function with 1 method) @@ -478,56 +478,56 @@ catch e end # You can define functions that take keyword arguments -function keywordArgs(;k1=4, name2="hello") # note the ; +function keyword_args(;k1=4, name2="hello") # note the ; return Dict("k1" => k1, "name2" => name2) end -# => keywordArgs (generic function with 1 method) +# => keyword_args (generic function with 1 method) -keywordArgs(name2="ness") # => ["name2"=>"ness", "k1"=>4] -keywordArgs(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] -keywordArgs() # => ["name2"=>"hello", "k1"=>4] +keyword_args(name2="ness") # => ["name2"=>"ness", "k1"=>4] +keyword_args(k1="mine") # => ["name2"=>"hello", "k1"=>"mine"] +keyword_args() # => ["name2"=>"hello", "k1"=>4] # You can combine all kinds of arguments in the same function -function allTheArgs(normalArg, optionalPositionalArg=2; keywordArg="foo") +function all_the_args(normalArg, optionalPositionalArg=2; keywordArg="foo") println("normal arg: $normalArg") println("optional arg: $optionalPositionalArg") println("keyword arg: $keywordArg") end -# => allTheArgs (generic function with 2 methods) +# => all_the_args (generic function with 2 methods) -allAheArgs(1, 3, keywordArg=4) +all_the_args(1, 3, keywordArg=4) # => normal arg: 1 # => optional arg: 3 # => keyword arg: 4 # Julia has first class functions -function createAdder(x) +function create_adder(x) adder = function (y) return x + y end return adder end -# => createAdder (generic function with 1 method) +# => create_adder (generic function with 1 method) # This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true -# This function is identical to createAdder implementation above. -function createAdder(x) +# This function is identical to create_adder implementation above. +function create_adder(x) y -> x + y end -# => createAdder (generic function with 1 method) +# => create_adder (generic function with 1 method) # You can also name the internal function, if you want -function createAdder(x) +function create_adder(x) function adder(y) x + y end adder end -# => createAdder (generic function with 1 method) +# => create_adder (generic function with 1 method) -add10 = createAdder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) +add10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) # (generic function with 1 method) add10(3) # => 13 @@ -669,14 +669,14 @@ Lion <: Cat # => true Panther <: Cat # => true # Defining a function that takes Cats -function petCat(cat::Cat) +function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end -# => petCat (generic function with 1 method) +# => pet_cat (generic function with 1 method) -petCat(Lion("42")) # => The cat says 42 +pet_cat(Lion("42")) # => The cat says 42 try - petCat(tigger) # => ERROR: MethodError: no method matching petCat(::Tiger) + pet_cat(tigger) # => ERROR: MethodError: no method matching pet_cat(::Tiger) catch e println(e) end @@ -744,14 +744,14 @@ fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie # Under the hood # You can take a look at the llvm and the assembly code generated. -squareArea(l) = l * l # squareArea (generic function with 1 method) +square_area(l) = l * l # square_area (generic function with 1 method) -squareArea(5) # => 25 +square_area(5) # => 25 -# What happens when we feed squareArea an integer? -codeNative(squareArea, (Int32,), syntax = :intel) +# What happens when we feed square_area an integer? +codeNative(square_area, (Int32,), syntax = :intel) # .text - # ; Function squareArea { + # ; Function square_area { # ; Location: REPL[116]:1 # Prologue # push rbp # mov rbp, rsp @@ -765,9 +765,9 @@ codeNative(squareArea, (Int32,), syntax = :intel) # nop dword ptr [rax + rax] # ;} -codeNative(squareArea, (Float32,), syntax = :intel) +codeNative(square_area, (Float32,), syntax = :intel) # .text - # ; Function squareArea { + # ; Function square_area { # ; Location: REPL[116]:1 # push rbp # mov rbp, rsp @@ -780,9 +780,9 @@ codeNative(squareArea, (Float32,), syntax = :intel) # nop word ptr [rax + rax] # ;} -codeNative(squareArea, (Float64,), syntax = :intel) +codeNative(square_area, (Float64,), syntax = :intel) # .text - # ; Function squareArea { + # ; Function square_area { # ; Location: REPL[116]:1 # push rbp # mov rbp, rsp @@ -798,12 +798,12 @@ codeNative(squareArea, (Float64,), syntax = :intel) # Note that julia will use floating point instructions if any of the # arguments are floats. # Let's calculate the area of a circle -circleArea(r) = pi * r * r # circleArea (generic function with 1 method) -circleArea(5) # 78.53981633974483 +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 -codeNative(circleArea, (Int32,), syntax = :intel) +codeNative(circle_area, (Int32,), syntax = :intel) # .text - # ; Function circleArea { + # ; Function circle_area { # ; Location: REPL[121]:1 # push rbp # mov rbp, rsp @@ -832,9 +832,9 @@ codeNative(circleArea, (Int32,), syntax = :intel) # nop dword ptr [rax] # ;} -codeNative(circleArea, (Float64,), syntax = :intel) +codeNative(circle_area, (Float64,), syntax = :intel) # .text - # ; Function circleArea { + # ; Function circle_area { # ; Location: REPL[121]:1 # push rbp # mov rbp, rsp -- cgit v1.2.3 From 7bd6f99b6b85ee9977be9f1212a8799876e5743c Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Thu, 4 Oct 2018 15:55:35 -0700 Subject: [julia/en] snake_case one more function name that slipped past --- julia.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 7914f154..0bb629d3 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -527,18 +527,18 @@ function create_adder(x) end # => create_adder (generic function with 1 method) -add10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) +add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) # (generic function with 1 method) -add10(3) # => 13 +add_10(3) # => 13 # There are built-in higher order functions -map(add10, [1,2,3]) # => [11, 12, 13] +map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions -[add10(i) for i = [1, 2, 3]] # => [11, 12, 13] -[add10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i = [1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -- cgit v1.2.3 From 34183aa023d64173c07d2da81f93d2da1a9f59f0 Mon Sep 17 00:00:00 2001 From: Den Patin Date: Fri, 5 Oct 2018 18:00:53 +0300 Subject: Add Russian translation for Crystal --- ru-ru/crystal-ru.html.markdown | 584 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 584 insertions(+) create mode 100644 ru-ru/crystal-ru.html.markdown diff --git a/ru-ru/crystal-ru.html.markdown b/ru-ru/crystal-ru.html.markdown new file mode 100644 index 00000000..e54926d2 --- /dev/null +++ b/ru-ru/crystal-ru.html.markdown @@ -0,0 +1,584 @@ +--- +language: crystal +filename: learncrystal-ru.cr +contributors: + - ["Vitalii Elenhaupt", "http://veelenga.com"] + - ["Arnaud Fernandés", "https://github.com/TechMagister/"] +translators: + - ["Den Patin", "https://github.com/denpatin"] +lang: ru-ru +--- + +```crystal +# — так начинается комментарий + + +# Всё является объектом +nil.class #=> Nil +100.class #=> Int32 +true.class #=> Bool + +# Возвращают false только nil, false и пустые указатели +!nil #=> true : Bool +!false #=> true : Bool +!0 #=> false : Bool + + +# Целые числа + +1.class #=> Int32 + +# Четыре типа целых чисел со знаком +1_i8.class #=> Int8 +1_i16.class #=> Int16 +1_i32.class #=> Int32 +1_i64.class #=> Int64 + +# Четыре типа целых чисел без знака +1_u8.class #=> UInt8 +1_u16.class #=> UInt16 +1_u32.class #=> UInt32 +1_u64.class #=> UInt64 + +2147483648.class #=> Int64 +9223372036854775808.class #=> UInt64 + +# Двоичные числа +0b1101 #=> 13 : Int32 + +# Восьмеричные числа +0o123 #=> 83 : Int32 + +# Шестнадцатеричные числа +0xFE012D #=> 16646445 : Int32 +0xfe012d #=> 16646445 : Int32 + +# Числа с плавающей точкой + +1.0.class #=> Float64 + +# Два типа чисел с плавающей запятой +1.0_f32.class #=> Float32 +1_f32.class #=> Float32 + +1e10.class #=> Float64 +1.5e10.class #=> Float64 +1.5e-7.class #=> Float64 + + +# Символьные литералы + +'a'.class #=> Char + +# Восьмеричный код символа +'\101' #=> 'A' : Char + +# Код символа Unicode +'\u0041' #=> 'A' : Char + + +# Строки + +"s".class #=> String + +# Строки неизменяемы +s = "hello, " #=> "hello, " : String +s.object_id #=> 134667712 : UInt64 +s += "Crystal" #=> "hello, Crystal" : String +s.object_id #=> 142528472 : UInt64 + +# Поддерживается интерполяция строк +"sum = #{1 + 2}" #=> "sum = 3" : String + +# Поддерживается многострочность +"This is + multiline string" + +# Строка с двойными кавычками +%(hello "world") #=> "hello \"world\"" + + +# Символы — константы без значения, определяемые только именем. Часто +# используются вместо часто используемых строк для лучшей производительности. +# На внутреннем уровне они представлены как Int32. + +:symbol.class #=> Symbol + +sentence = :question? # :"question?" : Symbol + +sentence == :question? #=> true : Bool +sentence == :exclamation! #=> false : Bool +sentence == "question?" #=> false : Bool + + +# Массивы + +[1, 2, 3].class #=> Array(Int32) +[1, "hello", 'x'].class #=> Array(Int32 | String | Char) + +# При объявлении пустого массива необходимо указать тип его элементов +[] # Syntax error: for empty arrays use '[] of ElementType' +[] of Int32 #=> [] : Array(Int32) +Array(Int32).new #=> [] : Array(Int32) + +# Элементы внутри массива имеют свои индексы +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] : Array(Int32) +array[0] #=> 1 : Int32 +array[10] # raises IndexError +array[-6] # raises IndexError +array[10]? #=> nil : (Int32 | Nil) +array[-6]? #=> nil : (Int32 | Nil) + +# Можно получать элементы по индексу с конца +array[-1] #=> 5 + +# С начала и с указанием размера итогового массива +array[2, 3] #=> [3, 4, 5] + +# Или посредством указания диапазона +array[1..3] #=> [2, 3, 4] + +# Добавление в массив +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# Удаление элемента из конца массива +array.pop #=> 6 +array #=> [1, 2, 3, 4, 5] + +# Удаление элемента из начала массива +array.shift #=> 1 +array #=> [2, 3, 4, 5] + +# Проверка на наличие элемента в массиве +array.includes? 3 #=> true + +# Синтаксический сахар для массива строк и символов +%w(one two three) #=> ["one", "two", "three"] : Array(String) +%i(one two three) #=> [:one, :two, :three] : Array(Symbol) + +# Массивоподобный синтаксис используется и для других типов, только если для +# них определены методы .new и #<< +set = Set{1, 2, 3} #=> [1, 2, 3] +set.class #=> Set(Int32) + +# Вышеприведенное эквивалентно следующему +set = Set(typeof(1, 2, 3)).new +set << 1 +set << 2 +set << 3 + + +# Хэши + +{1 => 2, 3 => 4}.class #=> Hash(Int32, Int32) +{1 => 2, 'a' => 3}.class #=> Hash(Int32 | Char, Int32) + +# При объявлении пустого хэша необходимо указать типы ключа и значения +{} # Syntax error +{} of Int32 => Int32 # {} +Hash(Int32, Int32).new # {} + +# Значения в хэше легко найти по ключу +hash = {"color" => "green", "number" => 5} +hash["color"] #=> "green" +hash["no_such_key"] #=> Missing hash key: "no_such_key" (KeyError) +hash["no_such_key"]? #=> nil + +# Проверка наличия ключа в хэше +hash.has_key? "color" #=> true + +# Синтаксический сахар для символьных и строковых ключей +{key1: 'a', key2: 'b'} # {:key1 => 'a', :key2 => 'b'} +{"key1": 'a', "key2": 'b'} # {"key1" => 'a', "key2" => 'b'} + +# Хэшеподобный синтаксис используется и для других типов, только если для них +# определены методы .new и #[]= +class MyType + def []=(key, value) + puts "do stuff" + end +end + +MyType{"foo" => "bar"} + +# Вышеприведенное эквивалентно следующему +tmp = MyType.new +tmp["foo"] = "bar" +tmp + + +# Диапазоны + +1..10 #=> Range(Int32, Int32) +Range.new(1, 10).class #=> Range(Int32, Int32) + +# Включающий и исключающий диапазоны +(3..5).to_a #=> [3, 4, 5] +(3...5).to_a #=> [3, 4] + +# Проверка на вхождение в диапазон +(1..8).includes? 2 #=> true + + +# Кортежи +# Неизменяемые последовательности фиксированного размера, содержащие, +# как правило, элементы разных типов + +{1, "hello", 'x'}.class #=> Tuple(Int32, String, Char) + +# Доступ к элементам осуществляется по индексу +tuple = {:key1, :key2} +tuple[1] #=> :key2 +tuple[2] #=> syntax error : Index out of bound + +# Элементы кортежей можно попарно присвоить переменным +a, b, c = {:a, 'b', "c"} +a #=> :a +b #=> 'b' +c #=> "c" + + +# Процедуры +# Указатели на функцию с необязательным содержимым (замыкание). +# Обычно создаётся с помощью специального литерала -> + +proc = ->(x : Int32) { x.to_s } +proc.class # Proc(Int32, String) +# Или посредством метода .new +Proc(Int32, String).new { |x| x.to_s } + +# Вызываются посредством метода .call +proc.call 10 #=> "10" + + +# Управляющие операторы + +if true + "if statement" +elsif false + "else-if, optional" +else + "else, also optional" +end + +puts "if as a suffix" if true + +# if как часть выражения +a = if 2 > 1 + 3 + else + 4 + end + +a #=> 3 + +# Тернарный if +a = 1 > 2 ? 3 : 4 #=> 4 + +# Оператор выбора +cmd = "move" + +action = case cmd + when "create" + "Creating..." + when "copy" + "Copying..." + when "move" + "Moving..." + when "delete" + "Deleting..." +end + +action #=> "Moving..." + + +# Циклы + +index = 0 +while index <= 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +index = 0 +until index > 3 + puts "Index: #{index}" + index += 1 +end +# Index: 0 +# Index: 1 +# Index: 2 +# Index: 3 + +# Но лучше использовать each +(1..3).each do |index| + puts "Index: #{index}" +end +# Index: 1 +# Index: 2 +# Index: 3 + +# Тип переменной зависит от типа выражения +if a < 3 + a = "hello" +else + a = true +end +typeof a #=> (Bool | String) + +if a && b + # здесь гарантируется, что и a, и b — не nil +end + +if a.is_a? String + a.class #=> String +end + + +# Методы + +def double(x) + x * 2 +end + +# Методы (а также любые блоки) всегда возвращают значение последнего выражения +double(2) #=> 4 + +# Скобки можно опускать, если вызов метода не вносит двусмысленности +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Параметры методов перечисляются через запятую +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + + +# yield + +# У всех методов есть неявный необязательный параметр блока, который можно +# вызвать ключевым словом yield + +def surround + puts '{' + yield + puts '}' +end + +surround { puts "hello world" } + +# { +# hello world +# } + +# Методу можно передать блок +# & — ссылка на переданный блок +def guests(&block) + block.call "some_argument" +end + +# Методу можно передать список параметров, доступ к ним будет как к массиву +# Для этого используется оператор * +def guests(*array) + array.each { |guest| puts guest } +end + +# Если метод возвращает массив, можно попарно присвоить значение каждого из его +# элементов переменным +def foods + ["pancake", "sandwich", "quesadilla"] +end +breakfast, lunch, dinner = foods +breakfast #=> "pancake" +dinner #=> "quesadilla" + +# По соглашению название методов, возвращающих булево значение, должно +# оканчиваться вопросительным знаком +5.even? # false +5.odd? # true + +# Если название метода оканчивается восклицательным знаком, по соглашению это +# означает, что метод делает что-то необратимое, например изменяет получателя. +# Некоторые методы имеют две версии: "опасную" версию с !, которая что-то +# меняет, и "безопасную", которая просто возвращает новое значение +company_name = "Dunder Mifflin" +company_name.gsub "Dunder", "Donald" #=> "Donald Mifflin" +company_name #=> "Dunder Mifflin" +company_name.gsub! "Dunder", "Donald" +company_name #=> "Donald Mifflin" + + +# Классы +# Определяются с помощью ключевого слова class + +class Human + + # Переменная класса является общей для всех экземпляров этого класса + @@species = "H. sapiens" + + # Объявление типа переменной name экземпляра класса + @name : String + + # Базовый конструктор + # Значением первого параметра инициализируем переменную @name. + # То же делаем и со вторым параметром — переменная @age. В случае, если мы + # не передаём второй параметр, для инициализации @age будет взято значение + # по умолчанию (в данном случае — 0) + def initialize(@name, @age = 0) + end + + # Базовый метод установки значения переменной + def name=(name) + @name = name + end + + # Базовый метод получения значения переменной + def name + @name + end + + # Синтаксический сахар одновременно для двух методов выше + property :name + + # А также по отдельности + getter :name + setter :name + + # Метод класса определяется ключевым словом self, чтобы его можно было + # различить с методом экземпляра класса. Такой метод можно вызвать только + # на уровне класса, а не экземпляра. + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# Создание экземпляра класса +jim = Human.new("Jim Halpert") + +dwight = Human.new("Dwight K. Schrute") + +# Вызов методов экземпляра класса +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Вызов метода класса +Human.say("Hi") #=> выведет "Hi" и вернёт nil + +# Переменные экземпляра класса (@) видно только в пределах экземпляра +class TestClass + @var = "I'm an instance var" +end + +# Переменные класса (@) видны как в экземплярах класса, так и в самом классе +class TestClass + @@var = "I'm a class var" +end + +# Переменные с большой буквы — это константы +Var = "I'm a constant" +Var = "can't be updated" # Error: already initialized constant Var + +# Примеры + +# Базовый класс +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Класс-потомок +class Worker < Human +end + +Human.foo #=> 0 +Worker.foo #=> 0 + +Human.foo = 2 #=> 2 +Worker.foo #=> 0 + +Worker.foo = 3 #=> 3 +Human.foo #=> 2 +Worker.foo #=> 3 + +module ModuleExample + def foo + "foo" + end +end + +# Подключение модуля в класс добавляет его методы в экземпляр класса +# Расширение модуля добавляет его методы в сам класс + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => undefined method 'foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => undefined method 'foo' for Book + + +# Обработка исключений + +# Создание пользовательского типа исключения +class MyException < Exception +end + +# Ещё одного +class MyAnotherException < Exception; end + +ex = begin + raise MyException.new +rescue ex1 : IndexError + "ex1" +rescue ex2 : MyException | MyAnotherException + "ex2" +rescue ex3 : Exception + "ex3" +rescue ex4 # без указания конкретного типа исключения будут "отлавливаться" все + "ex4" +end + +ex #=> "ex2" + +``` + +## Дополнительная информация + +### На русском + +- [Официальная документация](http://ru.crystal-lang.org/docs/) + +### На английском + +- [Official Documentation](http://crystal-lang.org/) -- cgit v1.2.3 From e89ab955d8f599f70d6c331aa6c16040e4b7e4a3 Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Sat, 6 Oct 2018 19:42:59 +0530 Subject: Initial Commit for Opencv --- opencv.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 opencv.html.markdown diff --git a/opencv.html.markdown b/opencv.html.markdown new file mode 100644 index 00000000..75ef7168 --- /dev/null +++ b/opencv.html.markdown @@ -0,0 +1,15 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Yogesh Ojha", "http://github.com/yogeshojha"] +--- +# Opencv + +Further Reading: + +An up-to-date language reference can be found at + + +Additional resources may be found at + -- cgit v1.2.3 From dcaec93a0e4b629bb07fcdd72dcb4c71b0d52530 Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Sat, 6 Oct 2018 20:09:15 +0530 Subject: Update on opencv until read image --- opencv.html.markdown | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 75ef7168..7e048df5 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -1,15 +1,52 @@ --- -language: c++ -filename: learncpp.cpp +language: c++/python +filename: learnopencv.py contributors: - ["Yogesh Ojha", "http://github.com/yogeshojha"] --- -# Opencv +### Opencv + +OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. +Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). +Opencv currently supports wide variety of languages like, C++, Python, Java etc + +#### Installation +Please refer to these articles for installation of OpenCV on your computer. +* Windows Installation Instructions: + + +* Mac Installation Instructions (High Sierra): +https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a + +* Linux Installation Instructions (Ubuntu 18.04): + + +### Here we will be focusing on python implementation of OpenCV + +* __Reading image in OpenCV__ +``` +import cv2 +img = cv2.imread('cat.jpg') +# Simple isn't it? +# Displaying the image +# imshow() function is used to display the image +cv2.imshow('Image',img) +# Your first arguement is the title of the window and second parameter is image +# If you are getting error, Object Type None, your image path may be wrong. Please recheck the pack to the image +cv2.waitKey(0) +# waitKey() is a keyboard binding function and takes arguement in milliseconds. For GUI events you MUST use waitKey() function. +``` Further Reading: An up-to-date language reference can be found at - + Additional resources may be found at + +Good OpenCv Tutorials + + + + -- cgit v1.2.3 From 9169335e5bdf66916619a2565ba56235bc4cfb00 Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Sat, 6 Oct 2018 22:19:52 +0530 Subject: Drawing functions added --- opencv.html.markdown | 63 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 7e048df5..45046af6 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -1,5 +1,5 @@ --- -language: c++/python +language: python filename: learnopencv.py contributors: - ["Yogesh Ojha", "http://github.com/yogeshojha"] @@ -23,11 +23,11 @@ https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-pyt ### Here we will be focusing on python implementation of OpenCV -* __Reading image in OpenCV__ ``` +# Reading image in OpenCV import cv2 img = cv2.imread('cat.jpg') -# Simple isn't it? + # Displaying the image # imshow() function is used to display the image cv2.imshow('Image',img) @@ -35,10 +35,67 @@ cv2.imshow('Image',img) # If you are getting error, Object Type None, your image path may be wrong. Please recheck the pack to the image cv2.waitKey(0) # waitKey() is a keyboard binding function and takes arguement in milliseconds. For GUI events you MUST use waitKey() function. + +# Writing an image +cv2.imwrite('catgray.png',img) +# first arguement is the file name and second is the image + +# Convert image to grayscale +gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +# Capturing Video from Webcam +cap = cv2.VideoCapture(0) +#0 is your camera, if you have multiple camera, you need to enter their id +while(True): + # Capturing frame-by-frame + _, frame = cap.read() + cv2.imshow('Frame',frame) + # When user presses q -> quit + if cv2.waitKey(1) & 0xFF == ord('q'): + break +# Camera must be released +cap.release() + +# Playing Video from file +cap = cv2.VideoCapture('movie.mp4') +while(cap.isOpened()): + _, frame = cap.read() + # Play the video in grayscale + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + cv2.imshow('frame',gray) + if cv2.waitKey(1) & 0xFF == ord('q'): + break +cap.release() + +# Drawing The Line in OpenCV +# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +cv2.line(img,(0,0),(511,511),(255,0,0),5) + +# Drawing Rectangle +# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# thickness = -1 used for filling the rectangle +cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) + +# Drawing Circle +cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img,(200,90), 100, (0,0,255), -1) + +# Drawing Ellipse +cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) + +# Adding Text On Images +cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) + + +cv2.destroyAllWindows() +# destroyAllWindows() destroys all windows. If you wish to destroy specific window pass the exact name of window you created. ``` Further Reading: +OpenCV drawing Functions + + An up-to-date language reference can be found at -- cgit v1.2.3 From 8b1f80c472748359da442bd66232aae611610f50 Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Sat, 6 Oct 2018 22:33:37 +0530 Subject: added haar cascades, and image processing --- opencv.html.markdown | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 45046af6..4c52595e 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -86,13 +86,59 @@ cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) # Adding Text On Images cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) +# Blending Images +img1 = cv2.imread('cat.png') +img2 = cv2.imread('openCV.jpg') +dst = cv2.addWeighted(img1,0.5,img2,0.5,0) + +# Thresholding image +# Binary Thresholding +_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +# Adaptive Thresholding +adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) + +# Blur Image +# Gaussian Blur +blur = cv2.GaussianBlur(img,(5,5),0) +# Median Blur +medianBlur = cv2.medianBlur(img,5) + +# Canny Edge Detection +img = cv2.imread('cat.jpg',0) +edges = cv2.Canny(img,100,200) + +# Face Detection using Haar Cascades +# Download Haar Cascades from https://github.com/opencv/opencv/blob/master/data/haarcascades/ +import cv2 +import numpy as np +face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') +eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') + +img = cv2.imread('human.jpg') +gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +aces = face_cascade.detectMultiScale(gray, 1.3, 5) +for (x,y,w,h) in faces: + cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) + roi_gray = gray[y:y+h, x:x+w] + roi_color = img[y:y+h, x:x+w] + eyes = eye_cascade.detectMultiScale(roi_gray) + for (ex,ey,ew,eh) in eyes: + cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + +cv2.imshow('img',img) +cv2.waitKey(0) cv2.destroyAllWindows() -# destroyAllWindows() destroys all windows. If you wish to destroy specific window pass the exact name of window you created. +# destroyAllWindows() destroys all windows. +# If you wish to destroy specific window pass the exact name of window you created. ``` Further Reading: +Download Cascade from + + OpenCV drawing Functions -- cgit v1.2.3 From 9a8e722661c1afd0702e2174df54f8682b1fea44 Mon Sep 17 00:00:00 2001 From: Keith Miyake Date: Sat, 6 Oct 2018 23:43:50 -0700 Subject: [julia/en] divayprakash has an amazing eagle eye for function naming! --- julia.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 0bb629d3..2fe05c49 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -749,7 +749,7 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) # => 25 # What happens when we feed square_area an integer? -codeNative(square_area, (Int32,), syntax = :intel) +code_native(square_area, (Int32,), syntax = :intel) # .text # ; Function square_area { # ; Location: REPL[116]:1 # Prologue @@ -765,7 +765,7 @@ codeNative(square_area, (Int32,), syntax = :intel) # nop dword ptr [rax + rax] # ;} -codeNative(square_area, (Float32,), syntax = :intel) +code_native(square_area, (Float32,), syntax = :intel) # .text # ; Function square_area { # ; Location: REPL[116]:1 @@ -780,7 +780,7 @@ codeNative(square_area, (Float32,), syntax = :intel) # nop word ptr [rax + rax] # ;} -codeNative(square_area, (Float64,), syntax = :intel) +code_native(square_area, (Float64,), syntax = :intel) # .text # ; Function square_area { # ; Location: REPL[116]:1 @@ -801,7 +801,7 @@ codeNative(square_area, (Float64,), syntax = :intel) circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 -codeNative(circle_area, (Int32,), syntax = :intel) +code_native(circle_area, (Int32,), syntax = :intel) # .text # ; Function circle_area { # ; Location: REPL[121]:1 @@ -832,7 +832,7 @@ codeNative(circle_area, (Int32,), syntax = :intel) # nop dword ptr [rax] # ;} -codeNative(circle_area, (Float64,), syntax = :intel) +code_native(circle_area, (Float64,), syntax = :intel) # .text # ; Function circle_area { # ; Location: REPL[121]:1 -- cgit v1.2.3 From dc3842c2fc67b6dc0260726b7db22a2832cf7917 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 7 Oct 2018 15:10:11 -0700 Subject: Update textile.html.markdown --- textile.html.markdown | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/textile.html.markdown b/textile.html.markdown index d0785a91..2b81674a 100644 --- a/textile.html.markdown +++ b/textile.html.markdown @@ -30,7 +30,7 @@ written content published online. ## Comments -```textile +``` ###. Comments begin with three (3) '#' signs followed by a full-stop period '.'. Comments can span multiple lines until a blank line is reached. @@ -52,7 +52,7 @@ respected --> ## Paragraphs -```textile +``` ###. Paragraphs are a one or multiple adjacent lines of text separated by one or multiple blank lines. They can also be indicated explicitly with a 'p. ' @@ -126,7 +126,7 @@ text you want to be in that element by 'h#.' where # is the level 1-6. A blank line is required after headings. -```textile +``` h1. This is an

h2. This is an

@@ -144,7 +144,7 @@ h6. This is an

## Simple text styles -```textile +``` ###. Bold and strong text are indicated using asterisks: *This is strong text* @@ -182,7 +182,7 @@ This is -deleted- text and this is +inserted+ text. ## Lists -```textile +``` ###. Unordered lists can be made using asterisks '*' to indicate levels: * Item @@ -222,7 +222,7 @@ definition =: ## Code blocks -```textile +``` Code blocks use the 'bc.' shorthand: bc. This is code @@ -244,13 +244,13 @@ p. Indicate @inline code@ using the '@' symbol. Horizontal rules (`
`) are easily added with two hyphens -```textile +``` -- ``` ## Links -```textile +``` ###. Link text is in quotes, followed by a colon and the URL: "Link text":http://linkurl.com/ plain text. @@ -270,7 +270,7 @@ Multiple "references":txstyle to the "txstyle":txstyle website. ## Images -```textile +``` ###. Images can be included by surrounding its URL with exclamation marks (!) Alt text is included in parenthesis after the URL, and they can be linked too: @@ -284,7 +284,7 @@ Alt text is included in parenthesis after the URL, and they can be linked too: ## Footnotes and Endnotes -```textile +``` A footnote is indicated with the reference id in square brackets.[1] fn1. Footnote text with a "link":http://link.com. @@ -331,7 +331,7 @@ notelist!+. Notes with no backlinks to the citations, followed by ## Tables -```textile +``` ###. Tables are simple to define using the pipe '|' symbol | A | simple | table | row | @@ -403,7 +403,7 @@ A backslash \ is used for a column span: ``` or, for the same results -```textile +``` Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop @@ -414,13 +414,13 @@ Ugh this is so ugly | make it | stop ### Registered, Trademark, Copyright Symbols -```textile +``` RegisteredTrademark(r), Trademark(tm), Copyright (c) ``` ### Acronyms -```textile +``` ###. Acronym definitions can be provided in parentheses: EPA(Environmental Protection Agency) and CDC(Center for Disease Control) @@ -428,7 +428,7 @@ EPA(Environmental Protection Agency) and CDC(Center for Disease Control) ### Angle Brackets and Ampersand -```textile +``` ### Angled brackets < and > and ampersands & are automatically escaped: < => < > => > @@ -437,13 +437,13 @@ EPA(Environmental Protection Agency) and CDC(Center for Disease Control) ### Ellipses -```textile +``` p. Three consecutive periods are translated into ellipses...automatically ``` ### Em and En dashes -```textile +``` ###. En dashes (short) is a hyphen surrounded by spaces: This line uses an en dash to separate Oct - Nov 2018. @@ -457,7 +457,7 @@ That last hyphen between 'less' and 'used' is not converted between words. ## Fractions and other Math Symbols -```textile +``` One quarter: (1/4) => ¼ One half: (1/2) => ½ Three quarters: (3/4) => ¾ @@ -466,7 +466,7 @@ Plus/minus: (+/-) => ± ``` ### Multiplication/Dimension -```textile +``` p. Numbers separated by the letter 'x' translate to the multiplication or dimension symbol '×': 3 x 5 => 3 × 5 @@ -474,7 +474,7 @@ or dimension symbol '×': ### Quotes and Apostrophes -```textile +``` ###. Straight quotes and apostrophes are automatically converted to their curly equivalents: @@ -484,7 +484,7 @@ Leave them straight using '==' around the text: =="straight quotes"==. ## CSS -```textile +``` p{color:blue}. CSS Styles are enclosed in curly braces '{}' p(my-class). Classes are enclosed in parenthesis p(#my-id). IDs are enclosed in parentheses and prefaced with a pound '#'. @@ -492,7 +492,7 @@ p(#my-id). IDs are enclosed in parentheses and prefaced with a pound '#'. ## Spans and Divs -```textile +``` %spans% are enclosed in percent symbols div. Divs are indicated by the 'div.' shorthand ``` -- cgit v1.2.3 From cbab8774413633c80a35b2fcf74df76f569ffb1c Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 7 Oct 2018 22:40:41 -0700 Subject: Fix bom situation --- ru-ru/crystal-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/crystal-ru.html.markdown b/ru-ru/crystal-ru.html.markdown index e54926d2..87d12f23 100644 --- a/ru-ru/crystal-ru.html.markdown +++ b/ru-ru/crystal-ru.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: crystal filename: learncrystal-ru.cr contributors: -- cgit v1.2.3 From 7a415e2149e210783680e65154dcd55ede9dfbeb Mon Sep 17 00:00:00 2001 From: Qix Date: Mon, 8 Oct 2018 04:39:44 -0600 Subject: [rst/en] fix typo: tabless -> tables --- rst.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rst.html.markdown b/rst.html.markdown index fbf9a069..bfcb4e46 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -70,7 +70,7 @@ France Paris Japan Tokyo =========== ======== -More complex tabless can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) +More complex tables can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) There are multiple ways to make links: -- cgit v1.2.3 From 2a6ca9f3ff36203becd1cbeaf5e4a6878d85bc7e Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Mon, 8 Oct 2018 17:30:26 +0530 Subject: Update opencv.html.markdown --- opencv.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 4c52595e..aa26ecc0 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -1,5 +1,6 @@ --- -language: python +category: tool +tool: OpenCV filename: learnopencv.py contributors: - ["Yogesh Ojha", "http://github.com/yogeshojha"] -- cgit v1.2.3 From 215d688c0616f5023cab98b6b1ff9735581f03ec Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Mon, 8 Oct 2018 21:31:25 +0530 Subject: Update rst.html.markdown Clarify marking text as code --- rst.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rst.html.markdown b/rst.html.markdown index bfcb4e46..01595fe4 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -47,7 +47,7 @@ Title are underlined with equals signs too Subtitles with dashes --------------------- -You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. +You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``. Lists are as simple as in Markdown: -- cgit v1.2.3 From 6bdff7f79ac9d561763840ecf9554147a1a8ac4d Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Mon, 8 Oct 2018 12:09:51 -0400 Subject: Adds deprecation reminder for constant modifier in Solidity English documentation. --- solidity.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index 004c225e..c0074b33 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -111,6 +111,7 @@ contract SimpleBank { // CapWords /// @return The balance of the user // 'constant' prevents function from editing state variables; // allows function to run locally/off blockchain + // NOTE: 'constant' on functions is an alias to 'view', but this is deprecated and is planned to be dropped in version 0.5.0. function balance() constant public returns (uint) { return balances[msg.sender]; } -- cgit v1.2.3 From b230fbd52f2f1e657fd5ca384f88b0f1959d5809 Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Mon, 8 Oct 2018 12:17:24 -0400 Subject: Adds clarification for functions with multiple clauses. --- elixir.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index a74baa38..e82509e7 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -287,7 +287,11 @@ end PrivateMath.sum(1, 2) #=> 3 # PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) -# Function declarations also support guards and multiple clauses: +# Function declarations also support guards and multiple clauses. +# When a function with multiple clauses is called, the first function +# that satisfies the clause will be invoked. +# Example: invoking area({:circle, 3}) will call the second area +# function defined below, not the first: defmodule Geometry do def area({:rectangle, w, h}) do w * h -- cgit v1.2.3 From 3a48077c16b2a7f083cd096cf146e16b9bcebdb1 Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Mon, 8 Oct 2018 13:57:53 -0400 Subject: Fixes lambda calculus evaluation formula by fixing associativity --- lambda-calculus.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 72ed78ba..79dc20e7 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -55,7 +55,7 @@ Although lambda calculus traditionally supports only single parameter functions, we can create multi-parameter functions using a technique called [currying](https://en.wikipedia.org/wiki/Currying). -- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = x(y(z))` +- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = ((x y) z)` Sometimes `λxy.` is used interchangeably with: `λx.λy.` -- cgit v1.2.3 From 3f685318635b69d1492238378cd90c5908264b6c Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Tue, 9 Oct 2018 07:08:41 -0400 Subject: Fixes associativity issue in Lambda Calculus doc. --- lambda-calculus.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 79dc20e7..3d080de7 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -87,7 +87,7 @@ Using `IF`, we can define the basic boolean logic operators: `a NOT b` is equivalent to: `λa.IF a F T` -*Note: `IF a b c` is essentially saying: `IF(a(b(c)))`* +*Note: `IF a b c` is essentially saying: `IF((a b) c)`* ## Numbers: -- cgit v1.2.3 From e2fbb26b6ac1eda7df063f2936e08dd624bf38fc Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 9 Oct 2018 22:43:58 +0530 Subject: Fix error in unbound variable description, closes #2577 --- common-lisp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 28b5173b..73843436 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -181,8 +181,8 @@ nil ; false; also, the empty list: () ;;; You can also use unicode characters. (defparameter *AΛB* nil) -;;; Accessing a previously unbound variable is an undefined behavior, but -;;; possible. Don't do it. +;;; Accessing a previously unbound variable results in an UNBOUND-VARIABLE +;;; error, however it is defined behavior. Don't do it. ;;; You can create local bindings with LET. In the following snippet, `me` is ;;; bound to "dance with you" only within the (let ...). LET always returns -- cgit v1.2.3 From 3a0ffaa05dae6b570c582f7fd6ee3192e8caefb1 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 9 Oct 2018 22:49:47 +0530 Subject: Fix default make-array value, closes #2578 --- common-lisp.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 73843436..b12e50ca 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -284,7 +284,8 @@ nil ; false; also, the empty list: () ;;; To access the element at 1, 1, 1: (aref (make-array (list 2 2 2)) 1 1 1) ; => 0 - +;;; This value is implementation-defined: +;;; NIL on ECL, 0 on SBCL and CCL. ;;; Adjustable vectors -- cgit v1.2.3 From ff06f9cf993c79b843008a641abb92e183cff285 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 9 Oct 2018 22:59:19 +0530 Subject: Fix defer wording, closes #2673 --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index df677894..ae99535b 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -277,7 +277,8 @@ func sentenceFactory(mystring string) func(before, after string) string { } func learnDefer() (ok bool) { - // Deferred statements are executed just before the function returns. + // A defer statement pushes a function call onto a list. The list of saved + // calls is executed AFTER the surrounding function returns. defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // Defer is commonly used to close a file, so the function closing the -- cgit v1.2.3 From 4311e3866710ed02cef29cd62d66c123b9300f14 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 9 Oct 2018 23:10:17 +0530 Subject: Make description of static keyword stronger, closes #2848 --- c.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/c.html.markdown b/c.html.markdown index bf93dcf5..7975a1c2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -605,6 +605,14 @@ static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; } +// The static keyword makes a variable inaccessible to code outside the +// compilation unit. (On almost all systems, a "compilation unit" is a .c +// file.) static can apply both to global (to the compilation unit) variables, +// functions, and function-local variables. When using static with +// function-local variables, the variable is effectively global and retains its +// value across function calls, but is only accessible within the function it +// is declared in. Additionally, static variables are initialized to 0 if not +// declared with some other starting value. //**You may also declare functions as static to make them private** /////////////////////////////////////// -- cgit v1.2.3 From 31e4b9653966df83d5333419b80384933de9367a Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Wed, 10 Oct 2018 20:06:34 +0530 Subject: Made Necessary Changes on Markdown --- opencv.html.markdown | 45 +++++++++++++++------------------------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index aa26ecc0..7b61d2cd 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -13,18 +13,11 @@ Opencv currently supports wide variety of languages like, C++, Python, Java etc #### Installation Please refer to these articles for installation of OpenCV on your computer. -* Windows Installation Instructions: - - -* Mac Installation Instructions (High Sierra): -https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a - -* Linux Installation Instructions (Ubuntu 18.04): - - +* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows] +* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a] +* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv] ### Here we will be focusing on python implementation of OpenCV - -``` +```python # Reading image in OpenCV import cv2 img = cv2.imread('cat.jpg') @@ -135,22 +128,14 @@ cv2.destroyAllWindows() # If you wish to destroy specific window pass the exact name of window you created. ``` -Further Reading: - -Download Cascade from - - -OpenCV drawing Functions - - -An up-to-date language reference can be found at - - -Additional resources may be found at - - -Good OpenCv Tutorials - - - - +### Further Reading: + +* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades] +* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html] +* An up-to-date language reference can be found at [https://opencv.org] +* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV] +* Good OpenCv Tutorials + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html] + * [https://realpython.com/python-opencv-color-spaces] + * [https://pyimagesearch.com] + * [https://www.learnopencv.com] -- cgit v1.2.3 From 3dc029b2176bdf89b973f1bb8f6bc3e1a19d1f63 Mon Sep 17 00:00:00 2001 From: Abraham Toriz Cruz Date: Wed, 10 Oct 2018 09:40:26 -0500 Subject: Fixed and enhanced for python 3 Includes Spanish language corrections --- es-es/python3-es.html.markdown | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown index 05fd7065..342bb094 100644 --- a/es-es/python3-es.html.markdown +++ b/es-es/python3-es.html.markdown @@ -2,6 +2,7 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Categulario", "https://twitter.com/categulario"] translators: - ["Camilo Garrido", "http://twitter.com/hirohope"] lang: es-es @@ -14,8 +15,6 @@ Es básicamente pseudocódigo ejecutable. ¡Comentarios serán muy apreciados! Pueden contactarme en [@louiedinh](http://twitter.com/louiedinh) o louiedinh [at] [servicio de email de google] -Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser aplicable a Python 2.x. ¡Pronto un recorrido por Python 3! - ```python # Comentarios de una línea comienzan con una almohadilla (o signo gato) @@ -39,6 +38,8 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Excepto la división la cual por defecto retorna un número 'float' (número de coma flotante) 35 / 5 # => 7.0 +# Sin embargo también tienes disponible división entera +34 // 5 # => 6 # Cuando usas un float, los resultados son floats 3 * 2.0 # => 6.0 @@ -87,11 +88,14 @@ not False # => True # .format puede ser usaro para darle formato a los strings, así: "{} pueden ser {}".format("strings", "interpolados") -# Puedes repetir los argumentos de formateo para ahorrar tipeos. +# Puedes reutilizar los argumentos de formato si estos se repiten. "{0} sé ligero, {0} sé rápido, {0} brinca sobre la {1}".format("Jack", "vela") #=> "Jack sé ligero, Jack sé rápido, Jack brinca sobre la vela" # Puedes usar palabras claves si no quieres contar. -"{nombre} quiere comer {comida}".format(nombre="Bob", food="lasaña") #=> "Bob quiere comer lasaña" - +"{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") #=> "Bob quiere comer lasaña" +# También puedes interpolar cadenas usando variables en el contexto +nombre = 'Bob' +comida = 'Lasaña' +f'{nombre} quiere comer {comida}' #=> "Bob quiere comer lasaña" # None es un objeto None # => None @@ -101,12 +105,13 @@ None # => None "etc" is None #=> False None is None #=> True -# None, 0, y strings/listas/diccionarios vacíos(as) todos se evalúan como False. +# None, 0, y strings/listas/diccionarios/conjuntos vacíos(as) todos se evalúan como False. # Todos los otros valores son True bool(0) # => False bool("") # => False bool([]) #=> False bool({}) #=> False +bool(set()) #=> False #################################################### @@ -170,7 +175,7 @@ lista + otra_lista #=> [1, 2, 3, 4, 5, 6] - Nota: lista y otra_lista no se tocan # Concatenar listas con 'extend' lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] -# Chequea la existencia en una lista con 'in' +# Verifica la existencia en una lista con 'in' 1 in lista #=> True # Examina el largo de una lista con 'len' @@ -196,7 +201,7 @@ d, e, f = 4, 5, 6 e, d = d, e # d ahora es 5 y e ahora es 4 -# Diccionarios almacenan mapeos +# Diccionarios relacionan llaves y valores dicc_vacio = {} # Aquí está un diccionario prellenado dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} @@ -213,7 +218,7 @@ list(dicc_lleno.keys()) #=> ["tres", "dos", "uno"] list(dicc_lleno.values()) #=> [3, 2, 1] # Nota - Lo mismo que con las llaves, no se garantiza el orden. -# Chequea la existencia de una llave en el diccionario con 'in' +# Verifica la existencia de una llave en el diccionario con 'in' "uno" in dicc_lleno #=> True 1 in dicc_lleno #=> False @@ -253,7 +258,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Haz diferencia de conjuntos con - {1,2,3,4} - {2,3,5} #=> {1, 4} -# Chequea la existencia en un conjunto con 'in' +# Verifica la existencia en un conjunto con 'in' 2 in conjunto_lleno #=> True 10 in conjunto_lleno #=> False @@ -262,7 +267,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} ## 3. Control de Flujo #################################################### -# Let's just make a variable +# Creemos una variable para experimentar some_var = 5 # Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! @@ -275,18 +280,17 @@ else: # Esto también es opcional. print("una_variable es de hecho 10.") """ -For itera sobre listas +For itera sobre iterables (listas, cadenas, diccionarios, tuplas, generadores...) imprime: perro es un mamifero gato es un mamifero raton es un mamifero """ for animal in ["perro", "gato", "raton"]: - # Puedes usar % para interpolar strings formateados print("{} es un mamifero".format(animal)) """ -`range(número)` retorna una lista de números +`range(número)` retorna un generador de números desde cero hasta el número dado imprime: 0 @@ -323,7 +327,7 @@ except IndexError as e: dicc_lleno = {"uno": 1, "dos": 2, "tres": 3} nuestro_iterable = dicc_lleno.keys() -print(nuestro_iterable) #=> range(1,10). Este es un objeto que implementa nuestra interfaz Iterable +print(nuestro_iterable) #=> dict_keys(['uno', 'dos', 'tres']). Este es un objeto que implementa nuestra interfaz Iterable Podemos recorrerla. for i in nuestro_iterable: @@ -420,6 +424,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] # Podemos usar listas por comprensión para mapeos y filtros agradables [add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] +# también hay diccionarios +{k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4} +# y conjuntos por comprensión +{c for c in "la cadena"} #=> {'d', 'l', 'a', 'n', ' ', 'c', 'e'} #################################################### ## 5. Classes -- cgit v1.2.3 From f50ec0c885c063fce845e56611e1462510263bd1 Mon Sep 17 00:00:00 2001 From: Abraham Toriz Date: Wed, 10 Oct 2018 09:46:39 -0500 Subject: changes werent big enough to count myself as contributor of this article --- es-es/python3-es.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown index 342bb094..3236e73a 100644 --- a/es-es/python3-es.html.markdown +++ b/es-es/python3-es.html.markdown @@ -2,7 +2,6 @@ language: python3 contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - - ["Categulario", "https://twitter.com/categulario"] translators: - ["Camilo Garrido", "http://twitter.com/hirohope"] lang: es-es -- cgit v1.2.3 From 1ba29fe5bd451e3d049d86973d2a10c488a4137f Mon Sep 17 00:00:00 2001 From: Tommaso Date: Wed, 10 Oct 2018 22:22:33 +0200 Subject: [go/it-it] Fix `defer` wording, as shown in ff06f9cf993c79b843008a641abb92e183cff285 --- it-it/go-it.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index e49ccd79..797f6b0b 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -270,12 +270,13 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { } func imparaDefer() (ok bool) { - // Le istruzioni dette "deferred" (rinviate) sono eseguite - // appena prima che la funzione abbia termine. + // La parola chiave "defer" inserisce una funzione in una lista. + // La lista contenente tutte le chiamate a funzione viene eseguita DOPO + // il return finale della funzione che le circonda. defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") defer fmt.Println("\nQuesta riga viene stampata per prima perché") // defer viene usato di solito per chiudere un file, così la funzione che - // chiude il file viene messa vicino a quella che lo apre. + // chiude il file, preceduta da "defer", viene messa vicino a quella che lo apre. return true } -- cgit v1.2.3 From 576c9a33b6bd9004bf187323745da1e28d82614d Mon Sep 17 00:00:00 2001 From: Tommaso Date: Wed, 10 Oct 2018 22:29:03 +0200 Subject: [html/it-it] Add info about html MIME type and fix #3074 --- it-it/html-it.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/it-it/html-it.html.markdown b/it-it/html-it.html.markdown index 471019a1..8f7391a2 100644 --- a/it-it/html-it.html.markdown +++ b/it-it/html-it.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: learnhtml-it.html +filename: learnhtml-it.txt contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: @@ -112,7 +112,7 @@ Questo articolo riguarda principalmente la sintassi HTML ed alcuni suggerimenti ## Uso -HTML è scritto in files che finiscono con `.html`. +HTML è scritto in files che finiscono con `.html` o `.htm`. Il "MIME type" è `text/html`. ## Per saperne di più -- cgit v1.2.3 From 64426bc675c81203a682d0f2715d952c0b554742 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Thu, 11 Oct 2018 21:29:15 +0530 Subject: add LaTeX resource --- latex.html.markdown | 95 +++++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 47 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index c9b1d8fb..253c8139 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -26,8 +26,8 @@ filename: learn-latex.tex % Next we define the packages the document uses. % If you want to include graphics, colored text, or -% source code from another language file into your document, -% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. % I'm going to include the float and caption packages for figures % and hyperref package for hyperlinks \usepackage{caption} @@ -42,14 +42,14 @@ Svetlana Golubeva} % Now we're ready to begin the document % Everything before this line is called "The Preamble" -\begin{document} -% if we set the author, date, title fields, we can have LaTeX +\begin{document} +% if we set the author, date, title fields, we can have LaTeX % create a title page for us. \maketitle % If we have sections, we can create table of contents. We have to compile our % document twice to make it appear in right order. -% It is a good practice to separate the table of contents form the body of the +% It is a good practice to separate the table of contents form the body of the % document. To do so we use \newpage command \newpage \tableofcontents @@ -58,14 +58,14 @@ Svetlana Golubeva} % Most research papers have abstract, you can use the predefined commands for this. % This should appear in its logical order, therefore, after the top matter, -% but before the main sections of the body. +% but before the main sections of the body. % This command is available in the document classes article and report. \begin{abstract} \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not my idea! \end{abstract} -% Section commands are intuitive. +% Section commands are intuitive. % All the titles of the sections are added automatically to the table of contents. \section{Introduction} Hello, my name is Colton and together we're going to explore \LaTeX! @@ -81,16 +81,16 @@ Much better now. \label{subsec:pythagoras} % By using the asterisk we can suppress LaTeX's inbuilt numbering. -% This works for other LaTeX commands as well. -\section*{This is an unnumbered section} +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} However not all sections have to be numbered! \section{Some Text notes} %\section{Spacing} % Need to add more information about space intervals \LaTeX \hspace{1pt} is generally pretty good about placing text where it should -go. If -a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash -\hspace{1pt} to the source code. \\ +go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash +\hspace{1pt} to the source code. \\ \section{Lists} Lists are one of the easiest things to create in \LaTeX! I need to go shopping @@ -110,7 +110,7 @@ tomorrow, so let's make a grocery list. \section{Math} One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles -or technical papers. Usually in the realm of math and science. As such, +or technical papers. Usually in the realm of math and science. As such, we need to be able to add special symbols to our paper! \\ Math has many symbols, far beyond what you can find on a keyboard; @@ -118,9 +118,9 @@ Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ Sets and relations play a vital role in many mathematical research papers. Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ -% Notice how I needed to add $ signs before and after the symbols. This is -% because when writing, we are in text-mode. -% However, the math symbols only exist in math-mode. +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. % We can enter math-mode from text mode with the $ signs. % The opposite also holds true. Variable can also be rendered in math-mode. % We can also enter math mode with \[\] @@ -131,12 +131,12 @@ My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know about! \\ -Operators are essential parts of a mathematical document: -trigonometric functions ($\sin$, $\cos$, $\tan$), -logarithms and exponentials ($\log$, $\exp$), -limits ($\lim$), etc. -have per-defined LaTeX commands. -Let's write an equation to see how it's done: +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ Fractions (Numerator-denominators) can be written in these forms: @@ -156,31 +156,31 @@ We can also insert equations in an ``equation environment''. \label{eq:pythagoras} % for referencing \end{equation} % all \begin statements must have an end statement -We can then reference our new equation! +We can then reference our new equation! Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also -the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: figures, equations, sections, etc. Summations and Integrals are written with sum and int commands: % Some LaTeX compilers will complain if there are blank lines % In an equation environment. -\begin{equation} +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Figures} -Let's insert a Figure. Figure placement can get a little tricky. +Let's insert a Figure. Figure placement can get a little tricky. I definitely have to lookup the placement options each time. -\begin{figure}[H] % H here denoted the placement option. +\begin{figure}[H] % H here denoted the placement option. \centering % centers the figure on the page % Inserts a figure scaled to 0.8 the width of the page. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Commented out for compilation purposes. Please use your imagination. \caption{Right triangle with sides $a$, $b$, $c$} \label{fig:right-triangle} @@ -193,7 +193,7 @@ We can also insert Tables in the same way as figures. \caption{Caption for the Table.} % the {} arguments below describe how each row of the table is drawn. % Again, I have to look these up. Each. And. Every. Time. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Number & Last Name & First Name \\ % Column rows are separated by & \hline % a horizontal line 1 & Biggus & Dickus \\ @@ -204,34 +204,34 @@ We can also insert Tables in the same way as figures. \section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)} Let's say we want to include some code into our \LaTeX \hspace{1pt} document, we would then need \LaTeX \hspace{1pt} to not try and interpret that text and -instead just print it to the document. We do this with a verbatim -environment. +instead just print it to the document. We do this with a verbatim +environment. % There are other packages that exist (i.e. minty, lstlisting, etc.) % but verbatim is the bare-bones basic one. -\begin{verbatim} +\begin{verbatim} print("Hello World!") - a%b; % look! We can use % signs in verbatim. + a%b; % look! We can use % signs in verbatim. random = 4; #decided by fair random dice roll \end{verbatim} -\section{Compiling} +\section{Compiling} -By now you're probably wondering how to compile this fabulous document +By now you're probably wondering how to compile this fabulous document and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf. (yes, this document actually does compile). \\ -Getting to the final document using \LaTeX \hspace{1pt} consists of the following +Getting to the final document using \LaTeX \hspace{1pt} consists of the following steps: \begin{enumerate} \item Write the document in plain text (the ``source code''). - \item Compile source code to produce a pdf. + \item Compile source code to produce a pdf. The compilation step looks like this (in Linux): \\ - \begin{verbatim} + \begin{verbatim} > pdflatex learn-latex.tex \end{verbatim} \end{enumerate} -A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the +A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the same piece of software. So, you get to see Step 1, but not Step 2 completely. Step 2 is still happening behind the scenes\footnote{In cases, where you use references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2 @@ -245,17 +245,17 @@ format you defined in Step 1. \section{Hyperlinks} We can also insert hyperlinks in our document. To do so we need to include the package hyperref into preamble with the command: -\begin{verbatim} +\begin{verbatim} \usepackage{hyperref} \end{verbatim} There exists two main types of links: visible URL \\ -\url{https://learnxinyminutes.com/docs/latex/}, or +\url{https://learnxinyminutes.com/docs/latex/}, or \href{https://learnxinyminutes.com/docs/latex/}{shadowed by text} -% You can not add extra-spaces or special symbols into shadowing text since it +% You can not add extra-spaces or special symbols into shadowing text since it % will cause mistakes during the compilation -This package also produces list of thumbnails in the output pdf document and +This package also produces list of thumbnails in the output pdf document and active links in the table of contents. \section{End} @@ -267,7 +267,7 @@ That's all for now! \begin{thebibliography}{1} % similar to other lists, the \bibitem command can be used to list items % each entry can then be cited directly in the body of the text - \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em + \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em https://en.wikibooks.org/wiki/LaTeX} \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} \end{thebibliography} @@ -280,3 +280,4 @@ https://en.wikibooks.org/wiki/LaTeX} * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) * An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) +* A quick guide for learning LaTeX: [Learn LaTeX in 30 minutes](https://www.overleaf.com/learn/latex/Learn_LaTeX_in_30_minutes) -- cgit v1.2.3 From 00c12ddcff858b9e7bfe450bd4d4b492206a3b34 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Thu, 11 Oct 2018 21:41:42 +0530 Subject: add PHP resource --- php.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 6542035f..3b18aa60 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -794,7 +794,7 @@ But I'm ChildClass /********************** * Magic constants -* +* */ // Get current class name. Must be used inside a class declaration. @@ -826,7 +826,7 @@ echo "Current trait is " . __TRAIT__; /********************** * Error Handling -* +* */ // Simple error handling can be done with try catch block @@ -871,6 +871,9 @@ and community input. If you're interested in up-to-date best practices, visit [PHP The Right Way](http://www.phptherightway.com/). +A tutorial covering basics of language, setting up coding environment and making +few practical projects at [Codecourse - PHP Basics](https://www.youtube.com/playlist?list=PLfdtiltiRHWHjTPiFDRdTOPtSyYfz3iLW). + If you're coming from a language with good package management, check out [Composer](http://getcomposer.org/). -- cgit v1.2.3 From fb58e953434956811b37ebde53be2f148aaa3a5f Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Thu, 11 Oct 2018 15:46:00 -0300 Subject: [html/pt-br] Add Portuguese language for html --- pt-br/html-pt.html.markdown | 125 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 pt-br/html-pt.html.markdown diff --git a/pt-br/html-pt.html.markdown b/pt-br/html-pt.html.markdown new file mode 100644 index 00000000..5a4bc3bc --- /dev/null +++ b/pt-br/html-pt.html.markdown @@ -0,0 +1,125 @@ +--- +language: html +filename: learnhtml.txt +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] +lang: pt-br +--- + +HTML é um acrônimo de HyperText Markup Language(Linguagem de Marcação de HiperTexto). +É uma linguagem que nos permite escrever páginas para a "world wide web". +É uma linguagem de marcação, nos permite escrever páginas na web usando código +para indicar como o texto e os dados serão ser exibidos. +De fato, arquivos HTML são simples arquivos de texto. +O que seria marcação? É um método de organização dos dados da página envolvidos +por abertura e fechamento de tags. +Essa marcação serve para dar significado ao texto que envolve. +Assim como outras linguagens, o HTML tem diversas versões. Aqui falaremos sobre o HTML5. + +**NOTA :** Você pode testar diferentes tags e elementos conforme progride os +tutoriais em sites como [codepen](http://codepen.io/pen/) podendo ver seus efeitos, +entendendo como funcionam e se familiarizando com a linguagem. +Esse artigo tem seu foco principal na sintaxe do HTML e algumas dicas úteis. + + +```html + + + + + + + + + + Meu Site + + +

Olá, mundo!

+ Venha ver como isso aparece +

Esse é um parágrafo.

+

Esse é um outro parágrafo.

+
    +
  • Esse é um item de uma lista não enumerada (bullet list)
  • +
  • Esse é um outro item
  • +
  • E esse é o último item da lista
  • +
+ + + + + + + + + + + + + + + + + + + + + Meu Site + + + + + + + +

Olá, mundo!

+ + Venha ver o que isso exibe +

Esse é um parágrafo.

+

Esse é um outro parágrafo.

+
    + +
  • Esse é um item de uma lista não-enumerada.
  • +
  • Esse é um outro item
  • +
  • E esse é o último item da lista
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Primeiro cabeçalho Segundo cabeçalho
Primeira linha, primeira coluna Primeira linha, segunda coluna
Segunda linha, primeira colunaSegunda linha, segunda coluna
+ +``` + +## Uso + +HTML é escrito em arquivos com a extensão `.html` ou `.htm`. Seu mime type é `text/html`. + +## Para aprender mais + +* [wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 56258dfb72c17192d1963d56da6aaf12624b3e43 Mon Sep 17 00:00:00 2001 From: Joseph G Date: Thu, 11 Oct 2018 14:10:16 -0700 Subject: Add f-string clarification. --- python3.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index b378a8c6..7683bc60 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -139,9 +139,11 @@ len("This is a string") # => 16 # still use the old style of formatting: "%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" -# You can also format using f-strings or formatted string literals +# You can also format using f-strings or formatted string literals (in Python 3.6+) name = "Reiko" f"She said her name is {name}." # => "She said her name is Reiko" +# You can basically put any Python statement inside the braces and it will be output in the string. +f"{name} is {len(name)} characters long." # None is an object -- cgit v1.2.3 From 175a78ec331b6d28e5940206f6f3e884405a858d Mon Sep 17 00:00:00 2001 From: Joseph G Date: Thu, 11 Oct 2018 14:21:54 -0700 Subject: Removed deprecated reference --- swift.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 516debed..f834f373 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -13,9 +13,9 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+. -The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. +The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. -See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift. +Another great reference is _About Swift_ on Swift's [website](https://docs.swift.org/swift-book/). ```swift // import a module -- cgit v1.2.3 From 1c932a33f99149f6be77aa0de07abc1aedbc0d74 Mon Sep 17 00:00:00 2001 From: Lucas Pugliesi Date: Fri, 12 Oct 2018 22:49:15 -0300 Subject: [cmake/pt-br] Add portuguese language for cmake --- pt-br/cmake-pt.html.markdown | 178 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 pt-br/cmake-pt.html.markdown diff --git a/pt-br/cmake-pt.html.markdown b/pt-br/cmake-pt.html.markdown new file mode 100644 index 00000000..bc3e7050 --- /dev/null +++ b/pt-br/cmake-pt.html.markdown @@ -0,0 +1,178 @@ +--- +language: cmake +contributors: + - ["Bruno Alano", "https://github.com/brunoalano"] +filename: CMake +translators: + - ["Lucas Pugliesi", "https://github.com/fplucas"] +lang: pt-br +--- + +CMake é um programa de compilação open-source e multiplataforma. Essa ferramenta +permitirá testar, compilar e criar pacotes a partir do seu código fonte. + +O problema que o CMake tenta resolver são os problemas de configurar os Makefiles +e Autoconfigure (diferente dos interpretadores make que tem comandos diferentes) +e sua facilidade de uso envolvendo bibliotecas terceiras. + +CMake é um sistema open-source extensível que gerencia o processo de build em um +sistema operacional e um método independente de compilador. Diferente de sistemas +multiplataformas, CMake é designado a usar em conjunto ao ambiente de compilação +nativo. Seus simples arquivos de configuração localizados em seus diretórios +(chamados arquivos CMakeLists.txt) que são usados para gerar padrões de arquivos +de compilação (ex: makefiles no Unix e projetos em Windows MSVC) que são usados +de maneira simples. + +```cmake +# No CMake, isso é um comentário + +# Para rodar nosso código, iremos utilizar esses comandos: +# - mkdir build && cd build +# - cmake .. +# - make +# +# Com esses comandos, iremos seguir as melhores práticas para compilar em um +# subdiretório e na segunda linha pediremos ao CMake para gerar um novo Makefile +# independente de sistema operacional. E finalmente, rodar o comando make. + +#------------------------------------------------------------------------------ +# Básico +#------------------------------------------------------------------------------ +# +# O arquivo CMake deve ser chamado de "CMakeLists.txt". + +# Configura a versão mínima requerida do CMake para gerar o Makefile +cmake_minimum_required (VERSION 2.8) + +# Exibe FATAL_ERROR se a versão for menor que 2.8 +cmake_minimum_required (VERSION 2.8 FATAL_ERROR) + +# Configuramos o nome do nosso projeto. Mas antes disso, iremos alterar alguns +# diretórios em nome da convenção gerada pelo CMake. Podemos enviar a LANG do +# código como segundo parâmetro +project (learncmake C) + +# Configure o diretório do código do projeto (somente convenção) +set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} ) +set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} ) + +# Isso é muito útil para configurar a versão do nosso código no sistema de compilação +# usando um estilo `semver` +set (LEARN_CMAKE_VERSION_MAJOR 1) +set (LEARN_CMAKE_VERSION_MINOR 0) +set (LEARN_CMAKE_VERSION_PATCH 0) + +# Envie as variáveis (número da versão) para o cabeçalho de código-fonte +configure_file ( + "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" + "${PROJECT_BINARY_DIR}/TutorialConfig.h" +) + +# Inclua Diretórios +# No GCC, isso irá invocar o comando "-I" +include_directories( include ) + +# Onde as bibliotecas adicionais estão instaladas? Nota: permite incluir o path +# aqui, na sequência as checagens irão resolver o resto +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condições +if ( CONDICAO ) + # reposta! + + # Informação incidental + message(STATUS "Minha mensagem") + + # Aviso CMake, continua processando + message(WARNING "Minha mensagem") + + # Aviso (dev) CMake, continua processando + message(AUTHOR_WARNING "Minha mensagem") + + # Erro CMake, continua processando, mas pula a geração + message(SEND_ERROR "Minha mensagem") + + # Erro CMake, para o processamento e a geração + message(FATAL_ERROR "Minha mensagem") +endif() + +if( CONDICAO ) + +elseif( CONDICAO ) + +else( CONDICAO ) + +endif( CONDICAO ) + +# Loops +foreach(loop_var arg1 arg2 ...) + COMANDO1(ARGS ...) + COMANDO2(ARGS ...) + ... +endforeach(loop_var) + +foreach(loop_var RANGE total) +foreach(loop_var RANGE start stop [step]) + +foreach(loop_var IN [LISTS [list1 [...]]] + [ITEMS [item1 [...]]]) + +while(condicao) + COMANDO1(ARGS ...) + COMANDO2(ARGS ...) + ... +endwhile(condicao) + + +# Operações Lógicas +if(FALSE AND (FALSE OR TRUE)) + message("Não exiba!") +endif() + +# Configure um cache normal, ou uma variável de ambiente com o dado valor. +# Se a opção PARENT_SCOPE for informada em uma variável que será setada no escopo +# acima do escopo corrente. +# `set( ... [PARENT_SCOPE])` + +# Como refencia variáveis dentro de aspas ou não, argumentos com strings vazias +# não serão setados +${nome_da_variavel} + +# Listas +# Configure a lista de arquivos código-fonte +set( LEARN_CMAKE_SOURCES + src/main.c + src/imagem.c + src/pather.c +) + +# Chama o compilador +# +# ${PROJECT_NAME} referencia ao Learn_CMake +add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} ) + +# Linka as bibliotecas +target_link_libraries( ${PROJECT_NAME} ${LIBS} m ) + +# Onde as bibliotecas adicionais serão instaladas? Nota: nos permite incluir o path +# aqui, em seguida os testes irão resolver o restante +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condição do compilador (gcc ; g++) +if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" ) + message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" ) + add_definitions( --std=c99 ) +endif() + +# Checa o Sistema Operacional +if( UNIX ) + set( LEARN_CMAKE_DEFINITIONS + "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" ) +endif() +``` + +### Mais Recursos + ++ [cmake tutorial](https://cmake.org/cmake-tutorial/) ++ [cmake documentation](https://cmake.org/documentation/) ++ [mastering cmake](http://amzn.com/1930934319/) -- cgit v1.2.3 From 2c5f56394a0352414484cd06f0e3ee11c21f4f89 Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 13 Oct 2018 15:03:07 +0200 Subject: [qt/it-IT] Add italian language for qt --- it-it/qt-it.html.markdown | 161 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 it-it/qt-it.html.markdown diff --git a/it-it/qt-it.html.markdown b/it-it/qt-it.html.markdown new file mode 100644 index 00000000..4543818f --- /dev/null +++ b/it-it/qt-it.html.markdown @@ -0,0 +1,161 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +translators: + - ["Ale46", "https://gihub.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*, ci sono diversi porting in altri linguaggi: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** è ottimo per la creazione di applicazioni con interfaccia utente grafica (GUI). Questo tutorial descrive come farlo in *C++*. + +```c++ +/* + * Iniziamo classicamente + */ + +// tutte le intestazioni dal framework Qt iniziano con la lettera maiuscola 'Q' +#include +#include + +int main(int argc, char *argv[]) { + // crea un oggetto per gestire le risorse a livello di applicazione + QApplication app(argc, argv); + + // crea un widget di campo di testo e lo mostra sullo schermo + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // avvia il ciclo degli eventi dell'applicazione + return app.exec(); +} +``` + +La parte relativa alla GUI di **Qt** riguarda esclusivamente *widget* e le loro *connessioni*. + +[LEGGI DI PIÙ SUI WIDGET](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Creiamo un'etichetta e un pulsante. + * Un'etichetta dovrebbe apparire quando si preme un pulsante. + * + * Il codice Qt parla da solo. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Grazie per aver premuto quel pulsante"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Premimi"); + layout.addWidget(&button); + + // mostra l'etichetta nascosta quando viene premuto il pulsante + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Si noti la parte relativa a *QObject::connect*. Questo metodo viene utilizzato per connettere *SEGNALI* di un oggetto agli *SLOTS* di un altro. + +**I SEGNALI** vengono emessi quando certe cose accadono agli oggetti, come il segnale *premuto* che viene emesso quando l'utente preme sull'oggetto QPushButton. + +**Gli slot** sono *azioni* che potrebbero essere eseguite in risposta ai segnali ricevuti. + +[LEGGI DI PIÙ SU SLOT E SEGNALI](http://doc.qt.io/qt-5/signalsandslots.html) + + +Successivamente, impariamo che non possiamo solo usare i widget standard, ma estendere il loro comportamento usando l'ereditarietà. Creiamo un pulsante e contiamo quante volte è stato premuto. A tale scopo definiamo la nostra classe *CounterLabel*. Deve essere dichiarato in un file separato a causa dell'architettura Qt specifica. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Macro definite da Qt che devono essere presenti in ogni widget personalizzato + +public: + CounterLabel() : counter(0) { + setText("Il contatore non è stato ancora aumentato"); // metodo di QLabel + } + +public slots: + // azione che verrà chiamata in risposta alla pressione del pulsante + void increaseCounter() { + setText(QString("Valore contatore: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Quasi uguale all'esempio precedente + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Premimi ancora una volta"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +Questo è tutto! Ovviamente, il framework Qt è molto più grande della parte che è stata trattata in questo tutorial, quindi preparatevi a leggere e fare pratica. + +## Ulteriori letture + +- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html) +- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html) + +Buona fortuna e buon divertimento! -- cgit v1.2.3 From 50ebfcc340845052188eb0bc37978539cad74031 Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 13 Oct 2018 15:03:42 +0200 Subject: [dynamic-programming/it-IT] Add italian language for dynamic-programming --- it-it/dynamic-programming-it.html.markdown | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 it-it/dynamic-programming-it.html.markdown diff --git a/it-it/dynamic-programming-it.html.markdown b/it-it/dynamic-programming-it.html.markdown new file mode 100644 index 00000000..963d096c --- /dev/null +++ b/it-it/dynamic-programming-it.html.markdown @@ -0,0 +1,54 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +# Programmazione dinamica + +## Introduzione + +La programmazione dinamica è una tecnica potente utilizzata per risolvere una particolare classe di problemi, come vedremo. L'idea è molto semplice, se hai risolto un problema con l'input dato, salva il risultato come riferimento futuro, in modo da evitare di risolvere nuovamente lo stesso problema. + +Ricordate sempre! +"Chi non ricorda il passato è condannato a ripeterlo" + +## Modi per risolvere questi problemi + +1. *Top-Down* : Inizia a risolvere il problema specifico suddividendolo. Se vedi che il problema è già stato risolto, rispondi semplicemente con la risposta già salvata. Se non è stato risolto, risolvilo e salva la risposta. Di solito è facile da pensare e molto intuitivo. Questo è indicato come Memoization. + +2. *Bottom-Up* : Analizza il problema e vedi l'ordine in cui i sotto-problemi sono risolti e inizia a risolvere dal sottoproblema banale, verso il problema dato. In questo processo, è garantito che i sottoproblemi vengono risolti prima di risolvere il problema. Si parla di programmazione dinamica. + +## Esempio di programmazione dinamica + +Il problema di "Longest Increasing Subsequence" consiste nel trovare la sottosequenza crescente più lunga di una determinata sequenza. Data una sequenza `S= {a1 , a2 , a3, a4, ............., an-1, an }` dobbiamo trovare il sottoinsieme più lungo tale che per tutti gli `j` e gli `i`, `j a[j] and LS[i] Date: Sat, 13 Oct 2018 15:04:20 +0200 Subject: [jquery/it-IT] Add italian language for jquery --- it-it/jquery-it.html.markdown | 131 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 it-it/jquery-it.html.markdown diff --git a/it-it/jquery-it.html.markdown b/it-it/jquery-it.html.markdown new file mode 100644 index 00000000..811c5c3a --- /dev/null +++ b/it-it/jquery-it.html.markdown @@ -0,0 +1,131 @@ +--- +category: tool +tool: jquery +contributors: + - ["Sawyer Charles", "https://github.com/xssc"] +filename: jquery-it.js +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +jQuery è una libreria JavaScript che ti aiuta a "fare di più, scrivendo meno". Rende molte attività comuni di JavaScript più facili da scrivere. jQuery è utilizzato da molte grandi aziende e sviluppatori in tutto il mondo. Rende AJAX, gestione degli eventi, manipolazione dei documenti e molto altro, più facile e veloce. + +Visto che jQuery è una libreria JavaScript dovresti prima [imparare JavaScript](https://learnxinyminutes.com/docs/javascript/) + +```js + + +/////////////////////////////////// +// 1. Selettori + +// I selettori in jQuery vengono utilizzati per selezionare un elemento +var page = $(window); // Seleziona l'intera finestra + +// I selettori possono anche essere selettori CSS +var paragraph = $('p'); // Seleziona tutti gli elementi del paragrafo +var table1 = $('#table1'); // Seleziona elemento con id 'table1' +var squares = $('.square'); // Seleziona tutti gli elementi con la classe 'square' +var square_p = $('p.square') // Seleziona i paragrafi con la classe 'square' + + +/////////////////////////////////// +// 2. Eventi ed effetti +// jQuery è molto bravo a gestire ciò che accade quando un evento viene attivato +// Un evento molto comune è l'evento "pronto" sul documento +// Puoi usare il metodo 'ready' per aspettare che l'elemento abbia finito di caricare +$(document).ready(function(){ + // Il codice non verrà eseguito fino a quando il documento non verrà caricato +}); +// Puoi anche usare funzioni definite +function onAction() { + // Questo viene eseguito quando l'evento viene attivato +} +$('#btn').click(onAction); // Invoca onAction al click + +// Alcuni altri eventi comuni sono: +$('#btn').dblclick(onAction); // Doppio click +$('#btn').hover(onAction); // Al passaggio del mouse +$('#btn').focus(onAction); // Al focus +$('#btn').blur(onAction); // Focus perso +$('#btn').submit(onAction); // Al submit +$('#btn').select(onAction); // Quando un elemento è selezionato +$('#btn').keydown(onAction); // Quando un tasto è premuto (ma non rilasciato) +$('#btn').keyup(onAction); // Quando viene rilasciato un tasto +$('#btn').keypress(onAction); // Quando viene premuto un tasto +$('#btn').mousemove(onAction); // Quando il mouse viene spostato +$('#btn').mouseenter(onAction); // Il mouse entra nell'elemento +$('#btn').mouseleave(onAction); // Il mouse lascia l'elemento + + +// Questi possono anche innescare l'evento invece di gestirlo +// semplicemente non passando alcun parametro +$('#btn').dblclick(); // Innesca il doppio click sull'elemento + +// Puoi gestire più eventi mentre usi il selettore solo una volta +$('#btn').on( + {dblclick: myFunction1} // Attivato con doppio clic + {blur: myFunction1} // Attivato al blur +); + +// Puoi spostare e nascondere elementi con alcuni metodi di effetto +$('.table').hide(); // Nascondi gli elementi + +// Nota: chiamare una funzione in questi metodi nasconderà comunque l'elemento +$('.table').hide(function(){ + // Elemento nascosto quindi funzione eseguita +}); + +// È possibile memorizzare selettori in variabili +var tables = $('.table'); + +// Alcuni metodi di manipolazione dei documenti di base sono: +tables.hide(); // Nascondi elementi +tables.show(); // Mostra elementi +tables.toggle(); // Cambia lo stato nascondi/mostra +tables.fadeOut(); // Fades out +tables.fadeIn(); // Fades in +tables.fadeToggle(); // Fades in o out +tables.fadeTo(0.5); // Dissolve in opacità (tra 0 e 1) +tables.slideUp(); // Scorre verso l'alto +tables.slideDown(); // Scorre verso il basso +tables.slideToggle(); // Scorre su o giù + +// Tutti i precedenti prendono una velocità (millisecondi) e la funzione di callback +tables.hide(1000, myFunction); // nasconde l'animazione per 1 secondo quindi esegue la funzione + +// fadeTo ha un'opacità richiesta come secondo parametro +tables.fadeTo(2000, 0.1, myFunction); // esegue in 2 sec. il fade sino ad una opacità di 0.1 opacity e poi la funzione + +// Puoi ottenere un effetti più avanzati con il metodo animate +tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); +// Il metodo animate accetta un oggetto di css e valori con cui terminare, +// parametri opzionali per affinare l'animazione, +// e naturalmente la funzione di callback + +/////////////////////////////////// +// 3. Manipolazione + +// Questi sono simili agli effetti ma possono fare di più +$('div').addClass('taming-slim-20'); // Aggiunge la classe taming-slim-20 a tutti i div + +// Metodi di manipolazione comuni +$('p').append('Hello world'); // Aggiunge alla fine dell'elemento +$('p').attr('class'); // Ottiene l'attributo +$('p').attr('class', 'content'); // Imposta l'attributo +$('p').hasClass('taming-slim-20'); // Restituisce vero se ha la classe +$('p').height(); // Ottiene l'altezza dell'elemento o imposta l'altezza + + +// Per molti metodi di manipolazione, ottenere informazioni su un elemento +// restituirà SOLO il primo elemento corrispondente +$('p').height(); // Ottiene solo la prima altezza del tag 'p' + +// È possibile utilizzare each per scorrere tutti gli elementi +var heights = []; +$('p').each(function() { + heights.push($(this).height()); // Aggiunge tutte le altezze del tag 'p' all'array +}); + + +``` -- cgit v1.2.3 From e2c7caff58337e7a7821a8732d5b9d35a5dc80ce Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 13 Oct 2018 15:04:56 +0200 Subject: [asciidoc/it-IT] Add italian language for asciidoc --- it-it/asciidoc-it.html.markdown | 135 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 it-it/asciidoc-it.html.markdown diff --git a/it-it/asciidoc-it.html.markdown b/it-it/asciidoc-it.html.markdown new file mode 100644 index 00000000..47a57349 --- /dev/null +++ b/it-it/asciidoc-it.html.markdown @@ -0,0 +1,135 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/"] + - ["Abel Salgado Romero", "https://twitter.com/abelsromero"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +filename: asciidoc-it.md +--- + +AsciiDoc è un linguaggio di markup simile a Markdown e può essere usato per qualsiasi cosa, dai libri ai blog. Creato nel 2002 da Stuart Rackman, questo linguaggio è semplice ma permette un buon numero di personalizzazioni. + +Intestazione Documento + +Le intestazioni sono opzionali e possono contenere linee vuote. Deve avere almeno una linea vuota rispetto al contenuto. + +Solo titolo + +``` += Titolo documento + +Prima frase del documento. +``` + +Titolo ed Autore + +``` += Titolo documento +Primo Ultimo + +Inizio del documento +``` + +Autori multipli + +``` += Titolo Documento +John Doe ; Jane Doe; Black Beard + +Inizio di un documento con autori multipli. +``` + +Linea di revisione (richiede una linea autore) + +``` += Titolo documento V1 +Potato Man +v1.0, 2016-01-13 + +Questo articolo sulle patatine sarà divertente. +``` + +Paragrafi + +``` +Non hai bisogno di nulla di speciale per i paragrafi. + +Aggiungi una riga vuota tra i paragrafi per separarli. + +Per creare una riga vuota aggiungi un + +e riceverai una interruzione di linea! +``` + +Formattazione Testo + +``` +_underscore crea corsivo_ +*asterischi per il grassetto* +*_combinali per maggiore divertimento_* +`usa i ticks per indicare il monospazio` +`*spaziatura fissa in grassetto*` +``` + +Titoli di sezione + +``` += Livello 0 (può essere utilizzato solo nell'intestazione del documento) + +== Livello 1

+ +=== Livello 2

+ +==== Livello 3

+ +===== Livello 4

+ +``` + +Liste + +Per creare un elenco puntato, utilizzare gli asterischi. + +``` +* foo +* bar +* baz +``` + +Per creare un elenco numerato usa i periodi. + +``` +. item 1 +. item 2 +. item 3 +``` + +È possibile nidificare elenchi aggiungendo asterischi o periodi aggiuntivi fino a cinque volte. + +``` +* foo 1 +** foo 2 +*** foo 3 +**** foo 4 +***** foo 5 + +. foo 1 +.. foo 2 +... foo 3 +.... foo 4 +..... foo 5 +``` + +## Ulteriori letture + +Esistono due strumenti per elaborare i documenti AsciiDoc: + +1. [AsciiDoc](http://asciidoc.org/): implementazione Python originale, disponibile nelle principali distribuzioni Linux. Stabile e attualmente in modalità di manutenzione. +2. [Asciidoctor](http://asciidoctor.org/): implementazione alternativa di Ruby, utilizzabile anche da Java e JavaScript. In fase di sviluppo attivo, mira ad estendere la sintassi AsciiDoc con nuove funzionalità e formati di output. + +I seguenti collegamenti sono relativi all'implementazione di `Asciidoctor`: + +* [Markdown - AsciiDoc comparazione sintassi](http://asciidoctor.org/docs/user-manual/#comparison-by-example): confronto affiancato di elementi di Markdown e AsciiDoc comuni. +* [Per iniziare](http://asciidoctor.org/docs/#get-started-with-asciidoctor): installazione e guide rapide per il rendering di documenti semplici. +* [Asciidoctor Manuale Utente](http://asciidoctor.org/docs/user-manual/): manuale completo con riferimento alla sintassi, esempi, strumenti di rendering, tra gli altri. -- cgit v1.2.3 From b3586510e22d92c7c92df0a7f91f3b2542531a9c Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 13 Oct 2018 15:05:32 +0200 Subject: [pyqt/it-IT] Add italian language for pyqt --- it-it/pyqt-it.html.markdown | 85 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 it-it/pyqt-it.html.markdown diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown new file mode 100644 index 00000000..855a0c75 --- /dev/null +++ b/it-it/pyqt-it.html.markdown @@ -0,0 +1,85 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Ale46", "https://github.com/ale46"] +lang: it-it +--- + +**Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*. + + +Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192 +), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità +che avrebbero se fossero fatte usando pyqt! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Crea un oggetto applicazione + app = QtGui.QApplication(sys.argv) + # Crea un widget in cui verrà inserita la nostra etichetta + w = QtGui.QWidget() + # Aggiungi un'etichetta al widget + b = QtGui.QLabel(w) + # Imposta del testo per l'etichetta + b.setText("Ciao Mondo!") + # Fornisce informazioni su dimensioni e posizionamento + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Dai alla nostra finestra un bel titolo + w.setWindowTitle("PyQt") + # Visualizza tutto + w.show() + # Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi. +Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Crea un pulsante e allegalo al widget w + b = QPushButton(w) + b.setText("Premimi") + b.move(50, 50) + # Indica a b di chiamare questa funzione quando si fa clic +    # notare la mancanza di "()" sulla chiamata di funzione + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Questa funzione dovrebbe creare una finestra di dialogo con un pulsante +# che aspetta di essere cliccato e quindi esce dal programma +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Questa modalità dice al popup di bloccare il genitore, mentre è attivo + d.setWindowModality(Qt.ApplicationModal) + # Al click vorrei che l'intero processo finisse + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` -- cgit v1.2.3 From 6f7caa6caac87f2086277fb0856ea668717ab18a Mon Sep 17 00:00:00 2001 From: Yogesh Ojha Date: Sat, 13 Oct 2018 20:11:59 +0530 Subject: Update opencv.html.markdown --- opencv.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 7b61d2cd..9f81ee28 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -13,9 +13,10 @@ Opencv currently supports wide variety of languages like, C++, Python, Java etc #### Installation Please refer to these articles for installation of OpenCV on your computer. -* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows] -* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a] -* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv] + +* Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() +* Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() +* Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() ### Here we will be focusing on python implementation of OpenCV ```python # Reading image in OpenCV @@ -130,12 +131,12 @@ cv2.destroyAllWindows() ### Further Reading: -* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades] -* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html] -* An up-to-date language reference can be found at [https://opencv.org] -* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV] +* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]() +* OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() +* An up-to-date language reference can be found at [https://opencv.org]() +* Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV]() * Good OpenCv Tutorials - * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html] - * [https://realpython.com/python-opencv-color-spaces] - * [https://pyimagesearch.com] - * [https://www.learnopencv.com] + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() + * [https://realpython.com/python-opencv-color-spaces]() + * [https://pyimagesearch.com]() + * [https://www.learnopencv.com]() -- cgit v1.2.3 From 3388a561e5fddf03d2ca3175748cab4f149751ec Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sat, 13 Oct 2018 18:11:11 +0200 Subject: [toml/it] Add it-IT translation for TOML --- it-it/toml-it.html.markdown | 276 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 276 insertions(+) create mode 100644 it-it/toml-it.html.markdown diff --git a/it-it/toml-it.html.markdown b/it-it/toml-it.html.markdown new file mode 100644 index 00000000..99082048 --- /dev/null +++ b/it-it/toml-it.html.markdown @@ -0,0 +1,276 @@ +--- +language: toml +filename: learntoml-it.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la +serializzazione di dati, progettato per i file di configurazione. + +È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile +per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza +semplice nella maggior parte dei linguaggi di programmazione, in quanto è +progettato per essere tradotto senza ambiguità in una hash table. + +Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è +ancora stabile. Questo documento utilizza TOML 0.4.0. + +```toml +# I commenti in TOML sono fatti così. + +################ +# TIPI SCALARI # +################ + +# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa, +# anche chiamata dizionario, hash o oggetto in altri linguaggi. + +# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga, +# eccetto per alcuni tipi di valori. +key = "value" +stringa = "ciao" +numero = 42 +float = 3.14 +boolean = true +data = 1979-05-27T07:32:00-08:00 +notazScientifica = 1e+12 +"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure ' +"la key può contenere" = "lettere, numeri, underscore e trattini" + +############ +# Stringhe # +############ + +# Le stringhe possono contenere solo caratteri UTF-8 validi. +# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze +# di escape compatte. Ad esempio, \t corrisponde al TAB. +stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"." + +stringaMultiriga = """ +Racchiusa da tre virgolette doppie all'inizio e +alla fine - consente di andare a capo.""" + +stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.' + +stringaMultirigaLiteral = ''' +Racchiusa da tre virgolette singole all'inizio e +alla fine - consente di andare a capo. +Anche in questo caso non si può fare escape. +Il primo ritorno a capo viene eliminato. + Tutti gli altri spazi aggiuntivi + vengono mantenuti. +''' + +# Per i dati binari è consigliabile utilizzare Base64 e +# gestirli manualmente dall'applicazione. + +########## +# Interi # +########## + +## Gli interi possono avere o meno un segno (+, -). +## Non si possono inserire zero superflui all'inizio. +## Non è possibile inoltre utilizzare valori numerici +## non rappresentabili con una sequenza di cifre. +int1 = +42 +int2 = 0 +int3 = -21 + +## Puoi utilizzare gli underscore per migliorare la leggibilità. +## Fai attenzione a non inserirne due di seguito. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALIDO, ma da evitare + +######### +# Float # +######### + +# I float permettono di rappresentare numeri decimali. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +# I valori boolean (true/false) devono essere scritti in minuscolo. +bool1 = true +bool2 = false + +############ +# Data/ora # +############ + +data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC) +data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset + +###################### +# TIPI DI COLLECTION # +###################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Le", "virgole", "sono", "delimitatori" ] +array3 = [ "Non", "unire", "tipi", "diversi" ] +array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ] +array5 = [ + "Gli spazi vuoti", "sono", "ignorati" +] + +########### +# Tabelle # +########### + +# Le tabelle (o hash table o dizionari) sono collection di coppie key/value. +# Iniziano con un nome tra parentesi quadre su una linea separata. +# Le tabelle vuote (senza alcun valore) sono valide. +[tabella] + +# Tutti i valori che si trovano sotto il nome della tabella +# appartengono alla tabella stessa (finchè non ne viene creata un'altra). +# L'ordine di questi valori non è garantito. +[tabella-1] +key1 = "una stringa" +key2 = 123 + +[tabella-2] +key1 = "un'altra stringa" +key2 = 456 + +# Utilizzando i punti è possibile creare delle sottotabelle. +# Ogni parte suddivisa dai punti segue le regole delle key per il nome. +[tabella-3."sotto.tabella"] +key1 = "prova" + +# Ecco l'equivalente JSON della tabella precedente: +# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } } + +# Gli spazi non vengono considerati, ma è consigliabile +# evitare di usare spazi superflui. +[a.b.c] # consigliato +[ d.e.f ] # identico a [d.e.f] + +# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella. +# [x] queste +# [x.y] non +# [x.y.z] servono +[x.y.z.w] # per creare questa tabella + +# Se non è stata già creata prima, puoi anche creare +# una tabella superiore più avanti. +[a.b] +c = 1 + +[a] +d = 2 + +# Non puoi definire una key o una tabella più di una volta. + +# ERRORE +[a] +b = 1 + +[a] +c = 2 + +# ERRORE +[a] +b = 1 + +[a.b] +c = 2 + +# I nomi delle tabelle non possono essere vuoti. +[] # NON VALIDO +[a.] # NON VALIDO +[a..b] # NON VALIDO +[.b] # NON VALIDO +[.] # NON VALIDO + +################## +# Tabelle inline # +################## + +tabelleInline = { racchiuseData = "{ e }", rigaSingola = true } +punto = { x = 1, y = 2 } + +#################### +# Array di tabelle # +#################### + +# Un array di tabelle può essere creato utilizzando due parentesi quadre. +# Tutte le tabelle con questo nome saranno elementi dell'array. +# Gli elementi vengono inseriti nell'ordine in cui si trovano. + +[[prodotti]] +nome = "array di tabelle" +sku = 738594937 +tabelleVuoteValide = true + +[[prodotti]] + +[[prodotti]] +nome = "un altro item" +sku = 284758393 +colore = "grigio" + +# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie +# parentesi quadre apparterranno alla tabella più vicina sopra di esse. + +[[frutta]] + nome = "mela" + + [frutto.geometria] + forma = "sferica" + nota = "Sono una proprietà del frutto" + + [[frutto.colore]] + nome = "rosso" + nota = "Sono un oggetto di un array dentro mela" + + [[frutto.colore]] + nome = "verde" + nota = "Sono nello stesso array di rosso" + +[[frutta]] + nome = "banana" + + [[frutto.colore]] + nome = "giallo" + nota = "Anche io sono un oggetto di un array, ma dentro banana" +``` + +Ecco l'equivalente JSON dell'ultima tabella: + +```json +{ + "frutta": [ + { + "nome": "mela", + "geometria": { "forma": "sferica", "nota": "..."}, + "colore": [ + { "nome": "rosso", "nota": "..." }, + { "nome": "verde", "nota": "..." } + ] + }, + { + "nome": "banana", + "colore": [ + { "nome": "giallo", "nota": "..." } + ] + } + ] +} +``` + +### Altre risorse + ++ [Repository ufficiale di TOML](https://github.com/toml-lang/toml) -- cgit v1.2.3 From 2242ad7a1796bf3c9e25a0ec977620c05ac15c58 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 13 Oct 2018 22:28:57 +0530 Subject: add C++ resource --- c++.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index 8d1c7a26..579aabf5 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1131,3 +1131,5 @@ An up-to-date language reference can be found at Additional resources may be found at + +A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). -- cgit v1.2.3 From e0b768c713e2a0f6fdac61db825bb30bdbbb2f30 Mon Sep 17 00:00:00 2001 From: jhaasdijk Date: Sat, 13 Oct 2018 22:55:36 +0200 Subject: [dynamic-programming/nl-nl] Add Dutch language for dynamic-programming --- nl-nl/dynamic-programming-nl.html.markdown | 55 ++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 nl-nl/dynamic-programming-nl.html.markdown diff --git a/nl-nl/dynamic-programming-nl.html.markdown b/nl-nl/dynamic-programming-nl.html.markdown new file mode 100644 index 00000000..aeee937a --- /dev/null +++ b/nl-nl/dynamic-programming-nl.html.markdown @@ -0,0 +1,55 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Jasper Haasdijk", "https://github.com/jhaasdijk"] +lang: nl-nl +--- + +# Dynamisch Programmeren + +## Introductie + +Dynamisch programmeren is een krachtige techniek die, zoals we zullen zien, gebruikt kan worden om een bepaalde klasse van problemen op te lossen. Het idee is eenvoudig. Als je een oplossing hebt voor een probleem met een bepaalde input, sla dit resultaat dan op. Hiermee kan je voorkomen dat je in de toekomst nog een keer hetzelfde probleem moet gaan oplossen omdat je het resultaat vergeten bent. + +Onthoud altijd! +"Zij die het verleden niet kunnen herinneren, zijn gedoemd het te herhalen." + +## Verschillende aanpakken + +1. *Top-Down* : Oftewel, van boven naar beneden. Begin je oplossing met het afbreken van het probleem in kleine stukken. Kom je een stukje tegen dat je eerder al hebt opgelost, kijk dan enkel naar het opgeslagen antwoord. Kom je een stukje tegen dat je nog niet eerder hebt opgelost, los het op en sla het antwoord op. Deze manier is voor veel mensen de makkelijke manier om erover na te denken, erg intuitief. Deze methode wordt ook wel Memoization genoemd. + +2. *Bottom-Up* : Oftewel, van beneden naar boven. Analyseer het probleem en bekijk de volgorde waarin de sub-problemen opgelost kunnen worden. Begin met het oplossen van de triviale gevallen en maak zodoende de weg naar het gegeven probleem. In dit process is het gegarandeerd dat de sub-problemen eerder worden opgelost dan het gegeven probleem. Deze methode wordt ook wel Dynamisch Programmeren genoemd. + +## Voorbeeld van Dynamisch Programmeren + +Het langst stijgende sequentie probleem is het probleem waarbij je binnen een bepaalde reeks op zoek bent naar het langste aaneengesloten stijgende stuk. Gegeven een reeks `S = {a1 , a2 , a3, a4, ............., an-1, an }` zijn we op zoek naar het langst aaneengesloten stuk zodanig dat voor alle `j` en `i`, `j a[j] and LS[i] Date: Sun, 14 Oct 2018 05:26:21 +0530 Subject: Fix links and list styling --- c++.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 579aabf5..9d6470be 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1127,9 +1127,6 @@ compl 4 // Performs a bitwise not ``` Further Reading: -An up-to-date language reference can be found at - - -Additional resources may be found at - -A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). +* An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). +* Additional resources may be found at [CPlusPlus](http://cplusplus.com). +* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). -- cgit v1.2.3 From 4194b7b4561eda9cf9663c0e70a3b7de4bb25821 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:31:59 +0530 Subject: Fix links and list styling --- es-es/c++-es.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index bd1ad07c..9627c183 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -823,7 +823,5 @@ v.swap(vector()); ``` Otras lecturas: -Una referencia del lenguaje hasta a la fecha se puede encontrar en - - -Recursos adicionales se pueden encontrar en +* Una referencia del lenguaje hasta a la fecha se puede encontrar en [CPP Reference](http://cppreference.com/w/cpp). +* Recursos adicionales se pueden encontrar en [[CPlusPlus]](http://cplusplus.com). -- cgit v1.2.3 From 4b9c35047b54d4e886011cffd4adce015584f846 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:33:23 +0530 Subject: Fix links and list styling --- fr-fr/c++-fr.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown index acbaed58..8cd494e8 100644 --- a/fr-fr/c++-fr.html.markdown +++ b/fr-fr/c++-fr.html.markdown @@ -910,7 +910,5 @@ v.swap(vector()); ``` Lecture complémentaire : -Une référence à jour du langage est disponible à - - -Des ressources supplémentaires sont disponibles à +* Une référence à jour du langage est disponible à [CPP Reference](http://cppreference.com/w/cpp). +* Des ressources supplémentaires sont disponibles à [CPlusPlus](http://cplusplus.com). -- cgit v1.2.3 From 4de5670652ce33d8b7959e35da5ca52e07d1ffc9 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:34:24 +0530 Subject: Fix links and list styling --- it-it/c++-it.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index b4f9c50e..c20d4e38 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1130,7 +1130,5 @@ compl 4 // Effettua il NOT bit-a-bit ``` Letture consigliate: -Un riferimento aggiornato del linguaggio può essere trovato qui - - -Risorse addizionali possono essere trovate qui +* Un riferimento aggiornato del linguaggio può essere trovato qui [CPP Reference](http://cppreference.com/w/cpp). +* Risorse addizionali possono essere trovate qui [CPlusPlus](http://cplusplus.com). -- cgit v1.2.3 From 44663fba02c5c5f1f70112c8a5a3610334ef90ee Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:35:29 +0530 Subject: Fix links and list styling --- pt-br/c++-pt.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 2c15e92c..cefa2c64 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -609,7 +609,5 @@ h=sum(f,g); ``` Leitura Adicional: -Uma referência atualizada da linguagem pode ser encontrada em - - -Uma fonte adicional pode ser encontrada em +* Uma referência atualizada da linguagem pode ser encontrada em [CPP Reference](http://cppreference.com/w/cpp). +* Uma fonte adicional pode ser encontrada em [CPlusPlus](http://cplusplus.com). -- cgit v1.2.3 From 59c13bdfa25f8cf28735aaeef6e88783a3b221ff Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:36:28 +0530 Subject: Fix links and list styling --- ru-ru/c++-ru.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index b9704fc3..036db5cf 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -886,7 +886,5 @@ v.swap(vector()); ``` ## Дальнейшее чтение: -Наиболее полное и обновленное руководство по С++ можно найти на - - -Дополнительные ресурсы могут быть найдены на +* Наиболее полное и обновленное руководство по С++ можно найти на [CPP Reference](http://cppreference.com/w/cpp). +* Дополнительные ресурсы могут быть найдены на [CPlusPlus](http://cplusplus.com). -- cgit v1.2.3 From 0c1260369e99cb0c604bf43c8be2da7047459cac Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:37:43 +0530 Subject: Fix links and list styling --- tr-tr/c++-tr.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index 2c841456..89aa620b 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1071,7 +1071,5 @@ compl 4 // Bit seviyesinde değil işlemini gerçekleştirir ``` İleri okuma: -Güncel bir referans - adresinde bulunabilir - -Ek kaynaklar adresinde bulunabilir +* Güncel bir referans [CPP Reference](http://cppreference.com/w/cpp) adresinde bulunabilir. +* Ek kaynaklar [CPlusPlus](http://cplusplus.com) adresinde bulunabilir. -- cgit v1.2.3 From 8425ef331338831db286723b579c4fe1273b5ab6 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:38:53 +0530 Subject: Fix links and list styling --- zh-cn/c++-cn.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 87951bc3..51ffa02f 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -567,6 +567,5 @@ void doSomethingWithAFile(const std::string& filename) ``` 扩展阅读: - 提供了最新的语法参考。 - -可以在 找到一些补充资料。 +* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 +* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 -- cgit v1.2.3 From 99618d394e33c51ed8073b2dc013623442201c51 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:51:14 +0530 Subject: Add new link from 2242ad7 --- es-es/c++-es.html.markdown | 1 + fr-fr/c++-fr.html.markdown | 1 + it-it/c++-it.html.markdown | 1 + pt-br/c++-pt.html.markdown | 1 + ru-ru/c++-ru.html.markdown | 1 + tr-tr/c++-tr.html.markdown | 1 + zh-cn/c++-cn.html.markdown | 1 + 7 files changed, 7 insertions(+) diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown index 9627c183..2c3762d5 100644 --- a/es-es/c++-es.html.markdown +++ b/es-es/c++-es.html.markdown @@ -825,3 +825,4 @@ Otras lecturas: * Una referencia del lenguaje hasta a la fecha se puede encontrar en [CPP Reference](http://cppreference.com/w/cpp). * Recursos adicionales se pueden encontrar en [[CPlusPlus]](http://cplusplus.com). +* Un tutorial que cubre los conceptos básicos del lenguaje y la configuración del entorno de codificación está disponible en [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FF). diff --git a/fr-fr/c++-fr.html.markdown b/fr-fr/c++-fr.html.markdown index 8cd494e8..863162f7 100644 --- a/fr-fr/c++-fr.html.markdown +++ b/fr-fr/c++-fr.html.markdown @@ -912,3 +912,4 @@ Lecture complémentaire : * Une référence à jour du langage est disponible à [CPP Reference](http://cppreference.com/w/cpp). * Des ressources supplémentaires sont disponibles à [CPlusPlus](http://cplusplus.com). +* Un tutoriel couvrant les bases du langage et la configuration d'un environnement de codage est disponible à l'adresse [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index c20d4e38..449aebfb 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1132,3 +1132,4 @@ Letture consigliate: * Un riferimento aggiornato del linguaggio può essere trovato qui [CPP Reference](http://cppreference.com/w/cpp). * Risorse addizionali possono essere trovate qui [CPlusPlus](http://cplusplus.com). +* Un tutorial che copre le basi del linguaggio e l'impostazione dell'ambiente di codifica è disponibile su [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index cefa2c64..42a29991 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -611,3 +611,4 @@ Leitura Adicional: * Uma referência atualizada da linguagem pode ser encontrada em [CPP Reference](http://cppreference.com/w/cpp). * Uma fonte adicional pode ser encontrada em [CPlusPlus](http://cplusplus.com). +* Um tutorial cobrindo o básico da linguagem e configurando o ambiente de codificação está disponível em [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 036db5cf..35994749 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -888,3 +888,4 @@ v.swap(vector()); * Наиболее полное и обновленное руководство по С++ можно найти на [CPP Reference](http://cppreference.com/w/cpp). * Дополнительные ресурсы могут быть найдены на [CPlusPlus](http://cplusplus.com). +* Учебник, посвященный основам языка и настройке среды кодирования, доступен в [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index 89aa620b..9d65cf9c 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1073,3 +1073,4 @@ compl 4 // Bit seviyesinde değil işlemini gerçekleştirir * Güncel bir referans [CPP Reference](http://cppreference.com/w/cpp) adresinde bulunabilir. * Ek kaynaklar [CPlusPlus](http://cplusplus.com) adresinde bulunabilir. +* Dilin temellerini ve kodlama ortamını belirleyen bir öğretici [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb) adresinde bulunabilir. diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 51ffa02f..e0d6b6fe 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -569,3 +569,4 @@ void doSomethingWithAFile(const std::string& filename) * [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 * 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 +* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。 -- cgit v1.2.3 From f32d2f366eaf18010e7364bcd2e90fc85c6c3c02 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 05:59:24 +0530 Subject: Fix links --- dynamic-programming.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index 4db8e92e..aed169fc 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -42,9 +42,9 @@ for i=0 to n-1 ### Some Famous DP Problems -- Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Resources -- cgit v1.2.3 From c5df041f3117659a6c7cbad4020886e29bf3282f Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:02:26 +0530 Subject: Fix links --- de-de/dynamic-programming-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index 801d2514..afa9a17c 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -68,9 +68,9 @@ for i=0 to n-1 ### Einige bekannte DP Probleme -- Floyd Warshall Algorithm - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) -- Integer Knapsack Problem - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) -- Longest Common Subsequence - [Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Ressourcen -- cgit v1.2.3 From 3359cb0a20d96ad9507e12bbabd7744920d26c28 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:04:13 +0530 Subject: Fix links --- fr-fr/dynamic-programming-fr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index b3660ac9..54cca001 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -42,9 +42,9 @@ Le même concept peut être appliqué pour trouver le chemin le plus long dans u ### Problèmes classiques de programmation dynamique -- L'algorithme de Floyd Warshall(EN)) - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Problème du sac à dos(EN) - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Problème du sac à dos(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Resources -- cgit v1.2.3 From 494eb90fca764cb5a2f5e169d609cc8ef98c679d Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:05:25 +0530 Subject: Fix links --- it-it/dynamic-programming-it.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/it-it/dynamic-programming-it.html.markdown b/it-it/dynamic-programming-it.html.markdown index 963d096c..9c7bd9b6 100644 --- a/it-it/dynamic-programming-it.html.markdown +++ b/it-it/dynamic-programming-it.html.markdown @@ -45,9 +45,10 @@ for i=0 to n-1 ### Alcuni famosi problemi DP -- Floyd Warshall Algorithm - Tutorial e Codice sorgente in C del programma: http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Integer Knapsack Problem - Tutorial e Codice sorgente in C del programma: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Longest Common Subsequence - Tutorial e Codice sorgente in C del programma: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- Floyd Warshall Algorithm - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + ## Risorse online -- cgit v1.2.3 From c1a4445894cdd010e85c80144cb9cc8619963d30 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:06:05 +0530 Subject: Fix links --- nl-nl/dynamic-programming-nl.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-nl/dynamic-programming-nl.html.markdown b/nl-nl/dynamic-programming-nl.html.markdown index aeee937a..5186a3bf 100644 --- a/nl-nl/dynamic-programming-nl.html.markdown +++ b/nl-nl/dynamic-programming-nl.html.markdown @@ -46,9 +46,9 @@ for i=0 to n-1 ### Enkele beroemde DP problemen -- Floyd Warshall Algorithm - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -- Longest Common Subsequence - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() ## Online Bronnen -- cgit v1.2.3 From b3da5ca955bd3ad47ab6a7ec1c72f2b189b2335e Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:07:03 +0530 Subject: Fix links --- pt-br/dynamic-programming-pt.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 84b055d9..518660a3 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -63,13 +63,11 @@ grafo acíclico dirigido. ``` ## Alguns Problemas Famosos de Programação Dinâmica -``` -Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code - -Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem -Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence -``` +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() + ## Recursos Online (EN) -- cgit v1.2.3 From 8f2d9dcf83230b9cd59212a46ae98fbd4813b830 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:09:03 +0530 Subject: Fix links --- tr-tr/dynamic-programming-tr.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown index 606ecf04..f5744f7d 100644 --- a/tr-tr/dynamic-programming-tr.html.markdown +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -41,9 +41,10 @@ for i=0 to n-1 ``` Bazı Ünlü Dinamik Programlama Problemleri --Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs—floyd-warshall-algorithm-with-c-program-source-code --Integer Knapsack Problem - Tutorial and C Program source code: http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—the-integer-knapsack-problem --Longest Common Subsequence - Tutorial and C Program source code : http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming—longest-common-subsequence + +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() Online Kaynaklar -https://www.codechef.com/wiki/tutorial-dynamic-programming +- [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) -- cgit v1.2.3 From b4647a6eb3b123d12f4469d308268e536c79341c Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 14 Oct 2018 06:23:58 +0530 Subject: Fix formatting errors --- tr-tr/dynamic-programming-tr.html.markdown | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown index f5744f7d..e6a734a7 100644 --- a/tr-tr/dynamic-programming-tr.html.markdown +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -8,24 +8,28 @@ translators: lang: tr-tr --- -Dinamik Programlama -Giriş +# Dinamik Programlama + +## Giriş + Dinamik Programlama, göreceğimiz gibi belirli bir problem sınıfını çözmek için kullanılan güçlü bir tekniktir. Fikir çok basittir, verilen girdiyle ilgili bir sorunu çözdüyseniz, aynı sorunun tekrar çözülmesini önlemek için sonucunu gelecekte referans olarak kaydedilmesine dayanır. Her zaman hatırla! "Geçmiş hatırlayamayanlar, aynı şeyleri tekrar yaşamaya mahkumlardır!" -Bu tür sorunların çözüm yolları +## Bu tür sorunların çözüm yolları -1-Yukarıdan aşağıya: +1. Yukarıdan aşağıya: Verilen problemi çözerek çözmeye başlayın. Sorunun zaten çözüldüğünü görürseniz, kaydedilen cevabı döndürmeniz yeterlidir. Çözülmemişse, çözünüz ve cevabı saklayınız. Bu genellikle düşünmek kolaydır ve çok sezgiseldir. Buna Ezberleştirme denir. -2-Aşağıdan yukarıya: +2. Aşağıdan yukarıya: Sorunu analiz edin ve alt problemlerin çözülme sırasını görün ve önemsiz alt sorundan verilen soruna doğru başlayın. Bu süreçte, problemi çözmeden önce alt problemlerin çözülmesi gerekmektedir. Buna Dinamik Programlama denir. -Örnek -En Uzun Artan Subsequence problemi belirli bir dizinin en uzun artan alt dizini bulmaktır. S = {a1, a2, a3, a4, ............., an-1} dizisi göz önüne alındığında, en uzun bir alt kümeyi bulmak zorundayız, böylece tüm j ve i, j için Date: Sun, 14 Oct 2018 12:40:30 +0530 Subject: Added new empty line --- opencv.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/opencv.html.markdown b/opencv.html.markdown index 9f81ee28..f8763b35 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -17,7 +17,9 @@ Please refer to these articles for installation of OpenCV on your computer. * Windows Installation Instructions: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() * Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() * Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() + ### Here we will be focusing on python implementation of OpenCV + ```python # Reading image in OpenCV import cv2 -- cgit v1.2.3 From e3ae8a048f279b779ef4eb8d07daaf5578a63d4c Mon Sep 17 00:00:00 2001 From: bonte <6319051+abonte@users.noreply.github.com> Date: Sun, 14 Oct 2018 11:31:47 +0200 Subject: add translation [ruby/it] --- it-it/ruby-it.html.markdown | 642 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 642 insertions(+) create mode 100644 it-it/ruby-it.html.markdown diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown new file mode 100644 index 00000000..c082a987 --- /dev/null +++ b/it-it/ruby-it.html.markdown @@ -0,0 +1,642 @@ +--- +language: ruby +filename: learnruby-it.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] + - ["Corey Ward", "https://github.com/coreyward"] +lang: it-it +--- + +```ruby +# Questo è un commento + +# In Ruby, (quasi) tutto è un oggetto. +# Questo include i numeri... +3.class #=> Integer + +# ...stringhe... +"Hello".class #=> String + +# ...e anche i metodi! +"Hello".method(:class).class #=> Method + +# Qualche operazione aritmetica di base +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2 ** 5 #=> 32 +5 % 3 #=> 2 + +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# L'aritmetica è solo zucchero sintattico +# per chiamare il metodo di un oggetto +1.+(3) #=> 4 +10.* 5 #=> 50 +100.methods.include?(:/) #=> true + +# I valori speciali sono oggetti +nil # equivalente a null in altri linguaggi +true # vero +false # falso + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Uguaglianza +1 == 1 #=> true +2 == 1 #=> false + +# Disuguaglianza +1 != 1 #=> false +2 != 1 #=> true + +# nil è l'unico valore, oltre a false, che è considerato 'falso' +!!nil #=> false +!!false #=> false +!!0 #=> true +!!"" #=> true + +# Altri confronti +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Operatori di confronto combinati (ritorna '1' quando il primo argomento è più grande, +# '-1' quando il secondo argomento è più grande, altrimenti '0') +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Operatori logici +true && false #=> false +true || false #=> true + +# Ci sono versioni alternative degli operatori logici con meno precedenza. +# Sono usati come costrutti per il controllo di flusso per concatenare +# insieme statement finché uno di essi ritorna true o false. + +# `do_something_else` chiamato solo se `do_something` ha successo. +do_something() and do_something_else() +# `log_error` è chiamato solo se `do_something` fallisce. +do_something() or log_error() + +# Interpolazione di stringhe + +placeholder = 'usare l\'interpolazione di stringhe' +"Per #{placeholder} si usano stringhe con i doppi apici" +#=> "Per usare l'interpolazione di stringhe si usano stringhe con i doppi apici" + +# E' possibile combinare le stringhe usando `+`, ma non con gli altri tipi +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" +"hello #{3}" #=> "hello 3" + +# ...oppure combinare stringhe e operatori +'ciao ' * 3 #=> "ciao ciao ciao " + +# ...oppure aggiungere alla stringa +'ciao' << ' mondo' #=> "ciao mondo" + +# Per stampare a schermo e andare a capo +puts "Sto stampando!" +#=> Sto stampando! +#=> nil + +# Per stampare a schermo senza andare a capo +print "Sto stampando!" +#=> Sto stampando! => nil + +# Variabili +x = 25 #=> 25 +x #=> 25 + +# Notare che l'assegnamento ritorna il valore assegnato. +# Questo significa che è possibile effettuare assegnamenti multipli: +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Per convenzione si usa lo snake_case per i nomi delle variabili +snake_case = true + +# Usare nomi delle variabili descrittivi +path_to_project_root = '/buon/nome/' +m = '/nome/scadente/' + +# I simboli sono immutabili, costanti riusabili rappresentati internamente da +# un valore intero. Sono spesso usati al posto delle stringhe per comunicare +# specifici e significativi valori. + +:pendente.class #=> Symbol + +stato = :pendente + +stato == :pendente #=> true + +stato == 'pendente' #=> false + +stato == :approvato #=> false + +# Le stringhe possono essere convertite in simboli e viceversa: +status.to_s #=> "pendente" +"argon".to_sym #=> :argon + +# Arrays + +# Questo è un array +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Gli array possono contenere diversi tipi di elementi +[1, 'hello', false] #=> [1, "hello", false] + +# Gli array possono essere indicizzati +# Dall'inizio... +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + + +# ...o dalla fine... +array[-1] #=> 5 +array.last #=> 5 + +# With a start index and length +# ...o con un indice di inzio e la lunghezza... +array[2, 3] #=> [3, 4, 5] + +# ...oppure con un intervallo. +array[1..3] #=> [2, 3, 4] + +# Invertire l'ordine degli elementi di un array +a = [1,2,3] +a.reverse! #=> [3,2,1] + +# Come per l'aritmetica, l'accesso tramite [var] +# è solo zucchero sintattico +# per chiamare il metodo '[]'' di un oggetto +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Si può aggiungere un elemento all'array così +array << 6 #=> [1, 2, 3, 4, 5, 6] +# oppure così +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Controllare se un elemento esiste in un array +array.include?(1) #=> true + +# Hash è un dizionario con coppie di chiave e valore +# Un hash è denotato da parentesi graffe: +hash = { 'colore' => 'verde', 'numero' => 5 } + +hash.keys #=> ['colore', 'numero'] + +# E' possibile accedere all'hash tramite chiave: +hash['colore'] #=> 'verde' +hash['numero'] #=> 5 + +# Accedere all'hash con una chiave che non esiste ritorna nil: +hash['nothing here'] #=> nil + +# Quando si usano simboli come chiavi di un hash, si possono utilizzare queste sintassi: + +hash = { :defcon => 3, :action => true } +hash.keys #=> [:defcon, :action] +# oppure +hash = { defcon: 3, action: true } +hash.keys #=> [:defcon, :action] + +# Controllare l'esistenza di una chiave o di un valore in un hash +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true + +# Suggerimento: sia gli array che gli hash sono enumerabili! +# Entrambi possiedono metodi utili come each, map, count e altri. + +# Strutture di controllo + +#Condizionali +if true + 'if statement' +elsif false + 'else if, opzionale' +else + 'else, opzionale' +end + +#Cicli +# In Ruby, i tradizionali cicli `for` non sono molto comuni. Questi semplici cicli, invece, +# sono implementati con un enumerable, usando `each`: +(1..5).each do |contatore| + puts "iterazione #{contatore}" +end + +# Esso è equivalente a questo ciclo, il quale è inusuale da vedere in Ruby: +for contatore in 1..5 + puts "iterazione #{contatore}" +end + +# Il costrutto `do |variable| ... end` è chiamato 'blocco'. I blocchi +# sono simili alle lambda, funzioni anonime o closure che si trovano in altri +# linguaggi di programmazione. Essi possono essere passati come oggetti, +# chiamati o allegati come metodi. +# +# Il metodo 'each' di un intervallo (range) esegue il blocco una volta +# per ogni elemento dell'intervallo. +# Al blocco è passato un contatore come parametro. + +# E' possibile inglobare il blocco fra le parentesi graffe +(1..5).each { |contatore| puts "iterazione #{contatore}" } + +# Il contenuto delle strutture dati può essere iterato usando "each". +array.each do |elemento| + puts "#{elemento} è parte dell'array" +end +hash.each do |chiave, valore| + puts "#{chiave} è #{valore}" +end + +# If you still need an index you can use 'each_with_index' and define an index +# variable +# Se comunque si vuole un indice, si può usare "each_with_index" e definire +# una variabile che contiene l'indice +array.each_with_index do |elemento, indice| + puts "#{elemento} è il numero #{index} nell'array" +end + +contatore = 1 +while contatore <= 5 do + puts "iterazione #{contatore}" + contatore += 1 +end +#=> iterazione 1 +#=> iterazione 2 +#=> iterazione 3 +#=> iterazione 4 +#=> iterazione 5 + +# Esistono in Ruby ulteriori funzioni per fare i cicli, +# come per esempio 'map', 'reduce', 'inject' e altri. +# Nel caso di 'map', esso prende l'array sul quale si sta iterando, +# esegue le istruzioni definite nel blocco, e ritorna un array completamente nuovo. +array = [1,2,3,4,5] +doubled = array.map do |elemento| + elemento * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +# Costrutto "case" +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# 'case' può usare anche gli intervalli +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Gestione delle eccezioni +begin + # codice che può sollevare un eccezione + raise NoMemoryError, 'Esaurita la memoria.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError è stato sollevato.', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError è stato sollvato.' +else + puts 'Questo viene eseguito se nessuna eccezione è stata sollevata.' +ensure + puts 'Questo codice viene sempre eseguito a prescindere.' +end + +# Metodi + +def double(x) + x * 2 +end + +# Metodi (e blocchi) ritornano implicitamente il valore dell'ultima istruzione +double(2) #=> 4 + +# Le parentesi sono opzionali dove l'interpolazione è inequivocabile +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Gli argomenit dei metodi sono separati dalla virgola +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Tutti i metodi hanno un implicito e opzionale parametro del blocco. +# Esso può essere chiamato con la parola chiave 'yield'. + +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + +# I blocchi possono essere convertiti in 'proc', il quale racchiude il blocco +# e gli permette di essere passato ad un altro metodo, legato ad uno scope +# differente o modificato. Questo è molto comune nella lista parametri del +# metodo, dove è frequente vedere il parametro '&block' in coda. Esso accetta +# il blocco, se ne è stato passato uno, e lo converte in un 'Proc'. Qui la denominazione +# è una convenzione; funzionerebbe anche con '&ananas'. +def guests(&block) + block.class #=> Proc + block.call(4) +end + +# Il metodo 'call' del Proc è simile chiamare 'yield' quando è presente un blocco. +# Gli argomenti passati a 'call' sono inoltrati al blocco come argomenti: + +guests { |n| "You have #{n} guests." } +# => "You have 4 guests." + +# L'operatore splat ("*") consente di convertire una lista di argomenti in un array +def guests(*array) + array.each { |guest| puts guest } +end + +# Destrutturazione + +# Ruby destruttura automaticamente gli array in assegnamento a variabili multiple: +a, b, c = [1, 2, 3] +a #=> 1 +b #=> 2 +c #=> 3 + +# In alcuni casi si usa l'operatore splat ("*") per destrutturare un array in una lista. +classifica_concorrenti = ["John", "Sally", "Dingus", "Moe", "Marcy"] + +def migliore(primo, secondo, terzo) + puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}." +end + +migliore *classifica_concorrenti.first(3) #=> I vincitori sono John, Sally, e Dingus. + +# The splat operator can also be used in parameters: +def migliore(primo, secondo, terzo, *altri) + puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}." + puts "C'erano altri #{altri.count} partecipanti." +end + +migliore *classifica_concorrenti +#=> I vincitori sono John, Sally, e Dingus. +#=> C'erano altri 2 partecipanti. + +# Per convenzione, tutti i metodi che ritornano un booleano terminano con un punto interrogativo +5.even? #=> false +5.odd? #=> true + +# Per convenzione, se il nome di un metodo termina con un punto esclamativo, +# esso esegue qualcosa di distruttivo. Molti metodi hanno una versione con '!' +# per effettuare una modifiche, e una versione senza '!' che ritorna +# una versione modificata. +nome_azienda = "Dunder Mifflin" +nome_azienda.upcase #=> "DUNDER MIFFLIN" +nome_azienda #=> "Dunder Mifflin" +# Questa volta modifichiamo nome_azienda +nome_azienda.upcase! #=> "DUNDER MIFFLIN" +nome_azienda #=> "DUNDER MIFFLIN" + +# Classi + +# Definire una classe con la parola chiave class +class Umano + + # Una variabile di classe. E' condivisa da tutte le istance di questa classe. + @@specie = 'H. sapiens' + + # Inizializzatore di base + def initialize(nome, eta = 0) + # Assegna il valore dell'argomento alla variabile dell'istanza "nome" + @nome = nome + # Se l'età non è fornita, verrà assegnato il valore di default indicato nella lista degli argomenti + @eta = eta + end + + # Metodo setter di base + def nome=(nome) + @nome = nome + end + + # Metodo getter di base + def nome + @nome + end + + # Le funzionalità di cui sopra posso essere incapsulate usando il metodo attr_accessor come segue + attr_accessor :nome + + # Getter/setter possono anche essere creati individualmente + attr_reader :nome + attr_writer :nome + + # Un metodo della classe usa 'self' per distinguersi dai metodi dell'istanza. + # Può essere richimato solo dalla classe, non dall'istanza. + def self.say(msg) + puts msg + end + + def specie + @@specie + end +end + + +# Instanziare una classe +jim = Umano.new('Jim Halpert') + +dwight = Umano.new('Dwight K. Schrute') + +# Chiamiamo qualche metodo +jim.specie #=> "H. sapiens" +jim.nome #=> "Jim Halpert" +jim.nome = "Jim Halpert II" #=> "Jim Halpert II" +jim.nome #=> "Jim Halpert II" +dwight.specie #=> "H. sapiens" +dwight.nome #=> "Dwight K. Schrute" + +# Chiamare un metodo della classe +Umano.say('Ciao') #=> "Ciao" + +# La visibilità della variabile (variable's scope) è determinata dal modo in cui le viene assegnato il nome +# Variabili che iniziano con $ hanno uno scope globale +$var = "Sono una variabile globale" +defined? $var #=> "global-variable" + +# Variabili che inziano con @ hanno a livello dell'istanza +@var = "Sono una variabile dell'istanza" +defined? @var #=> "instance-variable" + +# Variabili che iniziano con @@ hanno una visibilità a livello della classe +@@var = "Sono una variabile della classe" +defined? @@var #=> "class variable" + +# Variabili che iniziano con una lettera maiuscola sono costanti +Var = "Sono una costante" +defined? Var #=> "constant" + +# Anche una classe è un oggetto in ruby. Quindi la classe può avere una variabile dell'istanza. +# Le variabili della classe sono condivise fra la classe e tutti i suoi discendenti. + +# Classe base +class Umano + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Classe derivata +class Lavoratore < Umano +end + +Umano.foo #=> 0 +Lavoratore.foo #=> 0 + +Umano.foo = 2 #=> 2 +Lavoratore.foo #=> 2 + +# La variabile dell'istanza della classe non è condivisa dai discendenti. + +class Umano + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Dottore < Umano +end + +Umano.bar #=> 0 +Dottore.bar #=> nil + +module EsempioModulo + def foo + 'foo' + end +end + +# Includere moduli vincola i suoi metodi all'istanza della classe. +# Estendere moduli vincola i suoi metodi alla classe stessa. +class Persona + include EsempioModulo +end + +class Libro + extend EsempioModulo +end + +Persona.foo #=> NoMethodError: undefined method `foo' for Person:Class +Persona.new.foo #=> 'foo' +Libro.foo #=> 'foo' +Libro.new.foo #=> NoMethodError: undefined method `foo' + +# Callbacks sono eseguiti quand si include o estende un modulo +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar #=> 'bar' +Something.qux #=> NoMethodError: undefined method `qux' +Something.new.bar #=> NoMethodError: undefined method `bar' +Something.new.qux #=> 'qux' +``` + +## Ulteriori risorse + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Una variante di questa guida con esercizi nel browser. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Imparare Ruby attraverso una serie di tutorial interattivi. +- [Official Documentation](http://ruby-doc.org/core) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una passata [edizione libera](http://ruby-doc.com/docs/ProgrammingRuby/) è disponibile online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Imparare le basi del linguaggio di programmazion Ruby, interattivamente nel browser. -- cgit v1.2.3 From 60377c4ee1c9f8602d6317507a0ef7b05304a0a7 Mon Sep 17 00:00:00 2001 From: bonte <6319051+abonte@users.noreply.github.com> Date: Sun, 14 Oct 2018 11:48:16 +0200 Subject: cut lines over 80 chars --- it-it/ruby-it.html.markdown | 49 +++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown index c082a987..cba636f5 100644 --- a/it-it/ruby-it.html.markdown +++ b/it-it/ruby-it.html.markdown @@ -80,8 +80,8 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true -# Operatori di confronto combinati (ritorna '1' quando il primo argomento è più grande, -# '-1' quando il secondo argomento è più grande, altrimenti '0') +# Operatori di confronto combinati (ritorna '1' quando il primo argomento è più +# grande, '-1' quando il secondo argomento è più grande, altrimenti '0') 1 <=> 10 #=> -1 10 <=> 1 #=> 1 1 <=> 1 #=> 0 @@ -218,7 +218,8 @@ hash['numero'] #=> 5 # Accedere all'hash con una chiave che non esiste ritorna nil: hash['nothing here'] #=> nil -# Quando si usano simboli come chiavi di un hash, si possono utilizzare queste sintassi: +# Quando si usano simboli come chiavi di un hash, si possono utilizzare +# queste sintassi: hash = { :defcon => 3, :action => true } hash.keys #=> [:defcon, :action] @@ -245,8 +246,8 @@ else end #Cicli -# In Ruby, i tradizionali cicli `for` non sono molto comuni. Questi semplici cicli, invece, -# sono implementati con un enumerable, usando `each`: +# In Ruby, i tradizionali cicli `for` non sono molto comuni. Questi semplici +# cicli, invece, sono implementati con un enumerable, usando `each`: (1..5).each do |contatore| puts "iterazione #{contatore}" end @@ -297,8 +298,8 @@ end # Esistono in Ruby ulteriori funzioni per fare i cicli, # come per esempio 'map', 'reduce', 'inject' e altri. -# Nel caso di 'map', esso prende l'array sul quale si sta iterando, -# esegue le istruzioni definite nel blocco, e ritorna un array completamente nuovo. +# Nel caso di 'map', esso prende l'array sul quale si sta iterando, esegue +# le istruzioni definite nel blocco, e ritorna un array completamente nuovo. array = [1,2,3,4,5] doubled = array.map do |elemento| elemento * 2 @@ -396,40 +397,43 @@ surround { puts 'hello world' } # e gli permette di essere passato ad un altro metodo, legato ad uno scope # differente o modificato. Questo è molto comune nella lista parametri del # metodo, dove è frequente vedere il parametro '&block' in coda. Esso accetta -# il blocco, se ne è stato passato uno, e lo converte in un 'Proc'. Qui la denominazione -# è una convenzione; funzionerebbe anche con '&ananas'. +# il blocco, se ne è stato passato uno, e lo converte in un 'Proc'. +# Qui la denominazione è una convenzione; funzionerebbe anche con '&ananas'. def guests(&block) block.class #=> Proc block.call(4) end -# Il metodo 'call' del Proc è simile chiamare 'yield' quando è presente un blocco. +# Il metodo 'call' del Proc è simile allo 'yield' quando è presente un blocco. # Gli argomenti passati a 'call' sono inoltrati al blocco come argomenti: guests { |n| "You have #{n} guests." } # => "You have 4 guests." -# L'operatore splat ("*") consente di convertire una lista di argomenti in un array +# L'operatore splat ("*") converte una lista di argomenti in un array def guests(*array) array.each { |guest| puts guest } end # Destrutturazione -# Ruby destruttura automaticamente gli array in assegnamento a variabili multiple: +# Ruby destruttura automaticamente gli array in assegnamento +# a variabili multiple: a, b, c = [1, 2, 3] a #=> 1 b #=> 2 c #=> 3 -# In alcuni casi si usa l'operatore splat ("*") per destrutturare un array in una lista. +# In alcuni casi si usa l'operatore splat ("*") per destrutturare +# un array in una lista. classifica_concorrenti = ["John", "Sally", "Dingus", "Moe", "Marcy"] def migliore(primo, secondo, terzo) puts "I vincitori sono #{primo}, #{secondo}, e #{terzo}." end -migliore *classifica_concorrenti.first(3) #=> I vincitori sono John, Sally, e Dingus. +migliore *classifica_concorrenti.first(3) +#=> I vincitori sono John, Sally, e Dingus. # The splat operator can also be used in parameters: def migliore(primo, secondo, terzo, *altri) @@ -441,7 +445,8 @@ migliore *classifica_concorrenti #=> I vincitori sono John, Sally, e Dingus. #=> C'erano altri 2 partecipanti. -# Per convenzione, tutti i metodi che ritornano un booleano terminano con un punto interrogativo +# Per convenzione, tutti i metodi che ritornano un booleano terminano +# con un punto interrogativo 5.even? #=> false 5.odd? #=> true @@ -468,7 +473,8 @@ class Umano def initialize(nome, eta = 0) # Assegna il valore dell'argomento alla variabile dell'istanza "nome" @nome = nome - # Se l'età non è fornita, verrà assegnato il valore di default indicato nella lista degli argomenti + # Se l'età non è fornita, verrà assegnato il valore di default indicato + # nella lista degli argomenti @eta = eta end @@ -482,7 +488,8 @@ class Umano @nome end - # Le funzionalità di cui sopra posso essere incapsulate usando il metodo attr_accessor come segue + # Le funzionalità di cui sopra posso essere incapsulate usando + # il metodo attr_accessor come segue attr_accessor :nome # Getter/setter possono anche essere creati individualmente @@ -517,7 +524,8 @@ dwight.nome #=> "Dwight K. Schrute" # Chiamare un metodo della classe Umano.say('Ciao') #=> "Ciao" -# La visibilità della variabile (variable's scope) è determinata dal modo in cui le viene assegnato il nome +# La visibilità della variabile (variable's scope) è determinata dal modo +# in cui le viene assegnato il nome. # Variabili che iniziano con $ hanno uno scope globale $var = "Sono una variabile globale" defined? $var #=> "global-variable" @@ -534,8 +542,9 @@ defined? @@var #=> "class variable" Var = "Sono una costante" defined? Var #=> "constant" -# Anche una classe è un oggetto in ruby. Quindi la classe può avere una variabile dell'istanza. -# Le variabili della classe sono condivise fra la classe e tutti i suoi discendenti. +# Anche una classe è un oggetto in ruby. Quindi la classe può avere +# una variabile dell'istanza. Le variabili della classe sono condivise +# fra la classe e tutti i suoi discendenti. # Classe base class Umano -- cgit v1.2.3 From 61dc8ca784b884e8126b3513091425304a40c8b3 Mon Sep 17 00:00:00 2001 From: bonte <6319051+abonte@users.noreply.github.com> Date: Sun, 14 Oct 2018 12:00:21 +0200 Subject: add translator --- it-it/ruby-it.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown index cba636f5..7b3b5e27 100644 --- a/it-it/ruby-it.html.markdown +++ b/it-it/ruby-it.html.markdown @@ -16,6 +16,8 @@ contributors: - ["Persa Zula", "http://persazula.com"] - ["Jake Faris", "https://github.com/farisj"] - ["Corey Ward", "https://github.com/coreyward"] +translators: + - ["abonte", "https://github.com/abonte"] lang: it-it --- -- cgit v1.2.3 From 7a88501d529096ac2c902b443ba9b17ff660213d Mon Sep 17 00:00:00 2001 From: bonte <6319051+abonte@users.noreply.github.com> Date: Sun, 14 Oct 2018 12:04:44 +0200 Subject: small change --- it-it/ruby-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/ruby-it.html.markdown b/it-it/ruby-it.html.markdown index 7b3b5e27..295bf28a 100644 --- a/it-it/ruby-it.html.markdown +++ b/it-it/ruby-it.html.markdown @@ -17,7 +17,7 @@ contributors: - ["Jake Faris", "https://github.com/farisj"] - ["Corey Ward", "https://github.com/coreyward"] translators: - - ["abonte", "https://github.com/abonte"] + - ["abonte", "https://github.com/abonte"] lang: it-it --- -- cgit v1.2.3 From e0efb66f069b6ac4fe3632d9036d057ab1ff424a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Kuba?= Date: Sun, 14 Oct 2018 23:31:33 +0200 Subject: improve wording, fix typos, add missing text from english original --- cs-cz/javascript.html.markdown | 360 +++++++++++++++++++++++------------------ 1 file changed, 207 insertions(+), 153 deletions(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index cbf7687e..8d4ac278 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -9,32 +9,27 @@ lang: cs-cz filename: javascript-cz.js --- -JavaScript byl vytvořen Brendan Eichem v roce 1995 pro Netscape. Byl původně -zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk Javy, -která byla zamýšlena pro více komplexní webové aplikace, ale jeho úzké propojení -s webovými stránkami a vestavěná podpora v prohlížečích způsobila, že se stala -více běžná ve webovém frontendu než Java. +JavaScript byl vytvořen Brendanem Eichem v roce 1995 pro Netscape. Původně byl +zamýšlen jako jednoduchý skriptovací jazyk pro webové stránky, jako doplněk +Javy, která byla zamýšlena pro komplexnější webové aplikace. Úzké propojení +JavaScriptu s webovými stránkami a vestavěná podpora v prohlížečích způsobila, +že se stal ve webovém frontendu běžnějším než Java. - -JavaScript není omezen pouze na webové prohlížeče, např. projekt Node.js, +JavaScript není omezen pouze na webové prohlížeče. Např. projekt Node.js, který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z -Google Chrome se stává více a více oblíbený pro serverovou část webových aplikací. - -Zpětná vazba je velmi ceněná. Autora článku můžete kontaktovat (anglicky) na -[@adambrenecki](https://twitter.com/adambrenecki), nebo -[adam@brenecki.id.au](mailto:adam@brenecki.id.au), nebo mě, jakožto překladatele, -na [martinek@ludis.me](mailto:martinek@ludis.me). +Google Chrome se stává stále oblíbenější i pro serverovou část webových +aplikací. ```js -// Komentáře jsou jako v zayku C. Jednořádkové komentáře začínájí dvojitým lomítkem, +// Jednořádkové komentáře začínájí dvojitým lomítkem, /* a víceřádkové komentáře začínají lomítkem s hvězdičkou a končí hvězdičkou s lomítkem */ -// Vyrazu můžou být spuštěny pomocí ; +// Příkazy mohou být ukončeny středníkem ; delejNeco(); -// ... ale nemusí, středníky jsou automaticky vloženy kdekoliv, -// kde končí řádka, kromě pár speciálních případů +// ... ale nemusí, protože středníky jsou automaticky vloženy kdekoliv, +// kde končí řádka, kromě pár speciálních případů. delejNeco() // Protože tyto případy můžou způsobit neočekávané výsledky, budeme @@ -44,12 +39,12 @@ delejNeco() // 1. Čísla, řetězce a operátory // JavaScript má jeden číselný typ (čímž je 64-bitový IEEE 754 double). -// Double má 52-bit přesnost, což je dostatečně přesné pro ukládání celých čísel -// do 9✕10¹⁵. +// Double má 52-bitovou přesnost, což je dostatečně přesné pro ukládání celých +// čísel až do 9✕10¹⁵. 3; // = 3 1.5; // = 1.5 -// Základní matematické operace fungují, jak byste očekávali +// Základní matematické operace fungují tak, jak byste očekávali 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 @@ -65,30 +60,30 @@ delejNeco() 18.5 % 7; // = 4.5 // Bitové operace také fungují; když provádíte bitové operace, desetinné číslo -// (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů +// (float) se převede na celé číslo (int) se znaménkem *až do* 32 bitů 1 << 2; // = 4 // Přednost se vynucuje závorkami. (1 + 3) * 2; // = 8 -// Existují 3 hodnoty mimo obor reálných čísel +// Existují 3 hodnoty mimo obor reálných čísel: Infinity; // + nekonečno; výsledek např. 1/0 -Infinity; // - nekonečno; výsledek např. -1/0 NaN; // výsledek např. 0/0, znamená, že výsledek není číslo ('Not a Number') -// Také existují hodnoty typu bool +// Také existují hodnoty typu boolean. true; // pravda false; // nepravda -// Řetězce znaků jsou obaleny ' nebo ". +// Řetězce znaků jsou obaleny ' nebo ". 'abc'; -"Ahoj světe!"; +"Hello, world"; -// Negace se tvoří pomocí ! +// Negace se tvoří pomocí znaku ! !true; // = false !false; // = true -// Rovnost se porovnává === +// Rovnost se porovnává pomocí === 1 === 1; // = true 2 === 1; // = false @@ -103,16 +98,16 @@ false; // nepravda 2 >= 2; // = true // Řetězce znaků se spojují pomocí + -"Ahoj " + "světe!"; // = "Ahoj světe!" +"Hello " + "world!"; // = "Hello world!" -// ... což funguje nejenom s řetězci +// ... což funguje nejen s řetězci "1, 2, " + 3; // = "1, 2, 3" -"Ahoj " + ["světe", "!"] // = "Ahoj světe,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // a porovnávají se pomocí < nebo > "a" < "b"; // = true -// Rovnost s převodem typů se dělá pomocí == ... +// Rovnost s převodem typů se dělá za pomoci dvojitého rovnítka... "5" == 5; // = true null == undefined; // = true @@ -124,24 +119,24 @@ null === undefined; // = false 13 + !0; // 14 "13" + !0; // '13true' -// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí charAt` +// Můžeme přistupovat k jednotlivým znakům v řetězci pomocí `charAt` "Toto je řetězec".charAt(0); // = 'T' -// ...nebo použít `substring` k získání podřetězce -"Ahoj světe".substring(0, 4); // = "Ahoj" +// ...nebo použít `substring` k získání podřetězce. +"Hello world".substring(0, 5); // = "Hello" -// `length` znamená délka a je to vlastnost, takže nepoužívejte () -"Ahoj".length; // = 4 +// `length` znamená délka a je to vlastnost, takže nepoužívejte (). +"Hello".length; // = 5 // Existují také typy `null` a `undefined`. -null; // značí, že žádnou hodnotu -undefined; // značí, že hodnota nebyla definovaná (ikdyž +null; // obvykle označuje něco záměrně bez hodnoty +undefined; // obvykle označuje, že hodnota není momentálně definovaná (ačkoli // `undefined` je hodnota sama o sobě) // false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní -// vrací pravdu (true).. -// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, ikdyž 0 == "0" -// vrací pravdu +// vrací pravdu (true). +// Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, i když 0 == "0" +// vrací pravdu. /////////////////////////////////// // 2. Proměnné, pole a objekty @@ -151,11 +146,11 @@ undefined; // značí, že hodnota nebyla definovaná (ikdyž // znak `=`. var promenna = 5; -// když vynecháte slůvko 'var' nedostanete chybovou hlášku... +// Když vynecháte slůvko 'var', nedostanete chybovou hlášku... jinaPromenna = 10; -// ...ale vaše proměnná bude vytvořena globálně, bude vytvořena v globálním -// oblasti působnosti, ne jenom v lokálním tam, kde jste ji vytvořili +// ...ale vaše proměnná bude vytvořena globálně. Bude vytvořena v globální +// oblasti působnosti, tedy nejenom v lokální tam, kde jste ji vytvořili. // Proměnné vytvořené bez přiřazení obsahují hodnotu undefined. var dalsiPromenna; // = undefined @@ -163,56 +158,72 @@ var dalsiPromenna; // = undefined // Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou var someFourthVar = 2, someFifthVar = 4; -// Existuje kratší forma pro matematické operace na proměnné +// Existuje kratší forma pro matematické operace nad proměnnými promenna += 5; // se provede stejně jako promenna = promenna + 5; -// promenna je ted 10 +// promenna je teď 10 promenna *= 10; // teď je promenna rovna 100 // a tohle je způsob, jak přičítat a odečítat 1 promenna++; // teď je promenna 101 promenna--; // zpět na 100 -// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu -var mojePole = ["Ahoj", 45, true]; +// Pole jsou uspořádané seznamy hodnot jakéhokoliv typu. +var myArray = ["Ahoj", 45, true]; // Jednotlivé hodnoty jsou přístupné přes hranaté závorky. // Členové pole se začínají počítat na nule. myArray[1]; // = 45 -// Pole je proměnlivé délky a členové se můžou měnit -myArray.push("Světe"); +// Pole je proměnlivé délky a členové se můžou měnit. +myArray.push("World"); myArray.length; // = 4 // Přidání/změna na specifickém indexu myArray[3] = "Hello"; -// JavaScriptové objekty jsou stejné jako asociativní pole v jinných programovacích +// Přidání nebo odebrání člena ze začátku nebo konce pole +myArray.unshift(3); // Přidej jako první člen +someVar = myArray.shift(); // Odstraň prvního člena a vrať jeho hodnotu +myArray.push(3); // Přidej jako poslední člen +someVar = myArray.pop(); // Odstraň posledního člena a vrať jeho hodnotu + +// Spoj všechny členy pole středníkem +var myArray0 = [32,false,"js",12,56,90]; +myArray0.join(";") // = "32;false;js;12;56;90" + +// Vrať část pole s elementy od pozice 1 (včetně) do pozice 4 (nepočítaje) +myArray0.slice(1,4); // = [false,"js",12] + +// Odstraň čtyři členy od pozice 2, vlož následující +// "hi","wr" and "ld"; vrať odstraněné členy +myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// myArray0 === [32,false,"hi","wr","ld"] + +// JavaScriptové objekty jsou stejné jako asociativní pole v jiných programovacích // jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota. -var mujObjekt = {klic1: "Ahoj", klic2: "světe"}; +var mujObjekt = {klic1: "Hello", klic2: "World"}; -// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní -// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu- +// Klíče jsou řetězce, ale nemusí mít povinné uvozovky, pokud jsou validními +// JavaScriptovými identifikátory. Hodnoty můžou být jakéhokoliv typu. var mujObjekt = {klic: "mojeHodnota", "muj jiny klic": 4}; // K hodnotám můžeme přistupovat opět pomocí hranatých závorek -myObj["muj jiny klic"]; // = 4 +mujObjekt["muj jiny klic"]; // = 4 // ... nebo pokud je klíč platným identifikátorem, můžeme přistupovat k // hodnotám i přes tečku mujObjekt.klic; // = "mojeHodnota" // Objekty jsou měnitelné, můžeme upravit hodnoty, nebo přidat nové klíče. -myObj.mujDalsiKlic = true; +mujObjekt.mujDalsiKlic = true; -// Pokud se snažíte přistoupit ke klíči, který není nastaven, dostanete undefined -myObj.dalsiKlic; // = undefined +// Pokud se snažíte přistoupit ke klíči, který neexistuje, dostanete undefined. +mujObjekt.dalsiKlic; // = undefined /////////////////////////////////// // 3. Řízení toku programu -// Syntaxe pro tuto sekci je prakticky stejná jako pro Javu - -// `if` (když) funguje, jak byste čekali. +// Funkce `if` funguje, jak byste čekali. var pocet = 1; if (pocet == 3){ // provede, když se pocet rovná 3 @@ -222,42 +233,49 @@ if (pocet == 3){ // provede, když je pocet cokoliv jinného } -// Stejně tak cyklus while +// Stejně tak cyklus `while`. while (true){ - // nekonečný cyklus + // nekonečný cyklus! } -// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou +// Do-while cyklus je stejný jako while, akorát se vždy provede aspoň jednou. var vstup; do { vstup = nactiVstup(); } while (!jeValidni(vstup)) -// Cyklus for je stejný jako v Javě nebo jazyku C +// Cyklus `for` je stejný jako v Javě nebo jazyku C: // inicializace; podmínka pro pokračování; iterace. -for (var i = 0; i < 3; i++){ - // provede třikrát +for (var i = 0; i < 5; i++){ + // provede se pětkrát } -// Cyklus For-in iteruje přes každo vlastnost prototypu -var popis = ""; -var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; -for (var x in osoba){ - popis += osoba[x] + " "; +// Opuštění cyklu s návěštím je podobné jako v Javě +outer: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // opustí vnější (outer) cyklus místo pouze vnitřního (inner) cyklu + } + } } -//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou -//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty() +// Cyklus For-in iteruje přes každou vlastnost prototypu var popis = ""; -var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18}; +var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18}; for (var x in osoba){ - if (osoba.hasOwnProperty(x)){ - popis += osoba[x] + " "; - } -} + popis += osoba[x] + " "; +} // popis = 'Paul Ken 18 ' -// for-in by neměl být použit pro pole, pokud záleží na pořadí indexů. -// Neexistuje jistota, že for-in je vrátí ve správném pořadí. +// Příkaz for/of umožňuje iterovat iterovatelné objekty (včetně vestavěných typů +// String, Array, například polím podobným argumentům nebo NodeList objektům, +// TypeArray, Map a Set, či uživatelsky definované iterovatelné objekty). +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' // && je logické a, || je logické nebo if (dum.velikost == "velký" && dum.barva == "modrá"){ @@ -270,7 +288,6 @@ if (barva == "červená" || barva == "modrá"){ // && a || jsou praktické i pro nastavení základních hodnot var jmeno = nejakeJmeno || "default"; - // `switch` zkoumá přesnou rovnost (===) // Používejte 'break;' po každé možnosti, jinak se provede i možnost za ní. znamka = 'B'; @@ -289,8 +306,9 @@ switch (znamka) { break; } + //////////////////////////////////////////////////////// -// 4. Funckce, Oblast platnosti (scope) a Vnitřní funkce +// 4. Funkce, Oblast platnosti (scope) a Vnitřní funkce // JavaScriptové funkce jsou definovány slůvkem `function`. function funkce(text){ @@ -302,12 +320,9 @@ funkce("něco"); // = "NĚCO" // jako slůvko return, jinak se vrátí 'undefined', kvůli automatickému vkládání // středníků. Platí to zejména pro Allmanův styl zápisu. -function funkce() -{ +function funkce(){ return // <- zde je automaticky vložen středník - { - tohleJe: "vlastnost objektu" - } + { tohleJe: "vlastnost objektu"}; } funkce(); // = undefined @@ -327,9 +342,9 @@ function myFunction(){ setInterval(myFunction, 5000); // Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako -// ananymní funkci přímo vloženou jako argument +// anonymní funkci přímo vloženou jako argument setTimeout(function(){ - // tento kód bude zavolán za 5 vteřin + // tento kód bude zavolán za 5 vteřin }, 5000); // JavaScript má oblast platnosti funkce, funkce ho mají, ale jiné bloky ne @@ -339,21 +354,21 @@ if (true){ i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj // rámec působnosti -// Toto je běžný model,který chrání před únikem dočasných proměnných do +// Toto je běžný model, který chrání před únikem dočasných proměnných do //globální oblasti (function(){ var docasna = 5; - // Můžeme přistupovat k globálního oblasti přes přiřazování globalním + // Můžeme přistupovat ke globálního oblasti přes přiřazování globalním // objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt - // může mít v jiných prostředích jako Node.js jinné jméno. + // může mít v jiných prostředích jako Node.js jiné jméno. window.trvala = 10; })(); docasna; // způsobí ReferenceError trvala; // = 10 -// Jedna z nejvice mocných vlastnosti JavaScriptu je vnitřní funkce. Je to funkce -// definovaná v jinné funkci, vnitřní funkce má přístup ke všem proměnným ve -// vnější funkci, dokonce i poté, co funkce skončí +// Jedna z nejmocnějších vlastností JavaScriptu je vnitřní funkce. Je to funkce +// definovaná v jiné funkci. Vnitřní funkce má přístup ke všem proměnným ve +// vnější funkci, dokonce i poté, co vnější funkce skončí. function ahojPoPetiVterinach(jmeno){ var prompt = "Ahoj, " + jmeno + "!"; // Vnitřní funkce je dána do lokální oblasti platnosti, jako kdyby byla @@ -362,9 +377,9 @@ function ahojPoPetiVterinach(jmeno){ alert(prompt); } setTimeout(vnitrni, 5000); - // setTimeout je asynchronní, takže funkce ahojPoPetiVterinach se ukončí - // okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak protože - // vnitrni je definována přes ahojPoPetiVterinach, má pořád přístup k + // setTimeout je asynchronní, takže se funkce ahojPoPetiVterinach ukončí + // okamžitě, ale setTimeout zavolá funkci vnitrni až poté. Avšak + // vnitrni je definována přes ahojPoPetiVterinach a má pořád přístup k // proměnné prompt, když je konečně zavolána. } ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s @@ -372,23 +387,23 @@ ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s /////////////////////////////////////////////////// // 5. Více o objektech, konstuktorech a prototypech -// Objekty můžou obsahovat funkce +// Objekty můžou obsahovat funkce. var mujObjekt = { mojeFunkce: function(){ - return "Ahoj světe!"; + return "Hello world!"; } }; -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Když jsou funkce z objektu zavolány, můžou přistupovat k objektu přes slůvko // 'this'' var mujObjekt = { - text: "Ahoj světe!", + text: "Hello world!", mojeFunkce: function(){ return this.text; } }; -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Slůvko this je nastaveno k tomu, kde je voláno, ne k tomu, kde je definováno // Takže naše funkce nebude fungovat, když nebude v kontextu objektu. @@ -396,23 +411,23 @@ var mojeFunkce = mujObjekt.mojeFunkce; mojeFunkce(); // = undefined // Opačně, funkce může být přiřazena objektu a může přistupovat k objektu přes -// this, i když nebyla přímo v definici- +// this, i když nebyla přímo v definici. var mojeDalsiFunkce = function(){ return this.text.toUpperCase(); } mujObjekt.mojeDalsiFunkce = mojeDalsiFunkce; -mujObjekt.mojeDalsiFunkce(); // = "AHOJ SVĚTE!" +mujObjekt.mojeDalsiFunkce(); // = "HELLO WORLD!" // Můžeme také specifikovat, v jakém kontextu má být funkce volána pomocí // `call` nebo `apply`. var dalsiFunkce = function(s){ return this.text + s; -} -dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Ahoj světe! A ahoj měsíci!" +}; +dalsiFunkce.call(mujObjekt, " A ahoj měsíci!"); // = "Hello world! A ahoj měsíci!" -// Funkce `apply`je velmi podobná, akorát bere jako druhý argument pole argumentů -dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Ahoj světe! A ahoj slunce!" +// Funkce `apply`je velmi podobná, pouze bere jako druhý argument pole argumentů +dalsiFunkce.apply(mujObjekt, [" A ahoj slunce!"]); // = "Hello world! A ahoj slunce!" // To je praktické, když pracujete s funkcí, která bere sekvenci argumentů a // chcete předat pole. @@ -425,38 +440,42 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 // použijte `bind`. var pripojenaFunkce = dalsiFunkce.bind(mujObjekt); -pripojenaFunkce(" A ahoj Saturne!"); // = "Ahoj světe! A ahoj Saturne!" +pripojenaFunkce(" A ahoj Saturne!"); // = "Hello world! A ahoj Saturne!" -// `bind` může být použito čatečně částečně i k používání +// `bind` může být použito částečně k přepoužití funkce -var nasobeni = function(a, b){ return a * b; } +var nasobeni = function(a, b){ return a * b; }; var zdvojeni = nasobeni.bind(this, 2); zdvojeni(8); // = 16 // Když zavoláte funkci se slůvkem 'new', vytvoří se nový objekt a // a udělá se dostupný funkcím skrz slůvko 'this'. Funkcím volaným takto se říká -// konstruktory +// konstruktory. var MujKonstruktor = function(){ this.mojeCislo = 5; -} +}; mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5} mujObjekt.mojeCislo; // = 5 -// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlasnosti -// objektu, který neexistuje na objektu, tak se JS koukne do prototypu. +// Narozdíl od nejznámějších objektově orientovaných jazyků, JavaScript nezná +// koncept instancí vyvořených z tříd. Místo toho Javascript kombinuje +// instanciování a dědění do konceptu zvaného 'prototyp'. + +// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlastnosti +// objektu, který neexistuje na objektu, tak se JS podívá do prototypu. // Některé JS implementace vám umožní přistupovat k prototypu přes magickou // vlastnost '__proto__'. I když je toto užitečné k vysvětlování prototypů, není -// to součást standardu, ke standartní způsobu k používání prototypu se dostaneme -// později. +// to součást standardu. Ke standardnímu způsobu používání prototypu se +// dostaneme později. var mujObjekt = { mujText: "Ahoj svete!" }; var mujPrototyp = { smyslZivota: 42, mojeFunkce: function(){ - return this.mujText.toLowerCase() + return this.mujText.toLowerCase(); } }; @@ -464,7 +483,7 @@ mujObjekt.__proto__ = mujPrototyp; mujObjekt.smyslZivota; // = 42 // Toto funguje i pro funkce -mujObjekt.mojeFunkce(); // = "Ahoj světe!" +mujObjekt.mojeFunkce(); // = "Hello world!" // Samozřejmě, pokud není vlastnost na vašem prototypu, tak se hledá na // prototypu od prototypu atd. @@ -474,21 +493,41 @@ mujPrototyp.__proto__ = { mujObjekt.mujBoolean; // = true -// Zde neni žádné kopírování; každý objekt ukládá referenci na svůj prototyp -// Toto znamená, že můžeme měnit prototyp a změny se projeví všude +// Zde není žádné kopírování; každý objekt ukládá referenci na svůj prototyp +// Toto znamená, že můžeme měnit prototyp a změny se projeví všude. mujPrototyp.smyslZivota = 43; -mujObjekt.smyslZivota // = 43 +mujObjekt.smyslZivota; // = 43 + +// Příkaz for/in umožňuje iterovat vlastnosti objetku až do úrovně null +// prototypu. +for (var x in myObj){ + console.log(myObj[x]); +} +///Vypíše: +// Hello world! +// 43 +// [Function: myFunc] + +// Pro výpis pouze vlastností patřících danému objektu a nikoli jeho prototypu, +// použijte kontrolu pomocí `hasOwnProperty()`. +for (var x in myObj){ + if (myObj.hasOwnProperty(x)){ + console.log(myObj[x]); + } +} +///Vypíše: +// Hello world! // Zmínili jsme již předtím, že '__proto__' není ve standardu a není cesta, jak // měnit prototyp existujícího objektu. Avšak existují možnosti, jak vytvořit -// nový objekt s daným prototypem +// nový objekt s daným prototypem. // První je Object.create, což je nedávný přídavek do JS a není dostupný zatím // ve všech implementacích. var mujObjekt = Object.create(mujPrototyp); -mujObjekt.smyslZivota // = 43 +mujObjekt.smyslZivota; // = 43 -// Druhý způsob, který funguje všude je pomocí konstuktoru. Konstruktor má +// Druhý způsob, který funguje všude, je pomocí konstuktoru. Konstruktor má // vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale // prototyp nového objektu. MujKonstruktor.prototype = { @@ -499,10 +538,10 @@ MujKonstruktor.prototype = { }; var mujObjekt2 = new MujKonstruktor(); mujObjekt2.ziskejMojeCislo(); // = 5 -mujObjekt2.mojeCislo = 6 +mujObjekt2.mojeCislo = 6; mujObjekt2.ziskejMojeCislo(); // = 6 -// Vestavěnné typy jako čísla nebo řetězce mají také konstruktory, které vytváří +// Vestavěné typy jako čísla nebo řetězce mají také konstruktory, které vytváří // ekvivalentní obalovací objekty (wrappery). var mojeCislo = 12; var mojeCisloObj = new Number(12); @@ -530,45 +569,60 @@ String.prototype.prvniZnak = function(){ // Tento fakt je často používán v polyfillech, což je implementace novějších // vlastností JavaScriptu do starších variant, takže je můžete používat třeba -// ve starých prohlížečích +// ve starých prohlížečích. -// Pro příkklad, zmínili jsme, že Object.create není dostupný ve všech -// implementacích, můžeme si avšak přidat pomocí polyfillu +// Na příklad jsme zmínili, že Object.create není dostupný ve všech +// implementacích, ale můžeme si ho přidat pomocí polyfillu: if (Object.create === undefined){ // nebudeme ho přepisovat, když existuje Object.create = function(proto){ // vytvoříme dočasný konstruktor var Constructor = function(){}; Constructor.prototype = proto; - // ten použijeme k vytvoření nového s prototypem + // ten použijeme k vytvoření nového objektu s prototypem return new Constructor(); - } + }; } ``` ## Kam dál -[Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) obsahuje -perfektní dokumentaci pro JavaScript, který je používaný v prohlížečích. Navíc -je to i wiki, takže jakmile se naučíte více, můžete pomoci ostatním, tím, že -přispějete svými znalostmi. +[Mozilla Developer Network][1] obsahuje perfektní dokumentaci pro JavaScript, +který je používaný v prohlížečích. Navíc je to i wiki, takže jakmile se naučíte +více, můžete pomoci ostatním tím, že přispějete svými znalostmi. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +MDN's [A re-introduction to JavaScript][2] pojednává o konceptech vysvětlených zde v mnohem větší hloubce. Tento návod -pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit více, jak se používá -na webových stránkách, začněte tím, že se kouknete na [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +pokrývá hlavně JavaScript sám o sobě. Pokud se chcete naučit, jak se používá +na webových stránkách, začněte tím, že se podíváte na [DOM][3] + +[Learn Javascript by Example and with Challenges][4] +je varianta tohoto návodu i s úkoly. + +[JavaScript Garden][5] je sbírka příkladů těch nejnepředvídatelnějších částí +tohoto jazyka. + +[JavaScript: The Definitive Guide][6] je klasická výuková kniha. + +[Eloquent Javascript][8] od Marijn Haverbeke je výbornou JS knihou/e-knihou. -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto -návodu i s úkoly- +[Javascript: The Right Way][10] je průvodcem Javascriptem pro začínající +vývojáře i pomocníkem pro zkušené vývojáře, kteří si chtějí prohloubit své +znalosti. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) je sbírka -příkladů těch nejvíce nepředvídatelných částí tohoto jazyka. +[Javascript:Info][11] je moderním Javascriptovým průvodcem, který pokrývá +základní i pokročilé témata velice výstižným výkladem. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) -je klasická výuková kniha. +Jako dodatek k přímým autorům tohoto článku byly na těchto stránkách části +obsahu převzaty z Pythoního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7] +na stránkách Mozilla Developer Network. -Jako dodatek k přímým autorům tohoto článku, některý obsah byl přizpůsoben z -Pythoního tutoriálu od Louie Dinh na této stráce, a z [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -z Mozilla Developer Network. +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[10]: http://jstherightway.org/ +[11]: https://javascript.info/ -- cgit v1.2.3 From 8d463993ebe459a0ef8d1ade1814ba34abc34a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Kuba?= Date: Mon, 15 Oct 2018 10:42:55 +0200 Subject: fix spell check errors --- cs-cz/javascript.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index 8d4ac278..c2723725 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -16,12 +16,12 @@ JavaScriptu s webovými stránkami a vestavěná podpora v prohlížečích způ že se stal ve webovém frontendu běžnějším než Java. JavaScript není omezen pouze na webové prohlížeče. Např. projekt Node.js, -který zprostředkovává samostatně běžící prostředí V8 JavaScriptového enginu z -Google Chrome se stává stále oblíbenější i pro serverovou část webových +který zprostředkovává samostatně běžící prostředí V8 JavaScriptového jádra z +Google Chrome se stává stále oblíbenější i pro serverovou část webových aplikací. ```js -// Jednořádkové komentáře začínájí dvojitým lomítkem, +// Jednořádkové komentáře začínají dvojitým lomítkem, /* a víceřádkové komentáře začínají lomítkem s hvězdičkou a končí hvězdičkou s lomítkem */ @@ -30,7 +30,7 @@ delejNeco(); // ... ale nemusí, protože středníky jsou automaticky vloženy kdekoliv, // kde končí řádka, kromě pár speciálních případů. -delejNeco() +delejNeco(); // Protože tyto případy můžou způsobit neočekávané výsledky, budeme // středníky v našem návodu používat. @@ -230,7 +230,7 @@ if (pocet == 3){ } else if (pocet == 4){ // provede, když se pocet rovná 4 } else { - // provede, když je pocet cokoliv jinného + // provede, když je pocet cokoliv jiného } // Stejně tak cyklus `while`. @@ -282,7 +282,7 @@ if (dum.velikost == "velký" && dum.barva == "modrá"){ dum.obsahuje = "medvěd"; } if (barva == "červená" || barva == "modrá"){ - // barva je červená nebo modtrá + // barva je červená nebo modrá } // && a || jsou praktické i pro nastavení základních hodnot @@ -358,7 +358,7 @@ i; // = 5 - ne undefined, jak byste očekávali v jazyku, kde mají bloky svůj //globální oblasti (function(){ var docasna = 5; - // Můžeme přistupovat ke globálního oblasti přes přiřazování globalním + // Můžeme přistupovat ke globálního oblasti přes přiřazování globálním // objektům. Ve webovém prohlížeči je to vždy 'window`. Globální objekt // může mít v jiných prostředích jako Node.js jiné jméno. window.trvala = 10; @@ -382,10 +382,10 @@ function ahojPoPetiVterinach(jmeno){ // vnitrni je definována přes ahojPoPetiVterinach a má pořád přístup k // proměnné prompt, když je konečně zavolána. } -ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s +ahojPoPetiVterinach("Adam"); // otevře pop-up s textem "Ahoj, Adam!" za 5s /////////////////////////////////////////////////// -// 5. Více o objektech, konstuktorech a prototypech +// 5. Více o objektech, konstruktorech a prototypech // Objekty můžou obsahovat funkce. var mujObjekt = { -- cgit v1.2.3 From 5022b4544b0857bc11f40c26ca5fef651f88bb76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Kuba?= Date: Mon, 15 Oct 2018 11:01:42 +0200 Subject: fix spell typos and improve some more sentences --- cs-cz/javascript.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index c2723725..c05a9138 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -133,7 +133,7 @@ null; // obvykle označuje něco záměrně bez hodnoty undefined; // obvykle označuje, že hodnota není momentálně definovaná (ačkoli // `undefined` je hodnota sama o sobě) -// false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní +// false, null, undefined, NaN, 0 a "" vrací nepravdu (false). Všechno ostatní // vrací pravdu (true). // Všimněte si, že 0 vrací nepravdu, ale "0" vrací pravdu, i když 0 == "0" // vrací pravdu. @@ -382,7 +382,7 @@ function ahojPoPetiVterinach(jmeno){ // vnitrni je definována přes ahojPoPetiVterinach a má pořád přístup k // proměnné prompt, když je konečně zavolána. } -ahojPoPetiVterinach("Adam"); // otevře pop-up s textem "Ahoj, Adam!" za 5s +ahojPoPetiVterinach("Adam"); // otevře popup s "Ahoj, Adam!" za 5s /////////////////////////////////////////////////// // 5. Více o objektech, konstruktorech a prototypech @@ -442,7 +442,7 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 var pripojenaFunkce = dalsiFunkce.bind(mujObjekt); pripojenaFunkce(" A ahoj Saturne!"); // = "Hello world! A ahoj Saturne!" -// `bind` může být použito částečně k přepoužití funkce +// `bind` může být použito částečně k provázání funkcí var nasobeni = function(a, b){ return a * b; }; var zdvojeni = nasobeni.bind(this, 2); @@ -458,11 +458,11 @@ var MujKonstruktor = function(){ mujObjekt = new MujKonstruktor(); // = {mojeCislo: 5} mujObjekt.mojeCislo; // = 5 -// Narozdíl od nejznámějších objektově orientovaných jazyků, JavaScript nezná -// koncept instancí vyvořených z tříd. Místo toho Javascript kombinuje -// instanciování a dědění do konceptu zvaného 'prototyp'. +// Na rozdíl od nejznámějších objektově orientovaných jazyků, JavaScript nezná +// koncept instancí vytvořených z tříd. Místo toho Javascript kombinuje +// vytváření instancí a dědění do konceptu zvaného 'prototyp'. -// Každý JsavaScriptový objekt má prototyp. Když budete přistupovat k vlastnosti +// Každý JavaScriptový objekt má prototyp. Když budete přistupovat k vlastnosti // objektu, který neexistuje na objektu, tak se JS podívá do prototypu. // Některé JS implementace vám umožní přistupovat k prototypu přes magickou @@ -470,7 +470,7 @@ mujObjekt.mojeCislo; // = 5 // to součást standardu. Ke standardnímu způsobu používání prototypu se // dostaneme později. var mujObjekt = { - mujText: "Ahoj svete!" + mujText: "Hello world!" }; var mujPrototyp = { smyslZivota: 42, @@ -498,7 +498,7 @@ mujObjekt.mujBoolean; // = true mujPrototyp.smyslZivota = 43; mujObjekt.smyslZivota; // = 43 -// Příkaz for/in umožňuje iterovat vlastnosti objetku až do úrovně null +// Příkaz for/in umožňuje iterovat vlastnosti objektu až do úrovně null // prototypu. for (var x in myObj){ console.log(myObj[x]); @@ -527,7 +527,7 @@ for (var x in myObj){ var mujObjekt = Object.create(mujPrototyp); mujObjekt.smyslZivota; // = 43 -// Druhý způsob, který funguje všude, je pomocí konstuktoru. Konstruktor má +// Druhý způsob, který funguje všude, je pomocí konstruktoru. Konstruktor má // vlastnost jménem prototype. Toto *není* prototyp samotného konstruktoru, ale // prototyp nového objektu. MujKonstruktor.prototype = { @@ -560,7 +560,7 @@ if (new Number(0)){ // a objekty jsou vždy pravdivé } -// Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže +// Avšak, obalovací objekty a normální vestavěné typy sdílejí prototyp, takže // můžete přidat funkcionalitu k řetězci String.prototype.prvniZnak = function(){ return this.charAt(0); @@ -605,15 +605,15 @@ tohoto jazyka. [Eloquent Javascript][8] od Marijn Haverbeke je výbornou JS knihou/e-knihou. -[Javascript: The Right Way][10] je průvodcem Javascriptem pro začínající +[Javascript: The Right Way][10] je průvodcem JavaScriptem pro začínající vývojáře i pomocníkem pro zkušené vývojáře, kteří si chtějí prohloubit své znalosti. -[Javascript:Info][11] je moderním Javascriptovým průvodcem, který pokrývá +[Javascript:Info][11] je moderním JavaScriptovým průvodcem, který pokrývá základní i pokročilé témata velice výstižným výkladem. Jako dodatek k přímým autorům tohoto článku byly na těchto stránkách části -obsahu převzaty z Pythoního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7] +obsahu převzaty z Pythonního tutoriálu Louiho Dinha, a tak0 z [JS Tutorial][7] na stránkách Mozilla Developer Network. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript -- cgit v1.2.3 From cb12952d60909b0f68416190d3cc8e69b81085c8 Mon Sep 17 00:00:00 2001 From: Timothy Ubbens Date: Mon, 15 Oct 2018 23:22:14 -0400 Subject: Add hre.csv to this repo directly --- hre.csv | 1 + pythonstatcomp.html.markdown | 35 ++++++++++++++--------------------- 2 files changed, 15 insertions(+), 21 deletions(-) create mode 100644 hre.csv diff --git a/hre.csv b/hre.csv new file mode 100644 index 00000000..eab43cc4 --- /dev/null +++ b/hre.csv @@ -0,0 +1 @@ +Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814 N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840 N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855 N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875 N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877 N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887 N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894 N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898 N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899 N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905 N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924 1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973 2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983 3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002 4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024 5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039 6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056 7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105 8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125 9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137 10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190 11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197 12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215 13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250 14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313 15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347 16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378 17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437 18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493 19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519 20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556 21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564 22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576 23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612 24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619 25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637 26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657 27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705 28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711 29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740 30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745 31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765 32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790 33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792 34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806 \ No newline at end of file diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 2440d859..5444769a 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -146,7 +146,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") """ # load some data on Holy Roman Emperors -url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +url = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/hre.csv" r = requests.get(url) fp = "hre.csv" with open(fp, "wb") as f: @@ -156,26 +156,19 @@ hre = pd.read_csv(fp) hre.head() """ - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN + Ix Dynasty Name Birth Death +0 NaN Carolingian Charles I 2 April 742 28 January 814 +1 NaN Carolingian Louis I 778 20 June 840 +2 NaN Carolingian Lothair I 795 29 September 855 +3 NaN Carolingian Louis II 825 12 August 875 +4 NaN Carolingian Charles II 13 June 823 6 October 877 + + Coronation 1 Coronation 2 Ceased to be Emperor +0 25 December 800 NaN 28 January 814 +1 11 September 813 5 October 816 20 June 840 +2 5 April 823 NaN 29 September 855 +3 Easter 850 18 May 872 12 August 875 +4 29 December 875 NaN 6 October 877 """ # clean the Birth and Death columns -- cgit v1.2.3 From a5b7fe9e618c52399cf7bea539cafde7515a7b55 Mon Sep 17 00:00:00 2001 From: Timothy Ubbens Date: Mon, 15 Oct 2018 23:22:34 -0400 Subject: Add import to resolve changes in new versions of python --- pythonstatcomp.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 5444769a..4cff3535 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -186,6 +186,8 @@ rx = re.compile(r'\d+$') # match trailing digits - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html """ +from functools import reduce + def extractYear(v): return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int)) -- cgit v1.2.3 From bb7e218b828b0ebf980f0c1c4a293c423bbdd4b4 Mon Sep 17 00:00:00 2001 From: Philipp Fischbeck Date: Tue, 16 Oct 2018 16:58:55 +0200 Subject: Update ruby.html.markdown Fix typo ("Tt"-->"It") --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 2635309b..2595d1d5 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -377,7 +377,7 @@ sum sum(3, 4), 5 #=> 12 # yield # All methods have an implicit, optional block parameter. -# Tt can be called with the 'yield' keyword. +# It can be called with the 'yield' keyword. def surround puts '{' yield -- cgit v1.2.3 From 8b6e7fb9e3883686ed0cdf959ede065c72645f60 Mon Sep 17 00:00:00 2001 From: Vincent Chafouin Date: Tue, 16 Oct 2018 20:45:28 +0300 Subject: Update markdown-fr-html.mardown * Fix issue #2864 * Fix formatting * Fix ruby code snippet * Fix translation * Add missing keyboard keys section --- fr-fr/markdown-fr.html.markdown | 294 +++++++++++++++++++++++++--------------- 1 file changed, 188 insertions(+), 106 deletions(-) diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 8518f35c..2955fd14 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -6,52 +6,69 @@ filename: markdown-fr.md lang: fr-fr --- + Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML - (et beaucoup d'autres formats aussi à présent). +facile à lire et à écrire, aisément convertible en HTML (et dans beaucoup +d'autres formats aussi). + +Les implémentations du Markdown varient d'un analyseur syntaxique à un autre. +Ce guide va essayer de clarifier quand une fonctionnalité est universelle ou +quand elle est specifique à un certain analyseur syntaxique. + +- [Balises HTML](#balises-html) +- [En-têtes](#en-tetes) +- [Styles de texte basiques](#style-de-text-basiques) +- [Paragraphes](#paragraphes) +- [Listes](#listes) +- [Blocs de code](#blocs-de-code) +- [Séparateur horizontal](#separateur-horizontal) +- [Liens hypertextes](#liens-hypertextes) +- [Images](#images) +- [Divers](#divers) -Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" -et envoyer des pull request! +## Balises HTML +Markdown est un sur-ensemble du HTML, donc tout fichier HTML est un ficher +Markdown valide. ```md - + +``` - +## En-têtes - +Vous pouvez facilement créer des balises HTML `

` à `

` en précédant le +texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon +le niveau de titre souhaité. - - +```md # Ceci est un

## Ceci est un

### Ceci est un

#### Ceci est un

##### Ceci est un

###### Ceci est un
+``` - +Markdown fournit également une façon alternative de marquer les h1 et h2. +```md Ceci est un h1 ============= Ceci est un h2 ------------- +``` + +## Styles de texte basiques - - +On peut facilement rendre un texte "gras" ou "italique" en Markdown. +```md *Ce texte est en italique.* _Celui-ci aussi._ @@ -61,15 +78,21 @@ __Celui-là aussi.__ ***Ce texte a les deux styles.*** **_Pareil ici_** *__Et là!__* +``` - +Dans le "GitHub Flavored Markdown", utilisé pour interpréter le Markdown sur +GitHub, on a également le texte barré. -~~Ce texte est barré avec strikethrough.~~ +```md +~~Ce texte est barré.~~ +``` + +## Paragraphes - +Les paragraphes sont représentés par une ou plusieurs lignes de texte séparées +par une ou plusieurs lignes vides. +```md Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. @@ -77,21 +100,23 @@ Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! +``` - +Si jamais vous souhaitez insérer une balise HTML `
`, vous pouvez ajouter +un ou plusieurs espaces à la fin de votre paragraphe, et en commencer un +nouveau. -J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). +```md +J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! +``` - +Les blocs de citations sont générés aisément, grâce au caractère >. +```md > Ceci est une superbe citation. Vous pouvez même -> revenir à la ligne quand ça vous chante, et placer un `>` +> revenir à la ligne quand ça vous chante, et placer un `>` > devant chaque bout de ligne faisant partie > de la citation. > La taille ne compte pas^^ tant que chaque ligne commence par un `>`. @@ -99,191 +124,248 @@ Bigre, il y a un
au dessus de moi! > Vous pouvez aussi utiliser plus d'un niveau >> d'imbrication! > Classe et facile, pas vrai? +``` + +## Listes - - +Les listes non ordonnées sont marquées par des asterisques, signes plus ou +signes moins. +```md * Item * Item * Un autre item +``` ou +```md + Item + Item + Encore un item +``` ou +```md - Item - Item - Un dernier item +``` - +Les listes ordonnées sont générées via un nombre suivi d'un point. +```md 1. Item un 2. Item deux 3. Item trois +``` - +Vous pouvez même vous passer de tout numéroter, et Markdown générera les bons +chiffres. Ceci dit, cette variante perd en clarté. +```md 1. Item un 1. Item deux 1. Item trois - +``` - +(Cette liste sera interprétée de la même façon que celle au dessus) +Vous pouvez également utiliser des sous-listes. + +```md 1. Item un 2. Item deux 3. Item trois * Sub-item * Sub-item 4. Item quatre +``` - - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. +Il y a même des listes de taches. Elles génèrent des champs HTML de type case à +cocher. +```md +Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML +non-cochées. - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. - [x] Ça ... c'est fait! +``` + +## Blocs de code - - +Pour marquer du texte comme étant du code (qui utilise la balise ``), il +suffit d'indenter chaque ligne avec 4 espaces ou une tabulation. +```md echo "Ça, c'est du Code!"; var Ça = "aussi !"; +``` - +L'indentation par tabulation (ou série de quatre espaces) fonctionne aussi à +l'intérieur du bloc de code. +```md my_array.each do |item| puts item end +``` - +Des bouts de code en mode en ligne s'ajoutent en utilisant le caractères +`` ` ``. +```md La fonction `run()` ne vous oblige pas à aller courir! +``` - +En "GitHub Flavored Markdown", vous pouvez utiliser des syntaxes spécifiques +selon le language. -\`\`\`ruby - +
+```ruby
 def foobar
-puts "Hello world!"
+    puts "Hello world!"
 end
-\`\`\` 
+```
+
-<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub -va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> +Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub va +utiliser une coloration syntaxique pour le langage indiqué après les \`\`\`. - - +## Séparateur horizontal +La balise `
` peut être aisement ajoutée en utilisant trois ou plus +astérisques ou tirets, avec ou sans espaces entre chacun. + +```md *** --- - - - **************** +``` - - +## Liens hypertextes +Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des +liens hypertextes. Le texte du lien entre crochet `` [] ``, l'url entre +parenthèses `` () ``, et voilà le travail. + +```md [Clic moi!](http://test.com/) +``` - +Pour ajouter un attribut titre, ajoutez le entre les parenthèses entre +guillemets apres le lien. +```md [Clic moi!](http://test.com/ "Lien vers Test.com") +``` - +Markdown supporte aussi les liens relatifs. +```md [En avant la musique](/music/). +``` - +Les liens de références sont eux aussi disponibles en Markdown. +```md [Cliquez ici][link1] pour plus d'information! [Regardez aussi par ici][foobar] si vous voulez. [link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" +[foobar]: http://foobar.biz/ "Génial!" +``` - +Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou +absent. Les références peuvent être placées où vous voulez dans le document et +les identifiants peuvent être n'importe quoi tant qu'ils sont uniques. - +Il y a également le nommage implicite qui transforme le texte du lien en +identifiant. +```md [Ceci][] est un lien. [ceci]: http://ceciestunlien.com/ +``` + +Mais ce n'est pas beaucoup utilisé. - +## Images - - +Pour les images, la syntaxe est identique à celle des liens, sauf que précédée +d'un point d'exclamation! +```md ![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") +``` - +Là aussi, on peut utiliser les références. +```md ![Ceci est l'attribut ALT de l'image][monimage] [monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." +``` + +## Divers - - +### Liens hypertextes automatiques +```md est équivalent à : [http://testwebsite.com/](http://testwebsite.com/) +``` - +### Liens hypertextes automatiques pour emails +```md +``` + +### Caracteres d'echappement - Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ -Pour taper *ce texte* entouré d'astérisques mais pas en italique : +```md +Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. +``` + +### Touches de clavier - - +Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `` +pour représenter une touche du clavier. +```md +Ton ordinateur a planté? Essayer de taper : +Ctrl+Alt+Del +``` + +### Tableaux + +Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et +ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin : + +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Alignement Gauche | Centé | Alignement Droite | | bla | bla | bla | +``` - +ou bien, pour un résultat équivalent : +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ough que c'est moche | svp | arrêtez - - - ``` -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. +Pour plus d'information, consultez le post officiel de Jhon Gruber à propos de +la syntaxe [ici](http://daringfireball.net/projects/markdown/syntax) et la +superbe fiche pense-bête de Adam Pritchard [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 2d50b676c5bda44f9f5478f1eb6ee19923058247 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 18 Oct 2018 21:50:37 +0530 Subject: Fix upper register in character, closes #3014 --- uk-ua/java-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index df642f73..40d56988 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -592,7 +592,7 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // Позначення класу як абстрактного означає, що оголошені у ньому методи мають // бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри // абстракних класів, але їх можна успадковувати. Нащадок зобов’язаний реалізувати всі абстрактні -// методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені, +// методи. На відміну від інтерфейсів, абстрактні класи можуть мати як визначені, // так і абстрактні методи. Методи в інтерфейсах не мають тіла, // за винятком статичних методів, а змінні неявно мають модифікатор final, на відміну від // абстрактного класу. Абстрактні класи МОЖУТЬ мати метод «main». -- cgit v1.2.3 From 3cfb769bfbc42f5e4236401707913f6725a3070c Mon Sep 17 00:00:00 2001 From: Matthew Biondi Date: Thu, 18 Oct 2018 12:26:26 -0400 Subject: Addresses #3009, corrects C++ headers description --- c++.html.markdown | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 9d6470be..8be5a278 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -71,10 +71,16 @@ void func(); // function which may accept any number of arguments // Use nullptr instead of NULL in C++ int* ip = nullptr; -// C standard headers are available in C++, -// but are prefixed with "c" and have no .h suffix. +// C standard headers are available in C++. +// C headers end in .h, while +// C++ headers are prefixed with "c" and have no ".h" suffix. + +// The C++ standard version: #include +//The C standard version: +#include + int main() { printf("Hello, world!\n"); -- cgit v1.2.3 From 99cd64ed04b10e1ea8c7ae0f2eba32bed0e3590d Mon Sep 17 00:00:00 2001 From: abonte <6319051+abonte@users.noreply.github.com> Date: Thu, 18 Oct 2018 19:34:03 +0200 Subject: fix typos and accent marks --- it-it/java-it.html.markdown | 70 ++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 54602cff..1669816e 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -17,14 +17,14 @@ concorrente, basato su classi e adatto a svariati scopi. ```java // I commenti su singola linea incominciano con // /* -I commenti su piu' linee invece sono cosi' +I commenti su più linee invece sono così */ /** -I commenti per la documentazione JavaDoc si fanno cosi'. +I commenti per la documentazione JavaDoc si fanno così. Vengono usati per descrivere una classe o alcuni suoi attributi. */ -// Per importare la classe ArrayList conenuta nel package java.util +// Per importare la classe ArrayList contenuta nel package java.util import java.util.ArrayList; // Per importare tutte le classi contenute nel package java.security import java.security.*; @@ -48,7 +48,7 @@ public class LearnJava { System.out.print("Ciao "); System.out.print("Mondo "); - // Per stampare del testo formattato, si puo' usare System.out.printf + // Per stampare del testo formattato, si può usare System.out.printf System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159 /////////////////////////////////////// @@ -60,7 +60,7 @@ public class LearnJava { */ // Per dichiarare una variabile basta fare int fooInt; - // Per dichiarare piu' di una variabile dello lo stesso tipo si usa: + // Per dichiarare più di una variabile dello lo stesso tipo si usa: // , , int fooInt1, fooInt2, fooInt3; @@ -71,7 +71,7 @@ public class LearnJava { // Per inizializzare una variabile si usa // = int fooInt = 1; - // Per inizializzare piu' di una variabile dello lo stesso tipo + // Per inizializzare più di una variabile dello lo stesso tipo // si usa , , = int fooInt1, fooInt2, fooInt3; fooInt1 = fooInt2 = fooInt3 = 1; @@ -94,7 +94,7 @@ public class LearnJava { // Long - intero con segno a 64 bit (in complemento a 2) // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L viene usato per indicare che il valore e' di tipo Long; + // L viene usato per indicare che il valore è di tipo Long; // altrimenti il valore viene considerato come intero. // Nota: Java non dispone di interi senza segno. @@ -102,14 +102,14 @@ public class LearnJava { // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754) // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f o F indicano the la variabile e' di tipo float; + // f o F indicano the la variabile è di tipo float; // altrimenti il valore viene considerato come double. // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754) // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - Puo' assumere il valore vero (true) o falso (false) + // Boolean - Può assumere il valore vero (true) o falso (false) boolean fooBoolean = true; boolean barBoolean = false; @@ -118,26 +118,26 @@ public class LearnJava { // Le variabili precedute da final possono essere inizializzate una volta sola, final int HOURS_I_WORK_PER_WEEK = 9001; - // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento. + // però è possibile dichiararle e poi inizializzarle in un secondo momento. final double E; E = 2.71828; // BigInteger - Interi a precisione arbitraria // - // BigInteger e' un tipo di dato che permette ai programmatori di - // gestire interi piu' grandi di 64 bit. Internamente, le variabili + // BigInteger è un tipo di dato che permette ai programmatori di + // gestire interi più grandi di 64 bit. Internamente, le variabili // di tipo BigInteger vengono memorizzate come un vettore di byte e // vengono manipolate usando funzioni dentro la classe BigInteger. // - // Una variabile di tipo BigInteger puo' essere inizializzata usando + // Una variabile di tipo BigInteger può essere inizializzata usando // un array di byte oppure una stringa. BigInteger fooBigInteger = new BigDecimal(fooByteArray); // BigDecimal - Numero con segno, immutabile, a precisione arbitraria // - // Una variabile di tipo BigDecimal e' composta da due parti: un intero + // Una variabile di tipo BigDecimal è composta da due parti: un intero // a precisione arbitraria detto 'non scalato', e un intero a 32 bit // che rappresenta la 'scala', ovvero la potenza di 10 con cui // moltiplicare l'intero non scalato. @@ -158,9 +158,9 @@ public class LearnJava { // Stringhe String fooString = "Questa e' la mia stringa!"; - // \n e' un carattere di escape che rappresenta l'andare a capo + // \n è un carattere di escape che rappresenta l'andare a capo String barString = "Stampare su una nuova riga?\nNessun problema!"; - // \t e' un carattere di escape che aggiunge un tab + // \t è un carattere di escape che aggiunge un tab String bazString = "Vuoi aggiungere un tab?\tNessun problema!"; System.out.println(fooString); System.out.println(barString); @@ -168,7 +168,7 @@ public class LearnJava { // Vettori // La dimensione di un array deve essere decisa in fase di - // istanziazione. Per dichiarare un array si puo' fare in due modi: + // istanziazione. Per dichiarare un array si può fare in due modi: // [] = new []; // [] = new []; int[] intArray = new int[10]; @@ -189,8 +189,8 @@ public class LearnJava { System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Ci sono altri tipo di dato interessanti. - // ArrayList - Simili ai vettori, pero' offrono altre funzionalita', - // e la loro dimensione puo' essere modificata. + // ArrayList - Simili ai vettori, però offrono altre funzionalità, + // e la loro dimensione può essere modificata. // LinkedList - Si tratta di una lista linkata doppia, e come tale // implementa tutte le operazioni del caso. // Map - Un insieme di oggetti che fa corrispondere delle chiavi @@ -207,7 +207,7 @@ public class LearnJava { int i1 = 1, i2 = 2; // Dichiarazone multipla in contemporanea - // L'aritmetica e' lineare. + // L'aritmetica è lineare. System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 @@ -253,7 +253,7 @@ public class LearnJava { /////////////////////////////////////// System.out.println("\n->Strutture di controllo"); - // La dichiarazione dell'If e'' C-like. + // La dichiarazione dell'If è C-like. int j = 10; if (j == 10){ System.out.println("Io vengo stampato"); @@ -328,18 +328,18 @@ public class LearnJava { System.out.println("Risultato del costrutto switch: " + stringaMese); // Condizioni brevi - // Si puo' usare l'operatore '?' per un rapido assegnamento + // Si può usare l'operatore '?' per un rapido assegnamento // o per operazioni logiche. // Si legge: - // Se (condizione) e' vera, usa , altrimenti usa + // Se (condizione) è vera, usa , altrimenti usa int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println("Se la condizione e' vera stampa A: "+bar); - // Stampa A, perche' la condizione e' vera. + // Stampa A, perché la condizione è vera. ///////////////////////////////////////// - // Convertire i tipi di tati e Typcasting + // Convertire i tipi di dati e Typecasting ///////////////////////////////////////// // Convertire tipi di dati @@ -397,16 +397,16 @@ class Bicicletta { // Variabili della bicicletta public int cadenza; - // Public: Puo' essere richiamato da qualsiasi classe + // Public: Può essere richiamato da qualsiasi classe private int velocita; - // Private: e'' accessibile solo dalla classe dove e'' stato inizializzato + // Private: è accessibile solo dalla classe dove è stato inizializzato protected int ingranaggi; - // Protected: e'' visto sia dalla classe che dalle sottoclassi + // Protected: è visto sia dalla classe che dalle sottoclassi String nome; - // default: e'' accessibile sono all'interno dello stesso package + // default: è accessibile sono all'interno dello stesso package // I costruttori vengono usati per creare variabili - // Questo e'' un costruttore + // Questo è un costruttore public Bicicletta() { ingranaggi = 1; cadenza = 50; @@ -414,7 +414,7 @@ class Bicicletta { nome = "Bontrager"; } - // Questo e'' un costruttore che richiede parametri + // Questo è un costruttore che richiede parametri public Bicicletta(int cadenza, int velocita, int ingranaggi, String nome) { this.ingranaggi = ingranaggi; this.cadenza = cadenza; @@ -469,7 +469,7 @@ class Bicicletta { } } // Fine classe bicicletta -// PennyFarthing e'' una sottoclasse della bicicletta +// PennyFarthing è una sottoclasse della bicicletta class PennyFarthing extends Bicicletta { // (Sono quelle biciclette con un unica ruota enorme // Non hanno ingranaggi.) @@ -481,7 +481,7 @@ class PennyFarthing extends Bicicletta { // Bisogna contrassegnre un medodo che si sta riscrivendo // con una @annotazione - // Per saperne di piu' sulle annotazioni + // Per saperne di più sulle annotazioni // Vedi la guida: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setIngranaggi(int ingranaggi) { @@ -518,8 +518,8 @@ class Frutta implements Commestibile, Digestibile { } } -//In Java si puo' estendere solo una classe, ma si possono implementare -//piu' interfaccie, per esempio: +//In Java si può estendere solo una classe, ma si possono implementare +//più interfaccie, per esempio: class ClasseEsempio extends AltraClasse implements PrimaInterfaccia, SecondaInterfaccia { public void MetodoPrimaInterfaccia() { -- cgit v1.2.3 From e0c4fd13ddcee41959d496da8cf7e561d4759e90 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Thu, 18 Oct 2018 22:17:50 +0200 Subject: [hq9+/de] Translate hq9+ to german --- de-de/hq9+-de.html.markdown | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 de-de/hq9+-de.html.markdown diff --git a/de-de/hq9+-de.html.markdown b/de-de/hq9+-de.html.markdown new file mode 100644 index 00000000..b343201a --- /dev/null +++ b/de-de/hq9+-de.html.markdown @@ -0,0 +1,43 @@ +--- +language: HQ9+ +filename: hq9+.html +contributors: + - ["Alexey Nazaroff", "https://github.com/rogaven"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +HQ9+ ist eine Parodie auf esoterische Programmiersprachen und wurde von Cliff Biffle kreiert. +Die Sprache hat nur vier Befehle und ist nicht Turing-vollständig. + +``` +Es gibt nur vier Befehle, die durch die folgenden vier Zeichen dargestellt werden +H: druckt "Hello, world!" +Q: druckt den Quellcode des Programms (ein Quine) +9: druckt den Liedtext von "99 Bottles of Beer" ++: erhöhe den Akkumulator um Eins (Der Wert des Akkumulators kann nicht gelesen werden) +Jedes andere Zeichen wird ignoriert. + +Ok. Lass uns ein Programm schreiben: + HQ + +Ergebnis: + Hello world! + HQ + +HQ9+ ist zwar sehr simpel, es erlaubt aber dir Sachen zu machen, die in +anderen Sprachen sehr schwierig sind. Zum Beispiel druckt das folgende Programm +drei Mal Kopien von sich selbst auf den Bildschirm: + QQQ +Dies druckt: + QQQ + QQQ + QQQ +``` + +Und das ist alles. Es gibt sehr viele Interpreter für HQ9+. +Unten findest du einen von ihnen. + ++ [One of online interpreters](https://almnet.de/esolang/hq9plus.php) ++ [HQ9+ official website](http://cliffle.com/esoterica/hq9plus.html) -- cgit v1.2.3 From a3812bbf248a9e53cd33a141bedc747f8e305b74 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Thu, 18 Oct 2018 22:20:25 +0200 Subject: [opencv/de] Translate opencv to german --- de-de/opencv-de.html.markdown | 152 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 de-de/opencv-de.html.markdown diff --git a/de-de/opencv-de.html.markdown b/de-de/opencv-de.html.markdown new file mode 100644 index 00000000..31d0d05f --- /dev/null +++ b/de-de/opencv-de.html.markdown @@ -0,0 +1,152 @@ +--- +category: tool +tool: OpenCV +filename: learnopencv.py +contributors: + - ["Yogesh Ojha", "http://github.com/yogeshojha"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- +### Opencv + +OpenCV (Open Source Computer Vision) ist eine Bibliothek von Programmierfunktionen, +die hauptsächlich auf maschinelles Sehen in Echtzeit ausgerichtet ist. +Ursprünglich wurde OpenCV von Intel entwickelt. Später wurde es von von +Willow Garage und dann Itseez (das später von Intel übernommen wurde) unterstützt. +OpenCV unterstützt derzeit eine Vielzahl von Sprachen, wie C++, Python, Java uvm. + +#### Installation + +Bitte lese diese Artikel für die Installation von OpenCV auf deinen Computer. + +* Windows Installationsanleitung: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() +* Mac Installationsanleitung (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() +* Linux Installationsanleitung (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() + +### Hier werden wir uns auf die Pythonimplementierung von OpenCV konzentrieren. + +```python +# Bild in OpenCV lesen +import cv2 +img = cv2.imread('Katze.jpg') + +# Bild darstellen +# Die imshow() Funktion wird verwendet um das Display darzustellen. +cv2.imshow('Image',img) +# Das erste Argument ist der Titel des Fensters und der zweite Parameter ist das Bild +# Wenn du den Fehler Object Type None bekommst ist eventuell dein Bildpfad falsch. +# Bitte überprüfe dann den Pfad des Bildes erneut. +cv2.waitKey(0) +# waitKey() ist eine Tastaturbindungsfunktion, sie nimmt Argumente in +# Millisekunden an. Für GUI Ereignisse MUSST du die waitKey() Funktion verwenden. + +# Ein Bild schreiben +cv2.imwrite('graueKatze.png',img) +# Das erste Arkument ist der Dateiname und das Zweite ist das Bild + +# Konveriere das Bild zu Graustufen +gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +# Videoaufnahme von der Webcam +cap = cv2.VideoCapture(0) +# 0 ist deine Kamera, wenn du mehrere Kameras hast musst du deren Id eingeben +while(True): + # Erfassen von Einzelbildern + _, frame = cap.read() + cv2.imshow('Frame',frame) + # Wenn der Benutzer q drückt -> beenden + if cv2.waitKey(1) & 0xFF == ord('q'): + break +# Die Kamera muss wieder freigegeben werden +cap.release() + +# Wiedergabe von Videos aus einer Datei +cap = cv2.VideoCapture('film.mp4') +while(cap.isOpened()): + _, frame = cap.read() + # Das Video in Graustufen abspielen + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + cv2.imshow('frame',gray) + if cv2.waitKey(1) & 0xFF == ord('q'): + break +cap.release() + +# Zeichne eine Linie in OpenCV +# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +cv2.line(img,(0,0),(511,511),(255,0,0),5) + +# Zeichne ein Rechteck +# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# thickness = -1 wird zum Füllen des Rechtecks verwendet +cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) + +# Zeichne ein Kreis +cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img,(200,90), 100, (0,0,255), -1) + +# Zeichne eine Ellipse +cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) + +# Text auf Bildern hinzufügen +cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) + +# Bilder zusammenfüggen +img1 = cv2.imread('Katze.png') +img2 = cv2.imread('openCV.jpg') +dst = cv2.addWeighted(img1,0.5,img2,0.5,0) + +# Schwellwertbild +# Binäre Schwellenwerte +_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +# Anpassbare Schwellenwerte +adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) + +# Weichzeichnung von einem Bild +# Gausßscher Weichzeichner +blur = cv2.GaussianBlur(img,(5,5),0) +# Rangordnungsfilter +medianBlur = cv2.medianBlur(img,5) + +# Canny-Algorithmus +img = cv2.imread('Katze.jpg',0) +edges = cv2.Canny(img,100,200) + +# Gesichtserkennung mit Haarkaskaden +# Lade die Haarkaskaden von https://github.com/opencv/opencv/blob/master/data/haarcascades/ herunter +import cv2 +import numpy as np +face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') +eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') + +img = cv2.imread('Mensch.jpg') +gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +aces = face_cascade.detectMultiScale(gray, 1.3, 5) +for (x,y,w,h) in faces: + cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) + roi_gray = gray[y:y+h, x:x+w] + roi_color = img[y:y+h, x:x+w] + eyes = eye_cascade.detectMultiScale(roi_gray) + for (ex,ey,ew,eh) in eyes: + cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + +cv2.imshow('img',img) +cv2.waitKey(0) + +cv2.destroyAllWindows() +# destroyAllWindows() zerstört alle Fenster +# Wenn du ein bestimmtes Fenter zerstören möchtest musst du den genauen Namen des +# von dir erstellten Fensters übergeben. +``` + +### Weiterführende Literatur: +* Lade Kaskade hier herunter [https://github.com/opencv/opencv/blob/master/data/haarcascades]() +* OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() +* Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org]() +* Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV]() +* Gute OpenCv Tutorials + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() + * [https://realpython.com/python-opencv-color-spaces]() + * [https://pyimagesearch.com]() + * [https://www.learnopencv.com]() -- cgit v1.2.3 From daa95c961c93856eb1eb7265a7a52fe7360ddf7d Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Thu, 18 Oct 2018 22:26:05 +0200 Subject: [paren/de] Translate paren to german --- de-de/paren-de.html.markdown | 200 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 200 insertions(+) create mode 100644 de-de/paren-de.html.markdown diff --git a/de-de/paren-de.html.markdown b/de-de/paren-de.html.markdown new file mode 100644 index 00000000..0d914c05 --- /dev/null +++ b/de-de/paren-de.html.markdown @@ -0,0 +1,200 @@ +--- + +language: Paren +filename: learnparen.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] + - ["Claudson Martins", "https://github.com/claudsonm"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +[Paren](https://bitbucket.org/ktg/paren) ist ein Dialekt von Lisp. +Es ist als eingebettete Sprache konzipiert. + +Manche Beispiele sind von . + +```scheme +;;; Kommentare +# Kommentare + +;; Einzeilige Kommentare starten mit einem Semikolon oder einem Hashtag + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Primitive Datentypen und Operatoren +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Zahlen +123 ; int +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : int +(double 123) ; => 123 : double + +;; Funktionsapplikationen werden so geschrieben: (f x y z ...) +;; Dabei ist f eine Funktion und x, y, z sind die Operatoren. +;; Wenn du eine Literalliste von Daten erstelllen möchtest, +;; verwende (quote) um zu verhindern, dass sie ausgewertet zu werden. +(quote (+ 1 2)) ; => (+ 1 2) +;; Nun einige arithmetische Operationen +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Wahrheitswerte +true ; for Wahr +false ; for Falsch +(! true) ; => Falsch +(&& true false (prn "doesn't get here")) ; => Falsch +(|| false true (prn "doesn't get here")) ; => Wahr + +;;; Zeichen sind Ints. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Zeichenketten sind ein Array von Zahlen mit fester Länge. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; Backslash ist ein Escape-Zeichen +"Foo\tbar\r\n" ; beinhaltet C Escapes: \t \r \n + +;; Zeichenketten können auch verbunden werden! +(strcat "Hello " "world!") ; => "Hello world!" + +;; Eine Zeichenketten kann als Liste von Zeichen behandelt werden +(char-at "Apple" 0) ; => 65 + +;; Drucken ist ziemlich einfach +(pr "Ich bin" "Paren. ") (prn "Schön dich zu treffen!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variablen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Du kannst Variablen setzen indem du (set) verwedest +;; eine Variable kann alle Zeichen besitzen außer: ();#" +(set some-var 5) ; => 5 +some-var ; => 5 + +;; Zugriff auf eine zuvor nicht zugewiesene Variable erzeugt eine Ausnahme +; x ; => Unknown variable: x : nil + +;; Lokale Bindung: Verwende das Lambda Calculus! 'a' und 'b' +;; sind nur zu '1' und '2' innerhalb von (fn ...) gebunden. +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Sammlungen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Listen + +;; Listen sind Vektrorartige Datenstrukturen. (Zufälliger Zugriff ist O(1). +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; 'list' ist ein komfortabler variadischer Konstruktor für Listen +(list 1 2 3) ; => (1 2 3) +;; und ein quote kann als literaler Listwert verwendet werden +(quote (+ 1 2)) ; => (+ 1 2) + +;; Du kannst 'cons' verwenden um ein Element an den Anfang einer Liste hinzuzufügen. +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Listen sind ein sehr einfacher Typ, daher gibt es eine Vielzahl an Funktionen +;; für Sie. Ein paar Beispiele: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funktionen +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Verwende 'fn' um Funktionen zu erstellen. +;; eine Funktion gibt immer den Wert ihres letzten Ausdrucks zurück +(fn () "Hello World") ; => (fn () Hello World) : fn + +;; Verwende Klammern um alle Funktionen aufzurufen, inklusive Lambda Ausdrücke +((fn () "Hello World")) ; => "Hello World" + +;; Zuweisung einer Funktion zu einer Variablen +(set hello-world (fn () "Hello World")) +(hello-world) ; => "Hello World" + +;; Du kannst dies mit syntaktischen Zucker für die Funktionsdefinition verkürzen: +(defn hello-world2 () "Hello World") + +;; Die () von oben ist eine Liste von Argumente für die Funktion. +(set hello + (fn (name) + (strcat "Hello " name))) +(hello "Steve") ; => "Hello Steve" + +;; ... oder gleichwertig, unter Verwendung mit syntaktischen Zucker: +(defn hello2 (name) + (strcat "Hello " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Gleichheit +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Für Zahlen verwende '==' +(== 3 3.0) ; => wahr +(== 2 1) ; => falsch + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Kontrollfluss +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Bedingungen + +(if true ; test Ausdruck + "this is true" ; then Ausdruck + "this is false") ; else Ausdruck +; => "this is true" + +;;; Schleifen + +;; for Schleifen ist für Zahlen +;; (for SYMBOL START ENDE SCHRITT AUSDRUCK ..) +(for i 0 10 2 (pr i "")) ; => schreibt 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => schreibt 0 2.5 5 7.5 10 + +;; while Schleife +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => schreibt 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Verwende 'set' um einer Variablen oder einer Stelle einen neuen Wert zuzuweisen. +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Makros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Makros erlauben es dir die Syntax der Sprache zu erweitern. +;; Parens Makros sind einfach. +;; Tatsächlich ist (defn) ein Makro. +(defmacro setfn (name ...) (set name (fn ...))) +(defmacro defn (name ...) (def name (fn ...))) + +;; Lass uns eine Infix Notation hinzufügen +;; Let's add an infix notation +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Makros sind nicht hygenisch, Du kannst bestehende Variablen überschreiben! +;; Sie sind Codetransformationenen. +``` -- cgit v1.2.3 From af365b3631f5327218182e134c1749d0d9c3b3c9 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Thu, 18 Oct 2018 22:40:50 +0200 Subject: [rst/de] Translate rst to german --- de-de/rst-de.html.markdown | 119 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 de-de/rst-de.html.markdown diff --git a/de-de/rst-de.html.markdown b/de-de/rst-de.html.markdown new file mode 100644 index 00000000..bcfe21bd --- /dev/null +++ b/de-de/rst-de.html.markdown @@ -0,0 +1,119 @@ +--- +language: restructured text (RST) +filename: restructuredtext.rst +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +RST ist ein Dateiformat, das von der Python Community entwickelt wurde, + +um Dokumentation zu schreiben (und ist somit Teil von Docutils). + +RST-Dateien sind simple Textdateien mit einer leichtgewichtigen Syntax (im Vergleich zu HTML). + + +## Installation + +Um Restructured Text zu vewenden musst du [Python](http://www.python.org) + +installieren und das `docutils` Packet installieren. `docutils` kann mit dem folgenden + +Befehl auf der Kommandozeile installiert werden: + +```bash +$ easy_install docutils +``` + +Wenn auf deinem System `pip` installiert kannst du es statdessen auch verwenden: + +```bash +$ pip install docutils +``` + + +## Dateisyntax + +Ein einfaches Beispiel für die Dateisyntax: + +``` +.. Zeilen, die mit zwei Punkten starten sind spezielle Befehle. + +.. Wenn kein Befehl gefunden wird, wird die Zeile als Kommentar gewertet. + +============================================================================ +Haupttitel werden mit Gleichheitszeichen darüber und darunter gekennzeichnet +============================================================================ + +Beachte das es genau so viele Gleichheitszeichen, wie Hauptitelzeichen +geben muss. + +Titel werden auch mit Gleichheitszeichen unterstrichen +====================================================== + +Untertitel werden mit Strichen gekennzeichnet +--------------------------------------------- + +Text in *kursiv* oder in **fett**. Du kannst Text als Code "makieren", wenn +du doppelte Backquotes verwendest ``: ``print()``. + +Listen sind so einfach wie in Markdown: + +- Erstes Element +- Zweites Element + - Unterelement + +oder + +* Erstes Element +* Zweites Element + * Unterelement + +Tabellen sind einfach zu schreiben: + +=========== ========== +Land Hauptstadt +=========== ========== +Frankreich Paris +Japan Tokyo +=========== ======== + +Komplexere Tabellen (zusammengeführte Spalten und Zeilen) können einfach +erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu lesen :) + +Es gibt mehrere Möglichkeiten um Links zu machen: + +- Wenn man einen Unterstrich hinter einem Wort hinzufügt: Github_ Zusätzlich +muss man die Zielurl nach dem Text hinzufügen. +(Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt. +- Wenn man die vollständige Url eingibt : https://github.com/ +(Dies wird automatisch in ein Link konvertiert.) +- Wenn man es mehr Markdown ähnlich eingibt: `Github `_ . + +.. _Github https://github.com/ + +``` + + +## Wie man es verwendet + +RST kommt mit docutils, dort hast du den Befehl `rst2html`, zum Beispiel: + +```bash +$ rst2html myfile.rst output.html +``` + +*Anmerkung : Auf manchen Systemen könnte es rst2html.py sein* + +Es gibt komplexere Anwendungen, die das RST Format verwenden: + +- [Pelican](http://blog.getpelican.com/), ein statischer Websitengenerator +- [Sphinx](http://sphinx-doc.org/), Ein Dokumentationsgenerator +- und viele Andere + +## Zum Lesen + +- [Offizielle Schnellreferenz](http://docutils.sourceforge.net/docs/user/rst/quickref.html) -- cgit v1.2.3 From 6704c5b3f1f64c8d3a7bd99434eaef8dc4a4bb00 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Thu, 18 Oct 2018 22:41:48 +0200 Subject: [shutit/de] Translate shutit to german --- de-de/shutit-de.html.markdown | 330 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 de-de/shutit-de.html.markdown diff --git a/de-de/shutit-de.html.markdown b/de-de/shutit-de.html.markdown new file mode 100644 index 00000000..f66ed906 --- /dev/null +++ b/de-de/shutit-de.html.markdown @@ -0,0 +1,330 @@ +--- +category: tool +filename: learnshutit.html +tool: ShutIt +contributors: + - ["Ian Miell", "http://ian.meirionconsulting.tk"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +## ShutIt + +ShuIt ist eine Shellautomationsframework, welches für eine einfache +Handhabung entwickelt wurde. + +Er ist ein Wrapper, der auf einem Python expect Klon (pexpect) basiert. + +Es ist damit ein 'expect ohne Schmerzen'. + +Es ist verfügbar als pip install. + +## Hello World + +Starten wir mit dem einfachsten Beispiel. Erstelle eine Datei names example.py + +```python + +import shutit +session = shutit.create_session('bash') +session.send('echo Hello World', echo=True) +``` + +Führe es hiermit aus: + +```bash +python example.py +``` + +gibt aus: + +```bash +$ python example.py +echo "Hello World" +echo "Hello World" +Hello World +Ians-MacBook-Air.local:ORIGIN_ENV:RhuebR2T# +``` + +Das erste Argument zu 'send' ist der Befehl, den du ausführen möchtest. +Das 'echo' Argument gibt die Terminalinteraktion aus. ShuIt ist standardmäßig leise. + +'Send' kümmert sich um die nervige Arbeiten mit den Prompts und macht +alles was du von 'expect' erwarten würdest. + + +## Logge dich auf einen Server ein + +Sagen wir du möchtest dich auf einen Server einloggen und einen Befehl ausführen. +Ändere dafür example.py folgendermaßen: + +```python +import shutit +session = shutit.create_session('bash') +session.login('ssh you@example.com', user='du', password='meinpassword') +session.send('hostname', echo=True) +session.logout() +``` + +Dies erlaubt dir dich auf deinen Server einzuloggen +(ersetze die Details mit deinen Eigenen) und das Programm gibt dir deinen Hostnamen aus. + +``` +$ python example.py +hostname +hostname +example.com +example.com:cgoIsdVv:heDa77HB# +``` + + +Es ist klar das das nicht sicher ist. Stattdessen kann man Folgendes machen: + +```python +import shutit +session = shutit.create_session('bash') +password = session.get_input('', ispass=True) +session.login('ssh you@example.com', user='du', password=password) +session.send('hostname', echo=True) +session.logout() +``` + +Dies zwingt dich dein Passwort einzugeben: + +``` +$ python example.py +Input Secret: +hostname +hostname +example.com +example.com:cgoIsdVv:heDa77HB# +``` + + +Die 'login' Methode übernimmt wieder das veränderte Prompt für den Login. +Du übergibst ShutIt den User und das Passwort, falls es benötigt wird, +mit den du dich einloggen möchtest. ShutIt übernimmt den Rest. + +'logout' behandelt das Ende von 'login' und übernimmt alle Veränderungen des +Prompts für dich. + +## Einloggen auf mehrere Server + +Sagen wir, dass du eine Serverfarm mit zwei Servern hast und du dich in +beide Server einloggen möchtest. Dafür musst du nur zwei Session und +Logins erstellen und kannst dann Befehle schicken: + +```python +import shutit +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session1.get_input('Password für server1', ispass=True) +password2 = session2.get_input('Password für server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +session1.send('hostname', echo=True) +session2.send('hostname', echo=True) +session1.logout() +session2.logout() +``` + +Gibt aus: + +```bash +$ python example.py +Password for server1 +Input Secret: + +Password for server2 +Input Secret: +hostname +hostname +one.example.com +one.example.com:Fnh2pyFj:qkrsmUNs# hostname +hostname +two.example.com +two.example.com:Gl2lldEo:D3FavQjA# +``` + +## Beispiel: Überwachen mehrerer Server + +Wir können das obige Programm in ein einfaches Überwachungstool bringen indem +wir Logik hinzufügen um die Ausgabe von einem Befehl zu betrachten. + +```python +import shutit +capacity_command="""df / | awk '{print $5}' | tail -1 | sed s/[^0-9]//""" +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session.get_input('Passwort für Server1', ispass=True) +password2 = session.get_input('Passwort für Server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +capacity = session1.send_and_get_output(capacity_command) +if int(capacity) < 10: + print(kein Platz mehr auf Server1!') +capacity = session2.send_and_get_output(capacity_command) +if int(capacity) < 10: + print(kein Platz mehr auf Server2!') +session1.logout() +session2.logout() +``` + +Hier kannst du die 'send\_and\_get\_output' Methode verwenden um die Ausgabe von dem +Kapazitätsbefehl (df) zu erhalten. + +Es gibt elegantere Wege als oben (z.B. kannst du ein Dictionary verwenden um über +die Server zu iterieren), aber es hängt and dir wie clever das Python sein muss. + + +## kompliziertere IO - Expecting + +Sagen wir du hast eine Interaktion mit einer interaktiven Kommandozeilenprogramm, +die du automatisieren möchtest. Hier werden wir Telnet als triviales Beispiel verwenden: + +```python +import shutit +session = shutit.create_session('bash') +session.send('telnet', expect='elnet>', echo=True) +session.send('open google.com 80', expect='scape character', echo=True) +session.send('GET /', echo=True, check_exit=False) +session.logout() +``` + +Beachte das 'expect' Argument. Du brauchst nur ein Subset von Telnets +Eingabeaufforderung um es abzugleichen und fortzufahren. + +Beachte auch das neue Argument 'check\_exit'. Wir werden nachher nochmal +darauf zurückkommen. Die Ausgabe von oben ist: + +```bash +$ python example.py +telnet +telnet> open google.com 80 +Trying 216.58.214.14... +Connected to google.com. +Escape character is '^]'. +GET / +HTTP/1.0 302 Found +Cache-Control: private +Content-Type: text/html; charset=UTF-8 +Referrer-Policy: no-referrer +Location: http://www.google.co.uk/?gfe_rd=cr&ei=huczWcj3GfTW8gfq0paQDA +Content-Length: 261 +Date: Sun, 04 Jun 2017 10:57:10 GMT + + +302 Moved +

302 Moved

+The document has moved + +here +. + +Connection closed by foreign host. +``` + +Nun zurück zu 'check\_exit=False'. Da das Telnet Programm einen Fehler mit +Fehlercode (1) zurückgibt und wir nicht möchten das das Skript fehlschlägt +kannst du 'check\_exit=False' setzen und damit ShuIt wissen lassen, dass +der Ausgabecode dich nicht interessiert. + +Wenn du das Argument nicht mitgegeben hättest, dann hätte dir ShutIt +ein interaktives Terminal zurückgegeben, falls es ein Terminal zum +kommunizieren gibt. Dies nennt sich ein 'Pause point'. + + +## Pause Points + +Du kannst jederzeit 'pause point' auslösen, wenn du Folgendes in deinem Skript aufrufst: + +```python +[...] +session.pause_point('Das ist ein pause point') +[...] +``` + +Danach kannst du das Skript fortführen, wenn du CTRL und ']' zur selben Zeit drückst. +Dies ist gut für Debugging: Füge ein Pause Point hinzu und schaue dich um. +Danach kannst du das Programm weiter ausführen. Probiere folgendes aus: + +```python +import shutit +session = shutit.create_session('bash') +session.pause_point('Schaue dich um!') +session.send('echo "Hat dir der Pause point gefallen?"', echo=True) +``` + +Dies würde folgendes ausgeben: + +```bash +$ python example.py +Schaue dich um! + +Ians-Air.home:ORIGIN_ENV:I00LA1Mq# bash +imiell@Ians-Air:/space/git/shutit ⑂ master +  +CTRL-] caught, continuing with run... +2017-06-05 15:12:33,577 INFO: Sending: exit +2017-06-05 15:12:33,633 INFO: Output (squashed): exitexitIans-Air.home:ORIGIN_ENV:I00LA1Mq# [...] +echo "Hat dir der Pause point gefallen?" +echo "Hat dir der Pause point gefallen?" +Hat dir der Pause point gefallen? +Ians-Air.home:ORIGIN_ENV:I00LA1Mq# +``` + + +## noch kompliziertere IO - Hintergrund + +Kehren wir zu unseren Beispiel mit dem Überwachen von mehreren Servern zurück. +Stellen wir uns vor, dass wir eine langlaufende Aufgabe auf jedem Server durchführen möchten. +Standardmäßig arbeitet ShutIt seriell, was sehr lange dauern würde. +Wir können jedoch die Aufgaben im Hintergrund laufen lassen um sie zu beschleunigen. + +Hier ist ein Beispiel, welches du ausprobieren kannst. +Es verwendet den trivialen Befehl: 'sleep'. + + +```python +import shutit +import time +long_command="""sleep 60""" +session1 = shutit.create_session('bash') +session2 = shutit.create_session('bash') +password1 = session1.get_input('Password for server1', ispass=True) +password2 = session2.get_input('Password for server2', ispass=True) +session1.login('ssh you@one.example.com', user='du', password=password1) +session2.login('ssh you@two.example.com', user='du', password=password2) +start = time.time() +session1.send(long_command, background=True) +session2.send(long_command, background=True) +print('Es hat: ' + str(time.time() - start) + ' Sekunden zum Starten gebraucht') +session1.wait() +session2.wait() +print('Es hat:' + str(time.time() - start) + ' Sekunden zum Vollenden gebraucht') +``` + +Mein Computer meint, dass er 0.5 Sekunden gebraucht hat um die Befehle zu starten +und dann nur etwas über eine Minute gebraucht um sie zu beenden +(mit Verwendung der 'wait' Methode). + + +Das alles ist trivial, aber stelle dir vor das du hunderte an Servern so managen +kannst und man kann nun das Potential sehen, die in ein paar Zeilen Code und ein Python +import liegen können. + + +## Lerne mehr + +Es gibt noch viel mehr, was mit ShutIt erreicht werden kann. + +Um mehr zu erfahren, siehe: + +[ShutIt](https://ianmiell.github.io/shutit/) +[GitHub](https://github.com/ianmiell/shutit/blob/master/README.md) + +Es handelt sich um ein breiteres Automatiesierungsframework, und das oben +genannte ist der sogennante 'standalone Modus'. + +Feedback, feature requests, 'Wie mache ich es' sind herzlich willkommen! Erreiche mit unter +[@ianmiell](https://twitter.com/ianmiell) -- cgit v1.2.3 From 230b8b019f1d9e61d263cba42444496c99c06bde Mon Sep 17 00:00:00 2001 From: Senuros Date: Fri, 19 Oct 2018 12:53:36 +0200 Subject: Added another good Tutorial source, fixed word consistency --- de-de/opencv-de.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/de-de/opencv-de.html.markdown b/de-de/opencv-de.html.markdown index 31d0d05f..2d9a2c4e 100644 --- a/de-de/opencv-de.html.markdown +++ b/de-de/opencv-de.html.markdown @@ -145,8 +145,9 @@ cv2.destroyAllWindows() * OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() * Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org]() * Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV]() -* Gute OpenCv Tutorials +* Gute OpenCV Tutorials * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() * [https://realpython.com/python-opencv-color-spaces]() * [https://pyimagesearch.com]() * [https://www.learnopencv.com]() + * [https://docs.opencv.org/master/]() -- cgit v1.2.3 From 67730b4e0b3100a7a6df925ef28606b71aa30a43 Mon Sep 17 00:00:00 2001 From: Bradley Kemp Date: Fri, 19 Oct 2018 13:55:51 +0100 Subject: Add example of "implements" keyword --- typescript.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index db6579e2..9158f123 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -113,6 +113,13 @@ class Point { static origin = new Point(0, 0); } +// Classes can be explicitly marked as implementing an interface. +// Any missing properties will then cause an error at compile-time. +class PointPerson implements Person { + name: string + move() {} +} + let p1 = new Point(10, 20); let p2 = new Point(25); //y will be 0 -- cgit v1.2.3 From 6b3e3af2ac4138bd83ab472ef842cd868db9d30c Mon Sep 17 00:00:00 2001 From: Rick Haan Date: Fri, 19 Oct 2018 21:35:42 +0200 Subject: Added Dutch translation of Vim --- nl-nl/vim-nl.html.markdown | 272 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 nl-nl/vim-nl.html.markdown diff --git a/nl-nl/vim-nl.html.markdown b/nl-nl/vim-nl.html.markdown new file mode 100644 index 00000000..a69c031c --- /dev/null +++ b/nl-nl/vim-nl.html.markdown @@ -0,0 +1,272 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Rick Haan", "https://github.com/RickHaan"] +filename: learnvim-nl.yaml +lang: nl-nl +--- + +# Vim in het Nederlands + +[Vim](http://www.vim.org) +(Vi IMproved) is een kopie van de populaire vi editor voor Unix. Het is +ontworpen voor snelheid, verhoogde productiviteit en is beschikbaar in de meeste +unix-gebaseerde systemen. Het heeft verscheidene toetscombinaties voor snelle +navigatie en aanpassingen in het doelbestand. + +## De Basis van het navigeren in Vim + +``` Vim + vim # Open in vim + :help # Open ingebouwde documentatie over als + deze bestaat + :q # Vim afsluiten + :w # Huidig bestand opslaan + :wq # Huidig bestand opslaan en vim afsluiten + ZZ # Huidig bestand opslaan en vim afsluiten + :x # Huidig bestand opslaan en vim afsluiten, verkorte versie + :q! # Afsluiten zonder opslaan + # ! *forceert* het normale afsluiten met :q + + u # Ongedaan maken + CTRL+R # Opnieuw doen + + h # Ga 1 karakter naar links + j # Ga 1 regel naar beneden + k # Ga 1 regel omhoog + l # Ga 1 karakter naar rechts + + Ctrl+B # Ga 1 volledig scherm terug + Ctrl+F # Ga 1 volledig scherm vooruit + Ctrl+D # Ga 1/2 scherm vooruit + Ctrl+U # Ga 1/2 scherm terug + + # Verplaatsen over de regel + + 0 # Verplaats naar het begin van de regel + $ # Verplaats naar het eind van de regel + ^ # Verplaats naar het eerste niet-lege karakter op de regel + + # Zoeken in de tekst + + /word # Markeert alle voorvallen van 'word' na de cursor + ?word # Markeert alle voorvallen van 'word' voor de cursor + n # Verplaatst de cursor naar het volgende voorval van + de zoekopdracht + N # Verplaatst de cursor naar het vorige voorval van + de zoekopdracht + + :%s/foo/bar/g # Verander 'foo' naar 'bar' op elke regel van het bestand + :s/foo/bar/g # Verander 'foo' naar 'bar' op de huidge regel in + het bestand + :%s/\n/\r/g # Vervang nieuwe regel karakters met nieuwe regel karakters + + # Spring naar karakters + + f # Spring vooruit en land op + t # Spring vooruit en land net voor + + # Bijvoorbeeld, + f< # Spring vooruit en land op < + t< # Spring vooruit en land net voor < + + # Verplaatsen per woord + + w # Ga 1 woord vooruit + b # Ga 1 woord achteruit + e # Ga naar het einde van het huidige woord + + # Andere karakters om mee te verplaatsen + + gg # Ga naar de bovenkant van het bestand + G # Ga naar de onderkant van het bestand + :NUM # Ga naar regel NUM (NUM is elk nummer) + H # Ga naar de bovenkant van het scherm + M # Ga naar het midden van het scherm + L # Ga naar de onderkant van het scherm +``` + +## Help documentatie + +Vim heeft ingebouwde help documentatie dat benaderd kan worden met +`:help `. Bijvoorbeeld `:help navigation` geeft documentatie weer hoe +door vim te navigeren. `:help` kan ook gebruikt worden zonder onderwerp. Dan wordt de standaard documentatie weergeven die bedoelt is om vim toegankelijker te maken. + +## Modus + +Vim is gebaseerd op het concept van **modus**. + +* Command (opdracht) modus - Vim wordt opgestart in deze mode. Deze mode wordt +gebruikt om opdrachten te geven en te navigeren +* Insert (invoer) modus - Wordt gebruikt voor het aanpassen van het bestand +* Zichtbare (Visual) modus - Wordt gebruikt voor het markeren en bewerken van +tekst +* Ex modus - Wordt gebruikt voor het uitvoeren van opdrachten met `:` + +``` Vim + i # Zet vim in de Command modus voor de cursor positie + a # Zet vim in de Insert modus na de cursor positie (append) + v # Zet vim in de Visual modus + : # Zet vim in de ex modus + # 'Escapes' vanuit elke modus naar de Command modus + + # Het kopiëren en plakken van tekst + + y # Yank (kopieer) wat geselecteerd is + yy # Yank (kopieer) de huidige regel + d # Verwijder wat geselecteerd is + dd # Verwijder de huidige regel + p # Plak de huidige tekst op de cursor positie + P # Plak de huidige tekst voor de cursor positie + x # Verwijder karakter op cursor positie +``` + +## De 'gramatica' van vim + +Vim kan aangeleerd worden als een set van acties in het 'Verb-Modifier-Noun' +formaat waar: + +Verb (werkwoord) - De uit te voeren actie +Modifier (bijwoord) - Hoe de actie uitgevoerd dient te worden +Noun - Het object waarop de actie uitgevoerd wordt + +Een paar belangrijke voorbeelden van 'Verbs', 'Modifiers', en 'Nouns' zijn: + +``` Vim + # 'Verbs' + + d # Verwijder + c # Verander + y # Kopieer + v # Zichtbaar selecteren + + # 'Modifiers' + + i # Binnen + a # Rondom + NUM # Elk nummer + f # Zoekt iets en selecteerd het + t # Zoekt iets en selecteerd het karakter voor het + / # Vindt een combinatie van tekens vanaf de cursor + ? # Vindt een combinatie van tekens voor de cursor + + # 'Nouns' + + w # Woord + s # Zin + p # Paragraaf + b # Blok + + # Voorbeeld 'zinnen' of opdrachten + + d2w # Verwijder twee woorden + cis # Verander in de zin + yip # Kopiereer in de paragraaf + ct< # Verander naar haakje openen + # Verander de tekst vanaf de huidige positie tot het volgende haakje + openen + d$ # Verwijder tot het einde van de regel +``` + +## Een aantal afkortingen en trucs + +``` Vim + > # Verspring de selectie met 1 blok + < # Verspring de selectie met 1 blok terug + :earlier 15 # Zet het document terug naar de situatie van 15 minuten + geleden + :later 15 # Zet het document in de situatie 15 minuten in de toekomst + (omgekeerde van de vorige opdracht) + ddp # Wissel de positie van opeenvolgende regels. dd daarna p + . # Herhaal de vorige opdracht + :w !sudo tee% # Sla het huidige bestand op als root + :set syntax=c # Stel syntax uitlichten in op 'c' + :sort # Sorteer alle regels + :sort! # Sorteer alle regels omgekeerd + :sort u # Sorteer alle regels en verwijder duplicaten + ~ # Stel letter case in voor geselecteerde tekst + u # Verander de geselecteerde tekst naar kleine letters + U # Verander de geselecteerde tekst naar hoofdletters + + # Fold text + zf # Creeer een vouw op de geslecteerde tekst + zo # Open huidige vouw + zc # Sluit huidige vouw + zR # Open alle vouwen + zM # Sluit alle vouwen +``` + +## Macro's + +Macro's zijn opgeslagen opdrachten. Wanneer je begint met het opnemen van een +macro dan worden **alle** acties opgenomen, totdat je stopt met opnemen. Als de +macro uitgevoerd wordt, worden alle acties in de zelfde volgorde als tijdens het +opnemen uitgevoerd. + +``` Vim + qa # Start met het opnemen van de makro genaamd 'a' + q # Stop met opnemen + @a # Gebruik macro 'a' +``` + +## Configureren van .vimrc + +Het .vimrc bestand kan gebruikt worden voor het opslaan van een +standaardconfiguratie van Vim. Het bestand wordt opgeslagen in de home map van de gebruiker. Hieronder staat een voorbeeld van een .vimrc bestand. + +``` Vim +" Voorbeeld ~/.vimrc +" 2015.10 + +" In te stellen dat Vim niet samenwerkt met Vi +set nocompatible + +" Stel in dat Vim kijkt naar de bestandstype voor syntax uitlichting en +automatish inspringen +filetype indent plugin on + +" Zet inspringen aan +syntax on + +" Betere opdracht regel aanvulling +set wildmenu + +" Gebruik niet hoofdlettergevoelig zoeken. +set ignorecase +set smartcase + +" Gebruik automatisch inspringen +set autoindent + +" Geef regelnummers weer +set number + +" Het aantal zichtbare spatie's per TAB +set tabstop=4 + +" Het aantal spatie's tijdens het aanpassen +set softtabstop=4 + +" Aantal spatie's wanneer (>> en <<) worden gebruikt + +" Maak van TAB's spatie's +set expandtab + +" Gebruik slimme tabs spatie's voor inspringen en uitlijnen +set smarttab +``` + +## Referenties (Engels) + +[Vim | Home](http://www.vim.org/index.php) + +`$ vimtutor` + +[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/) + +[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about) + +[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim) \ No newline at end of file -- cgit v1.2.3 From cb88631777e409ad7358b39a9902c011a102f000 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Fri, 19 Oct 2018 21:27:51 -0300 Subject: [less/pt-br] Add portuguese language for less --- pt-br/less-pt.html.markdown | 390 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 390 insertions(+) create mode 100644 pt-br/less-pt.html.markdown diff --git a/pt-br/less-pt.html.markdown b/pt-br/less-pt.html.markdown new file mode 100644 index 00000000..679a2ed2 --- /dev/null +++ b/pt-br/less-pt.html.markdown @@ -0,0 +1,390 @@ +--- +language: less +filename: learnless.less +contributors: + - ["Saravanan Ganesh", "http://srrvnn.me"] + +lang: pt-br +--- + +Less é um pré-processador de CSS, que adiciona recursos como variáveis, aninhamento, mixins e muito mais. +Less (e outros pré-processadores, como o [Sass](http://sass-lang.com/)) ajudam os desenvolvedores a escreverem código que pode ser mantido e DRY (não se repita). + +```css + + +//Comentários de linha única são removidos quando Less é compilado para CSS. + +/*Comentários de várias linhas são preservados.*/ + + + +/* Variáveis +==============================*/ + + +/* Você pode armazenar um valor de CSS (como uma cor) em uma variável. + Use o símbolo '@' para criar uma variável. */ + +@primary-color: #a3a4ff; +@secondary-color: #51527f; +@body-font: 'Roboto', sans-serif; + +/* Você pode usar as variáveis ​​em toda a sua folha de estilo. + Agora, se você quiser alterar uma cor, só precisa fazer a alteração uma vez. */ + +body { + background-color: @primary-color; + color: @secondary-color; + font-family: @body-font; +} + +/* Isso compilará para: */ + +body { + background-color: #a3a4ff; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Isso é muito mais sustentável do que ter que mudar a cor + cada vez que aparece em toda a sua folha de estilo. */ + + + +/* Mixins +==============================*/ + + +/* Se você achar que está escrevendo o mesmo código para mais de um + elemento, você pode querer reutilizá-lo facilmente. */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Você pode usar o mixin simplesmente adicionando o seletor como um estilo. */ + +div { + .center; + background-color: @primary-color; +} + +/* Que compilaria para: */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + +/* Você pode omitir o código mixin de ser compilado adicionando parênteses + depois do seletor. */ + +.center() { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +div { + .center; + background-color: @primary-color; +} + +/* Que compilaria para: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + + + +/* Aninhamento +==============================*/ + + +/* Less permite aninhar seletores nos seletores. */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* '&' será substituído pelo seletor pai. */ +/* Você também pode aninhar pseudo-classes. */ +/* Tenha em mente que o aninhamento excessivo tornará seu código menos sustentável. + As melhores práticas recomendam não ultrapassar 3 níveis de profundidade ao aninhar. + Por exemplo: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compila para: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Functions +==============================*/ + + +/* Less fornece funções que podem ser usadas para realizar uma variedade de + tarefas. Considere o seguinte: */ + +/* Funções podem ser invocadas usando seu nome e passando os + argumentos requeridos. */ + +body { + width: round(10.25px); +} + +.header { + background-color: lighten(#000, 0.5); +} + +.footer { + background-color: fadeout(#000, 0.25) +} + +/* Compila para: */ + +body { + width: 10px; +} + +.header { + background-color: #010101; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Você também pode definir suas próprias funções. Funções são muito semelhantes às + mixins. Ao tentar escolher entre uma função ou a um mixin, lembre-se + que mixins são melhores para gerar CSS, enquanto as funções são melhores para + lógica que pode ser usada em todo o seu código Less. Os exemplos na + seção 'Operadores Matemáticos' são candidatos ideais para se tornarem funções reutilizáveis. */ + +/* Esta função calcula a média de dois números: */ + +.average(@x, @y) { + @average-result: ((@x + @y) / 2); +} + +div { + .average(16px, 50px); // "chama" o mixin + padding: @average-result; // use seu valor de "retorno" +} + +/* Compila para: */ + +div { + padding: 33px; +} + + + +/* Estender (herança) +==============================*/ + + +/* Estender é uma maneira de compartilhar as propriedades de um seletor com outro. */ + +.display { + height: 50px; +} + +.display-success { + &:extend(.display); + border-color: #22df56; +} + +/* Compila para: */ + +.display, +.display-success { + height: 50px; +} +.display-success { + border-color: #22df56; +} + +/* Estender uma instrução CSS é preferível para criar um mixin + por causa da maneira como agrupa as classes que compartilham + o mesmo estilo base. Se isso foi feito com um mixin, as propriedades + seriam duplicadas para cada declaração que + chamou o mixin. Embora isso não afete o seu fluxo de trabalho, + adicione o inchaço desnecessário aos arquivos criados pelo compilador Less. */ + + + +/* Parciais e Importações +==============================*/ + + +/* Less permite criar arquivos parciais. Isso pode ajudar a manter o seu + código Less modularizado. Arquivos parciais convencionalmente começam com um '_', + por exemplo. _reset.less. e são importados para um arquivo less principal que recebe + o css compilado. */ + +/* Considere o seguinte CSS que vamos colocar em um arquivo chamado _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Less disponibiliza @import que podem ser usadas para importar parciais em um arquivo. + Isso difere da declaração tradicional CSS @import que faz + outra solicitação HTTP para buscar o arquivo importado. Less leva o + arquivo importado e combina com o código compilado. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compila para: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Operações Matemáticas +==============================*/ + + +/* Less fornece os seguintes operadores: +, -, *, / e %. Estes podem + ser úteis para calcular valores diretamente nos seus arquivos Less + para usar valores que você já calculou manualmente. Abaixo está um exemplo + de como configurar um design simples de duas colunas. */ + +@content-area: 960px; +@main-content: 600px; +@sidebar-content: 300px; + +@main-size: @main-content / @content-area * 100%; +@sidebar-size: @sidebar-content / @content-area * 100%; +@gutter: 100% - (@main-size + @sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: @main-size; +} + +.sidebar { + width: @sidebar-size; +} + +.gutter { + width: @gutter; +} + +/* Compila para: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + +## Pratique Less + +Se você quiser praticar com Less no seu navegador, confira: * [Codepen](http://codepen.io/) * [LESS2CSS](http://lesscss.org/less-preview/) + +## Compatibilidade + +Less pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo em CSS. Você deseja verificar +se o CSS que você está usando é compatível com seus navegadores de destino. + +[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificar a compatibilidade. + +## Leitura adicional +* [Documentação Oficial](http://lesscss.org/features/) +* [Less CSS - Guia do iniciante](http://www.hongkiat.com/blog/less-basic/) -- cgit v1.2.3 From 2af4f99b67ceffe2be741a2acf6bb51dd26dc931 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 20 Oct 2018 21:11:17 +0530 Subject: add Git resource --- git.html.markdown | 60 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/git.html.markdown b/git.html.markdown index 582f8863..aa96c90a 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -26,11 +26,11 @@ Version control is a system that records changes to a file(s), over time. ### Centralized Versioning vs. Distributed Versioning -* Centralized version control focuses on synchronizing, tracking, and backing +* Centralized version control focuses on synchronizing, tracking, and backing up files. -* Distributed version control focuses on sharing changes. Every change has a +* Distributed version control focuses on sharing changes. Every change has a unique id. -* Distributed systems have no defined structure. You could easily have a SVN +* Distributed systems have no defined structure. You could easily have a SVN style, centralized system, with git. [Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -57,7 +57,7 @@ A git repository is comprised of the .git directory & working tree. ### .git Directory (component of repository) -The .git directory contains all the configurations, logs, branches, HEAD, and +The .git directory contains all the configurations, logs, branches, HEAD, and more. [Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) @@ -68,15 +68,15 @@ referred to as your working directory. ### Index (component of .git dir) -The Index is the staging area in git. It's basically a layer that separates -your working tree from the Git repository. This gives developers more power +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power over what gets sent to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your -Working Tree. For example, if you added 5 files, and removed 2 others, these -changes will be contained in a commit (or snapshot). This commit can then be +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be pushed to other repositories, or not! ### Branch @@ -91,13 +91,13 @@ functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) -HEAD is a pointer that points to the current branch. A repository only has 1 -*active* HEAD. -head is a pointer that points to any commit. A repository can have any number +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number of heads. ### Stages of Git -* Modified - Changes have been made to a file but file has not been committed +* Modified - Changes have been made to a file but file has not been committed to Git Database yet * Staged - Marks a modified file to go into your next commit snapshot * Committed - Files have been committed to the Git Database @@ -111,7 +111,7 @@ to Git Database yet ### init -Create an empty Git repository. The Git repository's settings, stored +Create an empty Git repository. The Git repository's settings, stored information, and more is stored in a directory (a folder) named ".git". ```bash @@ -179,7 +179,7 @@ $ git help status ### add -To add files to the staging area/index. If you do not `git add` new files to +To add files to the staging area/index. If you do not `git add` new files to the staging area/index, they will not be included in commits! ```bash @@ -201,7 +201,7 @@ working directory/repo. ### branch -Manage your branches. You can view, edit, create, delete branches using this +Manage your branches. You can view, edit, create, delete branches using this command. ```bash @@ -250,7 +250,7 @@ $ git push origin --tags ### checkout -Updates all files in the working tree to match the version in the index, or +Updates all files in the working tree to match the version in the index, or specified tree. ```bash @@ -269,7 +269,7 @@ $ git checkout -b newBranch ### clone Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you +remote-tracking branches for each branch in the cloned repo, which allows you to push to a remote branch. ```bash @@ -285,7 +285,7 @@ $ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git - ### commit -Stores the current contents of the index in a new "commit." This commit +Stores the current contents of the index in a new "commit." This commit contains the changes made and a message created by the user. ```bash @@ -401,11 +401,11 @@ Pulls from a repository and merges it with another branch. $ git pull origin master # By default, git pull will update your current branch -# by merging in new changes from its remote-tracking branch +# by merging in new changes from its remote-tracking branch $ git pull # Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git fetch , git +# branch commits onto your local repo, like: "git fetch , git # rebase /" $ git pull origin master --rebase ``` @@ -421,7 +421,7 @@ Push and merge changes from a branch to a remote & branch. $ git push origin master # By default, git push will push and merge changes from -# the current branch to its remote-tracking branch +# the current branch to its remote-tracking branch $ git push # To link up current local branch with a remote branch, add -u flag: @@ -432,7 +432,7 @@ $ git push ### stash -Stashing takes the dirty state of your working directory and saves it on a +Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. Let's say you've been doing some work in your git repo, but you want to pull @@ -464,7 +464,7 @@ nothing to commit, working directory clean ``` You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top. ```bash @@ -495,7 +495,7 @@ Now you're ready to get back to work on your stuff! ### rebase (caution) -Take all changes that were committed on one branch, and replay them onto +Take all changes that were committed on one branch, and replay them onto another branch. *Do not rebase commits that you have pushed to a public repo*. @@ -510,7 +510,7 @@ $ git rebase master experimentBranch ### reset (caution) Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you +pulls, commits, adds, and more. It's a great command but also dangerous if you don't know what you are doing. ```bash @@ -535,7 +535,7 @@ $ git reset --hard 31f2bb1 Reflog will list most of the git commands you have done for a given time period, default 90 days. -This give you the chance to reverse any git commands that have gone wrong +This give you the chance to reverse any git commands that have gone wrong (for instance, if a rebase has broken your application). You can do this: @@ -558,8 +558,8 @@ ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) ### revert -Revert can be used to undo a commit. It should not be confused with reset which -restores the state of a project to a previous point. Revert will add a new +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new commit which is the inverse of the specified commit, thus reverting it. ```bash @@ -604,3 +604,5 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) * [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + +* [The New Boston tutorial to Git covering basic commands and workflow](https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAKWClAD_iKpNC0bGHxGhcx) -- cgit v1.2.3 From 1e26ac4badd24fed4c76f71baee0095e105d5007 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 20 Oct 2018 21:19:46 +0530 Subject: add JSON resource --- json.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/json.html.markdown b/json.html.markdown index cd42d42d..322c7a47 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -81,3 +81,5 @@ Supported data types: ## Further Reading * [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics. + +* [JSON Tutorial](https://www.youtube.com/watch?v=wI1CWzNtE-M) A concise introduction to JSON. -- cgit v1.2.3 From 3724e4e27c54d8e962b3e66ba93e89c961214c7f Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 20 Oct 2018 21:30:06 +0530 Subject: add jQuery resource --- jquery.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/jquery.html.markdown b/jquery.html.markdown index 9326c74b..a1673c10 100644 --- a/jquery.html.markdown +++ b/jquery.html.markdown @@ -104,7 +104,7 @@ tables.animate({margin-top:"+=50", height: "100px"}, 500, myFunction); // 3. Manipulation // These are similar to effects but can do more -$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div +$('div').addClass('taming-slim-20'); // Adds class taming-slim-20 to all div // Common manipulation methods $('p').append('Hello world'); // Adds to end of element @@ -126,3 +126,7 @@ $('p').each(function() { ``` + +## Further Reading + +* [Codecademy - jQuery](https://www.codecademy.com/learn/learn-jquery) A good introduction to jQuery in a "learn by doing it" format. -- cgit v1.2.3 From 097fbf70761a8e525e574162b684e14e166f871b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Sat, 20 Oct 2018 23:10:56 -0300 Subject: [make/pt-br] Add portuguese language for make --- pt-br/make-pt.html.markdown | 242 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 pt-br/make-pt.html.markdown diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown new file mode 100644 index 00000000..8e7603cc --- /dev/null +++ b/pt-br/make-pt.html.markdown @@ -0,0 +1,242 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +filename: Makefile + +lang: pt-br +--- + +Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas. + +Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux. + +```make + +# Comentários podem ser escritos assim. + +# O arquivo deve ser nomeado Makefile e então pode ser executado como `make `. +# Caso contrário, nós usamos `make -f "nome-do-arquivo" `. + +# Aviso - use somente TABS para identar em Makefiles, nunca espaços! + +#----------------------------------------------------------------------- +# Noções básicas +#----------------------------------------------------------------------- + +# Regras são do formato +# alvo: +# onde os pré-requisitos são opcionais. + +# Uma regra - esta regra só será executada se o arquivo0.txt não existir. +arquivo0.txt: + echo "foo" > arquivo0.txt + # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell. + # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão. + +# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt. +arquivo1.txt: arquivo0.txt + cat arquivo0.txt > arquivo1.txt + # se as mesmas regras de citação do shell. + @cat arquivo0.txt >> arquivo1.txt + # @ pára o comando de ser ecoado para stdout. + -@echo 'hello' + # - significa que make continuará em caso de erro. + # Experimentar `make arquivo1.txt` na linha de comando. + +# Uma regra pode ter vários alvos e vários pré-requisitos +arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt + touch arquivo2.txt + touch arquivo3.txt + +# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar +# receitas não contam e podem ser usadas para adicionar novas dependências. + +#----------------------------------------------------------------------- +# Alvos falsos +#----------------------------------------------------------------------- + +# Um alvo falso. Qualquer alvo que não seja um arquivo. +# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo. +all: maker process + +# Podemos declarar as coisas fora de ordem. +maker: + touch ex0.txt ex1.txt + +# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome +.PHONY: all maker process +# Este é um alvo especial. Existem vários outros. + +# Uma regra com dependência de um alvo falso sempre será executada +ex0.txt ex1.txt: maker + +# Alvos falsos comuns são: todos fazem instalação limpa ... + +#----------------------------------------------------------------------- +# Variáveis ​​Automáticas e Curingas +#----------------------------------------------------------------------- + +process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos + @echo $^ # $^ é uma variável que contém a lista de pré-requisitos + @echo $@ # imprime o nome do alvo + #(fpara várias regras alvo, $@ é o que causou a execução da regra) + @echo $< # o primeiro pré-requisito listado + @echo $? # somente as dependências que estão desatualizadas + @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal) + #@echo $| # todos os pré-requisitos 'somente pedidos' + +# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los +process: ex1.txt arquivo0.txt +# ex1.txt será encontrado, mas arquivo0.txt será desduplicado. + +#----------------------------------------------------------------------- +# Padrões +#----------------------------------------------------------------------- + +# Pode ensinar make a converter certos arquivos em outros arquivos. + +%.png: %.svg + inkscape --export-png $^ + +# As regras padrões só farão qualquer coisa se decidirem criar o alvo. + +# Os caminhos de diretório são normalmente ignorados quando as regras de +# padrões são correspondentes. Mas make tentará usar a regra mais +# apropriada disponível. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make utilizará a última versão para uma regra de padrão que encontrar. +%.png: %.svg + @echo esta regra é escolhida + +# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo +%.png: %.ps + @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes + +# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe +# como transformar arquivos *.c em arquivos *.o. + +# Makefiles antigos podem usar regras de sufixo em vez de regras padrões +.png.ps: + @echo essa regra é semelhante a uma regra de padrão. + +# make sobre a regra de sufixo +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variáveis +#----------------------------------------------------------------------- +# aka. macros + +# As variáveis ​​são basicamente todos os tipos de string + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Isso não funcionará, tratado como $ (n)ame. + @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias. + +# Existem 4 lugares para definir variáveis. +# Em ordem de prioridade, do maior para o menor: +# 1: argumentos de linha de comando +# 2: Makefile +# 3: variáveis ​​de ambiente do shell - faça importações automaticamente. +# 4: make tem algumas variáveis ​​predefinidas + +name4 ?= Jean +# Somente defina a variável se a variável de ambiente ainda não estiver definida. + +override name5 = David +# Pára os argumentos da linha de comando de alterar essa variável. + +name4 +=grey +# Anexar valores à variável (inclui um espaço). + +# Valores variáveis ​​específicos de padrões (extensão GNU). +echo: name2 = Sara # Verdadeiro dentro da regra de correspondência + # e também dentro de suas recursivas dependências + # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!) + +# Algumas variáveis ​​definidas automaticamente pelo make +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variáveis 2 +#----------------------------------------------------------------------- + +# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas. +# TIsso pode ser caro, então existe um segundo tipo de variável que é +# avaliado apenas uma vez. (Esta é uma extensão do GNU make) + +var := hello +var2 ::= $(var) hello +#:= e ::= são equivalentes. + +# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que +# aparecem), quebrando assim o resto da línguagem! + +# Isso não funciona +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funções +#----------------------------------------------------------------------- + +# make tem muitas funções disponíveis. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# O formato é $(func arg0,arg1,arg2...) + +# Alguns exemplos +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Diretivas +#----------------------------------------------------------------------- + +# Inclua outros makefiles, úteis para código específico da plataforma +include foo.mk + +sport = tennis +# Compilação condicional +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Há também ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### More Resources + ++ [documentação gnu make](https://www.gnu.org/software/make/manual/) ++ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/) ++ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From e3123b92837ed05dd802c24e5e99d966d2a9f306 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Sat, 20 Oct 2018 23:47:54 -0300 Subject: Remove make translate --- pt-br/make-pt.html.markdown | 242 -------------------------------------------- 1 file changed, 242 deletions(-) delete mode 100644 pt-br/make-pt.html.markdown diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown deleted file mode 100644 index 8e7603cc..00000000 --- a/pt-br/make-pt.html.markdown +++ /dev/null @@ -1,242 +0,0 @@ ---- -language: make -contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] -filename: Makefile - -lang: pt-br ---- - -Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas. - -Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux. - -```make - -# Comentários podem ser escritos assim. - -# O arquivo deve ser nomeado Makefile e então pode ser executado como `make `. -# Caso contrário, nós usamos `make -f "nome-do-arquivo" `. - -# Aviso - use somente TABS para identar em Makefiles, nunca espaços! - -#----------------------------------------------------------------------- -# Noções básicas -#----------------------------------------------------------------------- - -# Regras são do formato -# alvo: -# onde os pré-requisitos são opcionais. - -# Uma regra - esta regra só será executada se o arquivo0.txt não existir. -arquivo0.txt: - echo "foo" > arquivo0.txt - # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell. - # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão. - -# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt. -arquivo1.txt: arquivo0.txt - cat arquivo0.txt > arquivo1.txt - # se as mesmas regras de citação do shell. - @cat arquivo0.txt >> arquivo1.txt - # @ pára o comando de ser ecoado para stdout. - -@echo 'hello' - # - significa que make continuará em caso de erro. - # Experimentar `make arquivo1.txt` na linha de comando. - -# Uma regra pode ter vários alvos e vários pré-requisitos -arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt - touch arquivo2.txt - touch arquivo3.txt - -# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar -# receitas não contam e podem ser usadas para adicionar novas dependências. - -#----------------------------------------------------------------------- -# Alvos falsos -#----------------------------------------------------------------------- - -# Um alvo falso. Qualquer alvo que não seja um arquivo. -# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo. -all: maker process - -# Podemos declarar as coisas fora de ordem. -maker: - touch ex0.txt ex1.txt - -# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome -.PHONY: all maker process -# Este é um alvo especial. Existem vários outros. - -# Uma regra com dependência de um alvo falso sempre será executada -ex0.txt ex1.txt: maker - -# Alvos falsos comuns são: todos fazem instalação limpa ... - -#----------------------------------------------------------------------- -# Variáveis ​​Automáticas e Curingas -#----------------------------------------------------------------------- - -process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos - @echo $^ # $^ é uma variável que contém a lista de pré-requisitos - @echo $@ # imprime o nome do alvo - #(fpara várias regras alvo, $@ é o que causou a execução da regra) - @echo $< # o primeiro pré-requisito listado - @echo $? # somente as dependências que estão desatualizadas - @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal) - #@echo $| # todos os pré-requisitos 'somente pedidos' - -# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los -process: ex1.txt arquivo0.txt -# ex1.txt será encontrado, mas arquivo0.txt será desduplicado. - -#----------------------------------------------------------------------- -# Padrões -#----------------------------------------------------------------------- - -# Pode ensinar make a converter certos arquivos em outros arquivos. - -%.png: %.svg - inkscape --export-png $^ - -# As regras padrões só farão qualquer coisa se decidirem criar o alvo. - -# Os caminhos de diretório são normalmente ignorados quando as regras de -# padrões são correspondentes. Mas make tentará usar a regra mais -# apropriada disponível. -small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ - -# make utilizará a última versão para uma regra de padrão que encontrar. -%.png: %.svg - @echo esta regra é escolhida - -# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo -%.png: %.ps - @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes - -# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe -# como transformar arquivos *.c em arquivos *.o. - -# Makefiles antigos podem usar regras de sufixo em vez de regras padrões -.png.ps: - @echo essa regra é semelhante a uma regra de padrão. - -# make sobre a regra de sufixo -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variáveis -#----------------------------------------------------------------------- -# aka. macros - -# As variáveis ​​são basicamente todos os tipos de string - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # Isso não funcionará, tratado como $ (n)ame. - @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias. - -# Existem 4 lugares para definir variáveis. -# Em ordem de prioridade, do maior para o menor: -# 1: argumentos de linha de comando -# 2: Makefile -# 3: variáveis ​​de ambiente do shell - faça importações automaticamente. -# 4: make tem algumas variáveis ​​predefinidas - -name4 ?= Jean -# Somente defina a variável se a variável de ambiente ainda não estiver definida. - -override name5 = David -# Pára os argumentos da linha de comando de alterar essa variável. - -name4 +=grey -# Anexar valores à variável (inclui um espaço). - -# Valores variáveis ​​específicos de padrões (extensão GNU). -echo: name2 = Sara # Verdadeiro dentro da regra de correspondência - # e também dentro de suas recursivas dependências - # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!) - -# Algumas variáveis ​​definidas automaticamente pelo make -echo_inbuilt: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variáveis 2 -#----------------------------------------------------------------------- - -# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas. -# TIsso pode ser caro, então existe um segundo tipo de variável que é -# avaliado apenas uma vez. (Esta é uma extensão do GNU make) - -var := hello -var2 ::= $(var) hello -#:= e ::= são equivalentes. - -# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que -# aparecem), quebrando assim o resto da línguagem! - -# Isso não funciona -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Funções -#----------------------------------------------------------------------- - -# make tem muitas funções disponíveis. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# O formato é $(func arg0,arg1,arg2...) - -# Alguns exemplos -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Diretivas -#----------------------------------------------------------------------- - -# Inclua outros makefiles, úteis para código específico da plataforma -include foo.mk - -sport = tennis -# Compilação condicional -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo "They think it's all over; it is now" -endif - -# Há também ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - -### More Resources - -+ [documentação gnu make](https://www.gnu.org/software/make/manual/) -+ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/) -+ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From 678e42b2a34cd91f40139eefa7cc3dd3e6e4e30a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Sun, 21 Oct 2018 00:27:00 -0300 Subject: [make/pt-br] Add portuguese language for make --- pt-br/make-pt.html.markdown | 242 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 pt-br/make-pt.html.markdown diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown new file mode 100644 index 00000000..8e7603cc --- /dev/null +++ b/pt-br/make-pt.html.markdown @@ -0,0 +1,242 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +filename: Makefile + +lang: pt-br +--- + +Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas. + +Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux. + +```make + +# Comentários podem ser escritos assim. + +# O arquivo deve ser nomeado Makefile e então pode ser executado como `make `. +# Caso contrário, nós usamos `make -f "nome-do-arquivo" `. + +# Aviso - use somente TABS para identar em Makefiles, nunca espaços! + +#----------------------------------------------------------------------- +# Noções básicas +#----------------------------------------------------------------------- + +# Regras são do formato +# alvo: +# onde os pré-requisitos são opcionais. + +# Uma regra - esta regra só será executada se o arquivo0.txt não existir. +arquivo0.txt: + echo "foo" > arquivo0.txt + # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell. + # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão. + +# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt. +arquivo1.txt: arquivo0.txt + cat arquivo0.txt > arquivo1.txt + # se as mesmas regras de citação do shell. + @cat arquivo0.txt >> arquivo1.txt + # @ pára o comando de ser ecoado para stdout. + -@echo 'hello' + # - significa que make continuará em caso de erro. + # Experimentar `make arquivo1.txt` na linha de comando. + +# Uma regra pode ter vários alvos e vários pré-requisitos +arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt + touch arquivo2.txt + touch arquivo3.txt + +# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar +# receitas não contam e podem ser usadas para adicionar novas dependências. + +#----------------------------------------------------------------------- +# Alvos falsos +#----------------------------------------------------------------------- + +# Um alvo falso. Qualquer alvo que não seja um arquivo. +# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo. +all: maker process + +# Podemos declarar as coisas fora de ordem. +maker: + touch ex0.txt ex1.txt + +# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome +.PHONY: all maker process +# Este é um alvo especial. Existem vários outros. + +# Uma regra com dependência de um alvo falso sempre será executada +ex0.txt ex1.txt: maker + +# Alvos falsos comuns são: todos fazem instalação limpa ... + +#----------------------------------------------------------------------- +# Variáveis ​​Automáticas e Curingas +#----------------------------------------------------------------------- + +process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos + @echo $^ # $^ é uma variável que contém a lista de pré-requisitos + @echo $@ # imprime o nome do alvo + #(fpara várias regras alvo, $@ é o que causou a execução da regra) + @echo $< # o primeiro pré-requisito listado + @echo $? # somente as dependências que estão desatualizadas + @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal) + #@echo $| # todos os pré-requisitos 'somente pedidos' + +# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los +process: ex1.txt arquivo0.txt +# ex1.txt será encontrado, mas arquivo0.txt será desduplicado. + +#----------------------------------------------------------------------- +# Padrões +#----------------------------------------------------------------------- + +# Pode ensinar make a converter certos arquivos em outros arquivos. + +%.png: %.svg + inkscape --export-png $^ + +# As regras padrões só farão qualquer coisa se decidirem criar o alvo. + +# Os caminhos de diretório são normalmente ignorados quando as regras de +# padrões são correspondentes. Mas make tentará usar a regra mais +# apropriada disponível. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make utilizará a última versão para uma regra de padrão que encontrar. +%.png: %.svg + @echo esta regra é escolhida + +# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo +%.png: %.ps + @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes + +# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe +# como transformar arquivos *.c em arquivos *.o. + +# Makefiles antigos podem usar regras de sufixo em vez de regras padrões +.png.ps: + @echo essa regra é semelhante a uma regra de padrão. + +# make sobre a regra de sufixo +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variáveis +#----------------------------------------------------------------------- +# aka. macros + +# As variáveis ​​são basicamente todos os tipos de string + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Isso não funcionará, tratado como $ (n)ame. + @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias. + +# Existem 4 lugares para definir variáveis. +# Em ordem de prioridade, do maior para o menor: +# 1: argumentos de linha de comando +# 2: Makefile +# 3: variáveis ​​de ambiente do shell - faça importações automaticamente. +# 4: make tem algumas variáveis ​​predefinidas + +name4 ?= Jean +# Somente defina a variável se a variável de ambiente ainda não estiver definida. + +override name5 = David +# Pára os argumentos da linha de comando de alterar essa variável. + +name4 +=grey +# Anexar valores à variável (inclui um espaço). + +# Valores variáveis ​​específicos de padrões (extensão GNU). +echo: name2 = Sara # Verdadeiro dentro da regra de correspondência + # e também dentro de suas recursivas dependências + # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!) + +# Algumas variáveis ​​definidas automaticamente pelo make +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variáveis 2 +#----------------------------------------------------------------------- + +# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas. +# TIsso pode ser caro, então existe um segundo tipo de variável que é +# avaliado apenas uma vez. (Esta é uma extensão do GNU make) + +var := hello +var2 ::= $(var) hello +#:= e ::= são equivalentes. + +# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que +# aparecem), quebrando assim o resto da línguagem! + +# Isso não funciona +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funções +#----------------------------------------------------------------------- + +# make tem muitas funções disponíveis. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# O formato é $(func arg0,arg1,arg2...) + +# Alguns exemplos +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Diretivas +#----------------------------------------------------------------------- + +# Inclua outros makefiles, úteis para código específico da plataforma +include foo.mk + +sport = tennis +# Compilação condicional +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Há também ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### More Resources + ++ [documentação gnu make](https://www.gnu.org/software/make/manual/) ++ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/) ++ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From c73fbc27631e51598bcefecc5ac9606e1bab6476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Sun, 21 Oct 2018 16:45:44 -0300 Subject: [cypher/pt-br] Add portuguese language for cypher --- pt-br/cypher-pt.html.markdown | 250 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 pt-br/cypher-pt.html.markdown diff --git a/pt-br/cypher-pt.html.markdown b/pt-br/cypher-pt.html.markdown new file mode 100644 index 00000000..7cfd8dcd --- /dev/null +++ b/pt-br/cypher-pt.html.markdown @@ -0,0 +1,250 @@ +--- +language: cypher +filename: LearnCypher.cql +contributors: + - ["Théo Gauchoux", "https://github.com/TheoGauchoux"] + +lang: pt-br +--- + +O Cypher é a linguagem de consulta do Neo4j para manipular gráficos facilmente. Ela reutiliza a sintaxe do SQL e a mistura com o tipo de ascii-art para representar gráficos. Este tutorial pressupõe que você já conheça conceitos de gráficos como nós e relacionamentos. + +[Leia mais aqui.](https://neo4j.com/developer/cypher-query-language/) + + +Nós +--- + +**Representa um registro em um gráfico.** + +`()` +É um *nó* vazio, para indicar que existe um *nó*, mas não é relevante para a consulta. + +`(n)` +É um *nó* referido pela variável **n**, reutilizável na consulta. Começa com minúsculas e usa o camelCase. + +`(p:Person)` +Você pode adicionar um *label* ao seu nó, aqui **Person**. É como um tipo / uma classe / uma categoria. Começa com maiúsculas e usa o camelCase. + +`(p:Person:Manager)` +Um nó pode ter muitos *labels*. + +`(p:Person {name : 'Théo Gauchoux', age : 22})` +Um nó pode ter algumas *propriedades*, aqui **name** e **age**. Começa com minúsculas e usa o camelCase. + +Os tipos permitidos nas propriedades: + + - Numeric + - Boolean + - String + - Lista de tipos primitivos anteriores + +*Aviso: não há propriedade datetime no Cypher! Você pode usar String com um padrão específico ou um Numeric a partir de uma data específica.* + +`p.name` +Você pode acessar uma propriedade com o estilo de ponto. + + +Relacionamentos (ou Arestas) +--- + +**Conecta dois nós** + +`[:KNOWS]` +É um *relacionamento* com o *label* **KNOWS**. É um *label* como um rótulo do nó. Começa com maiúsculas e usa UPPER_SNAKE_CASE. + +`[k:KNOWS]` +O mesmo *relacionamento*, referido pela variável **k**, reutilizável na consulta, mas não é necessário. + +`[k:KNOWS {since:2017}]` +O mesmo *relacionamento*, com *propriedades* (como *nó*), aqui **since**. + +`[k:KNOWS*..4]` +É uma informação estrutural para usar em um *path* (visto posteriormente). Aqui, **\*..4** diz, “Corresponda o padrão, com a relação **k** que é repetida de 1 a 4 vezes. + + +Paths +--- + +**A maneira de misturar nós e relacionamentos.** + +`(a:Person)-[:KNOWS]-(b:Person)` +Um path descrevendo que **a** e **b** se conhecem. + +`(a:Person)-[:MANAGES]->(b:Person)` +Um path pode ser direcionado. Este path descreve que **a** é o gerente de **b**. + +`(a:Person)-[:KNOWS]-(b:Person)-[:KNOWS]-(c:Person)` +Você pode encadear vários relacionamentos. Este path descreve o amigo de um amigo. + +`(a:Person)-[:MANAGES]->(b:Person)-[:MANAGES]->(c:Person)` +Uma encadeamento também pode ser direcionada. Este path descreve que **a** é o chefe de **b** e o grande chefe de **c**. + +Padrões frequentemente usados ​​(do Neo4j doc) : + +``` +// Amigo de um amigo +(user)-[:KNOWS]-(friend)-[:KNOWS]-(foaf) + +// Path mais curto +path = shortestPath( (user)-[:KNOWS*..5]-(other) ) + +// Filtragem colaborativa +(user)-[:PURCHASED]->(product)<-[:PURCHASED]-()-[:PURCHASED]->(otherProduct) + +// Navegação de árvore +(root)<-[:PARENT*]-(leaf:Category)-[:ITEM]->(data:Product) + +``` + + +Crie consultas +--- + +Create a new node +``` +CREATE (a:Person {name:"Théo Gauchoux"}) +RETURN a +``` +*`RETURN` permite ter um resultado após a consulta. Pode ser múltiplo, como `RETURN a, b`.* + +Crie um novo relacionamento (com 2 novos nós) +``` +CREATE (a:Person)-[k:KNOWS]-(b:Person) +RETURN a,k,b +``` + +Consultas que casam +--- + +Casam todos os nós +``` +MATCH (n) +RETURN n +``` + +Casam nós por label +``` +MATCH (a:Person) +RETURN a +``` + +Casam nós por label e propriedade +``` +MATCH (a:Person {name:"Théo Gauchoux"}) +RETURN a +``` + +Casam nós de acordo com os relacionamentos (não direcionados) +``` +MATCH (a)-[:KNOWS]-(b) +RETURN a,b +``` + +Casam nós de acordo com os relacionamentos (direcionados) +``` +MATCH (a)-[:MANAGES]->(b) +RETURN a,b +``` + +Casam nós com um cláusula `WHERE` +``` +MATCH (p:Person {name:"Théo Gauchoux"})-[s:LIVES_IN]->(city:City) +WHERE s.since = 2015 +RETURN p,state +``` + +Você pode usa a cláusula `MATCH WHERE` com a cláusula `CREATE` +``` +MATCH (a), (b) +WHERE a.name = "Jacquie" AND b.name = "Michel" +CREATE (a)-[:KNOWS]-(b) +``` + + +Atualizar consultas +--- + +Atualizar uma propriedade específica de um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p.age = 23 +``` + +Substituir todas as propriedades de um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p = {name: "Michel", age: 23} +``` + +Adicionar nova propriedade a um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p + = {studies: "IT Engineering"} +``` + +Adicione um label a um nó +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +SET p:Internship +``` + + +Excluir consultas +--- + +Excluir um nó específico (os relacionamentos vinculados devem ser excluídos antes) +``` +MATCH (p:Person)-[relationship]-() +WHERE p.name = "Théo Gauchoux" +DELETE relationship, p +``` + +Remover uma propriedade em um nó específico +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +REMOVE p.age +``` +*Prestar atenção à palavra chave `REMOVE`, não é `DELETE` !* + +Remover um label de um nó específico +``` +MATCH (p:Person) +WHERE p.name = "Théo Gauchoux" +DELETE p:Person +``` + +Excluir o banco de dados inteiro +``` +MATCH (n) +OPTIONAL MATCH (n)-[r]-() +DELETE n, r +``` +*Sério, é o `rm -rf /` do Cypher !* + + +Outras cláusulas úteis +--- + +`PROFILE` +Antes de uma consulta, mostre o plano de execução dela. + +`COUNT(e)` +Contar entidades (nós ou relacionamentos) que casam com **e**. + +`LIMIT x` +Limite o resultado aos primeiros x resultados. + + +Dicas Especiais +--- + +- Há apenas comentários de uma linha no Cypher, com barras duplas : // Comentários +- Você pode executar um script Cypher armazenado em um arquivo **.cql** diretamente no Neo4j (é uma importação). No entanto, você não pode ter várias instruções neste arquivo (separadas por **;**). +- Use o shell Neo4j para escrever Cypher, é realmente incrível. +- O Cypher será a linguagem de consulta padrão para todos os bancos de dados de gráficos (conhecidos como **OpenCypher**). -- cgit v1.2.3 From cb1ef05aa638d5e99e9956c215b79767bc02c1ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rog=C3=A9rio?= Date: Sun, 21 Oct 2018 20:35:57 -0300 Subject: [factor/pt-br] Add portuguese language for factor --- pt-br/factor-pt.html.markdown | 184 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 pt-br/factor-pt.html.markdown diff --git a/pt-br/factor-pt.html.markdown b/pt-br/factor-pt.html.markdown new file mode 100644 index 00000000..99e2b67f --- /dev/null +++ b/pt-br/factor-pt.html.markdown @@ -0,0 +1,184 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor + +lang: pt-br +--- + +Factor é uma linguagem moderna baseada em pilha, baseado em Forth, criada por Slava Pestov. + +Código neste arquivo pode ser digitado em Fator, mas não importado diretamente porque o cabeçalho de vocabulário e importação faria o início completamente confuso. + +``` +! Este é um comentário + +! Como Forth, toda a programação é feita manipulando a pilha. +! A indicação de um valor literal o coloca na pilha. +5 2 3 56 76 23 65 ! Nenhuma saída, mas a pilha é impressa no modo interativo + +! Esses números são adicionados à pilha, da esquerda para a direita. +! .s imprime a pilha de forma não destrutiva. +.s ! 5 2 3 56 76 23 65 + +! A aritmética funciona manipulando dados na pilha. +5 4 + ! Sem saída + +! `.` mostra o resultado superior da pilha e o imprime. +. ! 9 + +! Mais exemplos de aritmética: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! Várias palavras são fornecidas para manipular a pilha, coletivamente conhecidas como palavras embaralhadas. + +3 dup - ! duplica o primeiro item (1st agora igual a 2nd): 3 - 3 +2 5 swap / ! troca o primeiro com o segundo elemento: 5 / 2 +4 0 drop 2 / ! remove o primeiro item (não imprima na tela): 4 / 2 +1 2 3 nip .s ! remove o segundo item (semelhante a drop): 1 3 +1 2 clear .s ! acaba com toda a pilha +1 2 3 4 over .s ! duplica o segundo item para o topo: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplica o terceiro item para o topo: 1 2 3 4 2 3 + +! Criando Palavras +! O `:` conjuntos de palavras do Factor no modo de compilação até que ela veja a palavra `;`. +: square ( n -- n ) dup * ; ! Sem saída +5 square . ! 25 + +! Podemos ver o que as palavra fazem também. +! \ suprime a avaliação de uma palavra e coloca seu identificador na pilha. +\ square see ! : square ( n -- n ) dup * ; + +! Após o nome da palavra para criar, a declaração entre parênteses dá o efeito da pilha. +! Podemos usar os nomes que quisermos dentro da declaração: +: weirdsquare ( camel -- llama ) dup * ; + +! Contanto que sua contagem corresponda ao efeito da pilha da palavra: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Além disso Ok + +! Onde Factor difere do Forth é no uso de citações. +! Uma citação é um bloco de código que é colocado na pilha como um valor. +! [ inicia o modo de citação; ] termina. +[ 2 + ] ! A citação que adiciona 2 é deixada na pilha +4 swap call . ! 6 + +! E assim, palavras de ordem mais alta. TONS de palavras de ordem superior. +2 3 [ 2 + ] dip .s ! Retira valor do topo da pilha, execute citação, empurre de volta: 4 3 +3 4 [ + ] keep .s ! Copie o valor do topo da pilha, execute a citação, envie a cópia: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Executar cada citação no valor do topo, empurrar os dois resultados: 3 4 +4 3 1 [ + ] [ + ] bi .s ! As citações em um bi podem extrair valores mais profundos da pilha: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Executar a citação no primeiro e segundo valores +2 [ + ] curry ! Injeta o valor fornecido no início da citação: [ 2 + ] é deixado na pilha + +! Condicionais +! Qualquer valor é verdadeiro, exceto o valor interno f. +! m valor interno não existe, mas seu uso não é essencial. +! Condicionais são palavras de maior ordem, como com os combinadores acima. + +5 [ "Five is true" . ] when ! Cinco é verdadeiro +0 [ "Zero is true" . ] when ! Zero é verdadeiro +f [ "F is true" . ] when ! Sem saída +f [ "F is false" . ] unless ! F é falso +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two é verdadeiro + +! Por padrão, as condicionais consomem o valor em teste, mas variantes com asterisco +! deixe sozinho se é verdadeiro: + +5 [ . ] when* ! 5 +f [ . ] when* ! Nenhuma saída, pilha vazia, f é consumida porque é falsa + + +! Laços +! Você adivinhou .. estas são palavras de ordem mais elevada também. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Aqui está uma lista: +{ 2 4 6 8 } [ 1 + . ] each ! Exibe 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Sai { 3 5 7 9 } na pilha + +! Reduzir laços ou criar listas: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Mantém apenas membros da lista para os quais a citação é verdadeira: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Como "fold" em linguagens funcionais: exibe 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Como reduzir, mas mantém os valores intermediários em uma lista: exibe { 0 2 6 12 } então 20 +1 5 [ 2 * dup ] replicate . ! Repete a citação 5 vezes e coleta os resultados em uma lista: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Repete a segunda citação até que a primeira retorne como falsa e colete os resultados: { 2 4 8 16 32 64 128 } + +! Se tudo mais falhar, uma finalidade geral, enquanto repete: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Exibe "Hello" 10 vezes + ! Sim, é difícil de ler + ! Isso é o que todos esses loops variantes são para + +! Variáveis +! Normalmente, espera-se que os programas Factor mantenham todos os dados na pilha. +! Usar variáveis ​​nomeadas torna a refatoração mais difícil (e é chamada de Factor por um motivo) +! Variáveis ​​globais, se você precisar: + +SYMBOL: name ! Cria o nome como uma palavra identificadora +"Bob" name set-global ! Sem saída +name get-global . ! "Bob" + +! Variáveis ​​locais nomeadas são consideradas uma extensão, mas estão disponíveis +! Em uma citação .. +[| m n ! A citação captura os dois principais valores da pilha em m e n + | m n + ] ! Leia-os + +! Ou em uma palavra.. +:: lword ( -- ) ! Note os dois pontos duplos para invocar a extensão da variável lexica + 2 :> c ! Declara a variável imutável c para manter 2 + c . ; ! Imprima isso + +! Em uma palavra declarada dessa maneira, o lado de entrada da declaração de pilha +! torna-se significativo e fornece os valores das variáveis ​​em que os valores da pilha são capturados +:: double ( a -- result ) a 2 * ; + +! Variáveis ​​são declaradas mutáveis ​​ao terminar seu nome com um ponto de exclamação +:: mword2 ( a! -- x y ) ! Capture o topo da pilha na variável mutável a + a ! Empurrar a + a 2 * a! ! Multiplique por 2 e armazene o resultado em a + a ; ! Empurre novo valor de a +5 mword2 ! Pilha: 5 10 + +! Listas e Sequências +! Vimos acima como empurrar uma lista para a pilha + +0 { 1 2 3 4 } nth ! Acessar um membro específico de uma lista: 1 +10 { 1 2 3 4 } nth ! Error: índice de sequência fora dos limites +1 { 1 2 3 4 } ?nth ! O mesmo que nth se o índice estiver dentro dos limites: 2 +10 { 1 2 3 4 } ?nth ! Nenhum erro se estiver fora dos limites: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! E se você quiser obter meta, as citações são seqüências e podem ser desmontadas.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Pronto para mais? + +* [Documentação do Factor](http://docs.factorcode.org/content/article-help.home.html) -- cgit v1.2.3 From 129abf6113a48f928b5b8b47a54ff60184947cea Mon Sep 17 00:00:00 2001 From: Ankush Agarwal Date: Mon, 22 Oct 2018 08:44:21 -0700 Subject: Add comments about unordered_map and unordered_set --- c++.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index 8be5a278..f1ad0790 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1027,6 +1027,7 @@ for (it = my_vector.begin(); it != my_vector.end(); ++it) { // Set // Sets are containers that store unique elements following a specific order. +// For hash sets, use unordered_set. They are more effecient but do not preserve order. // Set is a very useful container to store unique values in sorted order // without any other functions or code. @@ -1061,6 +1062,7 @@ cout << ST.size(); // will print the size of set ST // Map // Maps store elements formed by a combination of a key value // and a mapped value, following a specific order. +// For hash maps, use unordered_map. They are more effecient but do not preserve order. #include map mymap; // Will initialize the map with key as char and value as int -- cgit v1.2.3 From 2e6208c754becae469c4056ac9ecdea40f490064 Mon Sep 17 00:00:00 2001 From: Ankush Agarwal Date: Mon, 22 Oct 2018 09:12:29 -0700 Subject: Update comments --- c++.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index f1ad0790..225472cb 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1027,7 +1027,6 @@ for (it = my_vector.begin(); it != my_vector.end(); ++it) { // Set // Sets are containers that store unique elements following a specific order. -// For hash sets, use unordered_set. They are more effecient but do not preserve order. // Set is a very useful container to store unique values in sorted order // without any other functions or code. @@ -1058,11 +1057,12 @@ cout << ST.size(); // will print the size of set ST // Output: 0 // NOTE: for duplicate elements we can use multiset +// NOTE: For hash sets, use unordered_set. They are more effecient but +// do not preserve order. unordered_set is available since C++11 // Map // Maps store elements formed by a combination of a key value // and a mapped value, following a specific order. -// For hash maps, use unordered_map. They are more effecient but do not preserve order. #include map mymap; // Will initialize the map with key as char and value as int @@ -1086,6 +1086,8 @@ cout << it->second; // Output: 26 +// NOTE: For hash maps, use unordered_map. They are more effecient but do +// not preserve order. unordered_map is available since C++11. /////////////////////////////////// // Logical and Bitwise operators -- cgit v1.2.3 From 00bb4b8a70f4ddd09ce4243e817fba2c489646da Mon Sep 17 00:00:00 2001 From: Ankush Agarwal Date: Mon, 22 Oct 2018 14:13:58 -0700 Subject: efficient typo fix --- c++.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 225472cb..4113d5f4 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1057,7 +1057,7 @@ cout << ST.size(); // will print the size of set ST // Output: 0 // NOTE: for duplicate elements we can use multiset -// NOTE: For hash sets, use unordered_set. They are more effecient but +// NOTE: For hash sets, use unordered_set. They are more efficient but // do not preserve order. unordered_set is available since C++11 // Map @@ -1086,7 +1086,7 @@ cout << it->second; // Output: 26 -// NOTE: For hash maps, use unordered_map. They are more effecient but do +// NOTE: For hash maps, use unordered_map. They are more efficient but do // not preserve order. unordered_map is available since C++11. /////////////////////////////////// -- cgit v1.2.3 From f7fb113ba5164883534e2a395435e889aff1b4ed Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Mon, 22 Oct 2018 23:49:15 +0200 Subject: [it/it] Add typescript-it.html.markdown --- it-it/typescript-it.html.markdown | 226 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 it-it/typescript-it.html.markdown diff --git a/it-it/typescript-it.html.markdown b/it-it/typescript-it.html.markdown new file mode 100644 index 00000000..5047de20 --- /dev/null +++ b/it-it/typescript-it.html.markdown @@ -0,0 +1,226 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Christian Grasso", "https://grasso.io"] +filename: learntypescript-it.ts +--- + +TypeScript è un linguaggio basato su JavaScript che punta a rendere il codice +più scalabile introducendo concetti quali le classi, i moduli, le interface, +e i generics. +Poichè TypeScript è un superset di JavaScript, è possibile sfruttare le sue +funzionalità anche in progetti esistenti: il codice JavaScript valido è anche +valido in TypeScript. Il compilatore di TypeScript genera codice JavaScript. + +Questo articolo si concentrerà solo sulle funzionalità aggiuntive di TypeScript. + +Per testare il compilatore, puoi utilizzare il +[Playground](http://www.typescriptlang.org/Playground), dove potrai scrivere +codice TypeScript e visualizzare l'output in JavaScript. + +```ts +// TypeScript ha tre tipi di base +let completato: boolean = false; +let righe: number = 42; +let nome: string = "Andrea"; + +// Il tipo può essere omesso se è presente un assegnamento a scalari/literal +let completato = false; +let righe = 42; +let nome = "Andrea"; + +// Il tipo "any" indica che la variabile può essere di qualsiasi tipo +let qualsiasi: any = 4; +qualsiasi = "oppure una stringa"; +qualsiasi = false; // o magari un boolean + +// Usa la keyword "const" per le costanti +const numeroViteGatti = 9; +numeroViteGatti = 1; // Errore + +// Per gli array, puoi usare l'apposito tipo o la versione con i generics +let lista: number[] = [1, 2, 3]; +let lista: Array = [1, 2, 3]; + +// Per le enumerazioni: +enum Colore { Rosso, Verde, Blu }; +let c: Colore = Colore.Verde; + +// Infine, "void" viene utilizzato per le funzioni che non restituiscono valori +function avviso(): void { + alert("Sono un piccolo avviso fastidioso!"); +} + +// Le funzioni supportano la sintassi "a freccia" (lambda) e supportano la type +// inference, cioè per scalari/literal non c'è bisogno di specificare il tipo + +// Tutte le seguenti funzioni sono equivalenti, e il compilatore genererà +// lo stesso codice JavaScript per ognuna di esse +let f1 = function (i: number): number { return i * i; } +// Type inference +let f2 = function (i: number) { return i * i; } +// Sintassi lambda +let f3 = (i: number): number => { return i * i; } +// Sintassi lambda + type inference +let f4 = (i: number) => { return i * i; } +// Sintassi lambda + type inference + sintassi abbreviata (senza return) +let f5 = (i: number) => i * i; + +// Le interfacce sono strutturali, e qualunque oggetto con le stesse proprietà +// di un'interfaccia è compatibile con essa +interface Persona { + nome: string; + // Proprietà opzionale, indicata con "?" + anni?: number; + // Funzioni + saluta(): void; +} + +// Oggetto che implementa l'interfaccia Persona +// È una Persona valida poichè implementa tutta le proprietà non opzionali +let p: Persona = { nome: "Bobby", saluta: () => { } }; +// Naturalmente può avere anche le proprietà opzionali: +let pValida: Persona = { nome: "Bobby", anni: 42, saluta: () => { } }; +// Questa invece NON è una Persona, poichè il tipo di "anni" è sbagliato +let pNonValida: Persona = { nome: "Bobby", anni: true }; + +// Le interfacce possono anche descrivere una funzione +interface SearchFunc { + (source: string, subString: string): boolean; +} +// I nomi dei parametri non sono rilevanti: vengono controllati solo i tipi +let ricerca: SearchFunc; +ricerca = function (src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classi - i membri sono pubblici di default +class Punto { + // Proprietà + x: number; + + // Costruttore - in questo caso la keyword "public" può generare in automatico + // il codice per l'inizializzazione di una variabile. + // In questo esempio, verrà creata la variabile y in modo identico alla x, ma + // con meno codice. Sono supportati anche i valori di default. + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funzioni + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membri statici + static origine = new Point(0, 0); +} + +// Le classi possono anche implementare esplicitamente delle interfacce. +// Il compilatore restituirà un errore nel caso in cui manchino delle proprietà. +class PersonaDiRiferimento implements Persona { + nome: string + saluta() {} +} + +let p1 = new Punto(10, 20); +let p2 = new Punto(25); // y = 0 + +// Inheritance +class Punto3D extends Punto { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // La chiamata esplicita a super è obbligatoria + } + + // Sovrascrittura + dist() { + let d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Moduli - "." può essere usato come separatore per i sottomoduli +module Geometria { + export class Quadrato { + constructor(public lato: number = 0) { } + + area() { + return Math.pow(this.lato, 2); + } + } +} + +let s1 = new Geometria.Quadrato(5); + +// Alias locale per un modulo +import G = Geometria; + +let s2 = new G.Quadrato(10); + +// Generics +// Classi +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfacce +interface Pair { + item1: T; + item2: T; +} + +// E funzioni +let pairToTuple = function (p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +let tuple = pairToTuple({ item1: "hello", item2: "world" }); + +// Interpolazione con le template string (definite con i backtick) +let nome = 'Tyrone'; +let saluto = `Ciao ${name}, come stai?` +// Possono anche estendersi su più righe +let multiriga = `Questo è un esempio +di stringa multiriga.`; + +// La keyword "readonly" rende un membro di sola lettura +interface Persona { + readonly nome: string; + readonly anni: number; +} + +var p1: Persona = { nome: "Tyrone", anni: 42 }; +p1.anni = 25; // Errore, p1.anni è readonly + +var p2 = { nome: "John", anni: 60 }; +var p3: Person = p2; // Ok, abbiamo creato una versione readonly di p2 +p3.anni = 35; // Errore, p3.anni è readonly +p2.anni = 45; // Compila, ma cambia anche p3.anni per via dell'aliasing! + +class Macchina { + readonly marca: string; + readonly modello: string; + readonly anno = 2018; + + constructor() { + // Possiamo anche assegnare nel constructor + this.marca = "Marca sconosciuta"; + this.modello = "Modello sconosciuto"; + } +} + +let numeri: Array = [0, 1, 2, 3, 4]; +let altriNumeri: ReadonlyArray = numbers; +altriNumeri[5] = 5; // Errore, gli elementi sono readonly +altriNumeri.push(5); // Errore, il metodo push non esiste (modifica l'array) +altriNumeri.length = 3; // Errore, length è readonly +numeri = altriNumeri; // Errore, i metodi di modifica non esistono +``` + +## Altre risorse + * [Sito ufficiale di TypeScript](http://www.typescriptlang.org/) + * [Specifica di TypeScript](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) + * [Anders Hejlsberg - Introducing TypeScript su Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [TypeScript su GitHub](https://github.com/Microsoft/TypeScript) + * [Definitely Typed - definizioni per le librerie](http://definitelytyped.org/) -- cgit v1.2.3 From 1970732479a296b3db1082ff07054f93819ffb67 Mon Sep 17 00:00:00 2001 From: Jade Thornton Date: Mon, 22 Oct 2018 20:59:56 -0500 Subject: update tcl/en hyperlinks --- tcl.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index f48d5271..3d23870b 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learntcl.tcl --- -Tcl was created by [John Ousterhout](https://wiki.tcl.tk/John%20Ousterout) as a +Tcl was created by [John Ousterhout](https://wiki.tcl-lang.org/page/John+Ousterhout) as a reusable scripting language for circuit design tools that he authored. In 1997 he was awarded the [ACM Software System Award](https://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl @@ -283,7 +283,7 @@ set c [expr {$a + $b}] # Since "expr" performs variable substitution on its own, brace the expression # to prevent Tcl from performing variable substitution first. See -# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. +# "https://wiki.tcl-lang.org/page/Brace+your+expr-essions" for details. # "expr" understands variable and script substitution: @@ -581,8 +581,8 @@ a ## Reference -[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) +[Official Tcl Documentation](https://www.tcl-lang.org) -[Tcl Wiki](http://wiki.tcl.tk) +[Tcl Wiki](https://wiki.tcl-lang.org) [Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From a516d9a37567881b448b1096616016bab2bec550 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Tue, 23 Oct 2018 22:35:48 +0200 Subject: [typescript/it] Add language spec line --- it-it/typescript-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/typescript-it.html.markdown b/it-it/typescript-it.html.markdown index 5047de20..b78705c5 100644 --- a/it-it/typescript-it.html.markdown +++ b/it-it/typescript-it.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Christian Grasso", "https://grasso.io"] filename: learntypescript-it.ts +lang: it-it --- TypeScript è un linguaggio basato su JavaScript che punta a rendere il codice -- cgit v1.2.3 From 757d37aa1c7b49465738ca669dc038f9fc2b95d4 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Tue, 23 Oct 2018 23:03:51 +0200 Subject: [pcre] Fix examples, closes #3226 --- pcre.html.markdown | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/pcre.html.markdown b/pcre.html.markdown index 0b61653d..3e877a35 100644 --- a/pcre.html.markdown +++ b/pcre.html.markdown @@ -63,20 +63,12 @@ We will test our examples on following string `66.249.64.13 - - [18/Sep/2004:11: | Regex | Result | Comment | | :---- | :-------------- | :------ | -| GET | GET | GET matches the characters GET literally (case sensitive) | -| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` match a digit [0-9] one or more times defined by `+` quantifier, `\.` matches `.` literally | -| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` is trying to match group (`\d+\.`) exactly three times. | -| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` matches any character (except newline), `.` is any character | -| ^\S+ | 66.249.64.13 | `^` means start of the line, `\S+` matches any number of non-space characters | -| \+[0-9]+ | +1000 | `\+` matches the character `+` literally. `[0-9]` character class means single number. Same can be achieved using `\+\d+` | - -All these examples can be tried at https://regex101.com/ - -1. Copy the example string in `TEST STRING` section -2. Copy regex code in `Regular Expression` section -3. The web application will show the matching result - +| `GET` | GET | GET matches the characters GET literally (case sensitive) | +| `\d+.\d+.\d+.\d+` | 66.249.64.13 | `\d+` match a digit [0-9] one or more times defined by `+` quantifier, `\.` matches `.` literally | +| `(\d+\.){3}\d+` | 66.249.64.13 | `(\d+\.){3}` is trying to match group (`\d+\.`) exactly three times. | +| `\[.+\]` | [18/Sep/2004:11:07:48 +1000] | `.+` matches any character (except newline), `.` is any character | +| `^\S+` | 66.249.64.13 | `^` means start of the line, `\S+` matches any number of non-space characters | +| `\+[0-9]+` | +1000 | `\+` matches the character `+` literally. `[0-9]` character class means single number. Same can be achieved using `\+\d+` | ## Further Reading - - +[Regex101](https://regex101.com/) - Regular Expression tester and debugger -- cgit v1.2.3 From f7d86067f1110e2db81dfd6194ff4ed52ab26fc3 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Tue, 23 Oct 2018 23:01:24 +0200 Subject: [pcre/it] Add pcre-it.html.markdown --- it-it/pcre-it.html.markdown | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 it-it/pcre-it.html.markdown diff --git a/it-it/pcre-it.html.markdown b/it-it/pcre-it.html.markdown new file mode 100644 index 00000000..68233858 --- /dev/null +++ b/it-it/pcre-it.html.markdown @@ -0,0 +1,80 @@ +--- +language: PCRE +filename: pcre-it.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +Un'espressione regolare (regex o regexp in breve) è una speciale stringa +utilizzata per definire un pattern, ad esempio per cercare una sequenza di +caratteri; ad esempio, `/^[a-z]+:/` può essere usato per estrarre `http:` +dall'URL `http://github.com/`. + +PCRE (Perl Compatible Regular Expressions) è una libreria per i regex in C. +La sintassi utilizzata per le espressioni è molto simile a quella di Perl, da +cui il nome. Si tratta di una delle sintassi più diffuse per la scrittura di +regex. + +Esistono due tipi di metacaratteri (caratteri con una funzione speciale): +* Caratteri riconosciuti ovunque tranne che nelle parentesi quadre +``` + \ carattere di escape + ^ cerca all'inizio della stringa (o della riga, in modalità multiline) + $ cerca alla fine della stringa (o della riga, in modalità multiline) + . qualsiasi carattere eccetto le newline + [ inizio classe di caratteri + | separatore condizioni alternative + ( inizio subpattern + ) fine subpattern + ? quantificatore "0 o 1" + * quantificatore "0 o più" + + quantificatore "1 o più" + { inizio quantificatore numerico +``` + +* Caratteri riconosciuti nelle parentesi quadre +``` + \ carattere di escape + ^ nega la classe se è il primo carattere + - indica una serie di caratteri + [ classe caratteri POSIX (se seguita dalla sintassi POSIX) + ] termina la classe caratteri + +``` + +PCRE fornisce inoltre delle classi di caratteri predefinite: +``` + \d cifra decimale + \D NON cifra decimale + \h spazio vuoto orizzontale + \H NON spazio vuoto orizzontale + \s spazio + \S NON spazio + \v spazio vuoto verticale + \V NON spazio vuoto verticale + \w parola + \W "NON parola" +``` + +## Esempi + +Utilizzeremo la seguente stringa per i nostri test: +``` +66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1" +``` +Si tratta di una riga di log del web server Apache. + +| Regex | Risultato | Commento | +| :---- | :-------------- | :------ | +| `GET` | GET | Cerca esattamente la stringa "GET" (case sensitive) | +| `\d+.\d+.\d+.\d+` | 66.249.64.13 | `\d+` identifica uno o più (quantificatore `+`) numeri [0-9], `\.` identifica il carattere `.` | +| `(\d+\.){3}\d+` | 66.249.64.13 | `(\d+\.){3}` cerca il gruppo (`\d+\.`) esattamente 3 volte. | +| `\[.+\]` | [18/Sep/2004:11:07:48 +1000] | `.+` identifica qualsiasi carattere, eccetto le newline; `.` indica un carattere qualsiasi | +| `^\S+` | 66.249.64.13 | `^` cerca all'inizio della stringa, `\S+` identifica la prima stringa di caratteri diversi dallo spazio | +| `\+[0-9]+` | +1000 | `\+` identifica il carattere `+`. `[0-9]` indica una cifra da 0 a 9. L'espressione è equivalente a `\+\d+` | + +## Altre risorse +[Regex101](https://regex101.com/) - tester per le espressioni regolari -- cgit v1.2.3 From 868b22058fe14b270c55116d8a5943c2d708415b Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 23 Oct 2018 20:36:28 -0700 Subject: Factor highlight is here --- factor.html.markdown | 2 +- pt-br/factor-pt.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/factor.html.markdown b/factor.html.markdown index 79596d83..53c692df 100644 --- a/factor.html.markdown +++ b/factor.html.markdown @@ -9,7 +9,7 @@ Factor is a modern stack-based language, based on Forth, created by Slava Pestov Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. -``` +```factor ! This is a comment ! Like Forth, all programming is done by manipulating the stack. diff --git a/pt-br/factor-pt.html.markdown b/pt-br/factor-pt.html.markdown index 99e2b67f..e3c8f4a9 100644 --- a/pt-br/factor-pt.html.markdown +++ b/pt-br/factor-pt.html.markdown @@ -11,7 +11,7 @@ Factor é uma linguagem moderna baseada em pilha, baseado em Forth, criada por S Código neste arquivo pode ser digitado em Fator, mas não importado diretamente porque o cabeçalho de vocabulário e importação faria o início completamente confuso. -``` +```factor ! Este é um comentário ! Como Forth, toda a programação é feita manipulando a pilha. -- cgit v1.2.3 From d0b9b1427d0e957a06f01f4e770aa90831ce9c74 Mon Sep 17 00:00:00 2001 From: vsraptor Date: Wed, 24 Oct 2018 13:04:34 -0400 Subject: Add LogTalk tutorial in Bulgarian --- bg-bg/logtalk-bg.html.markdown | 592 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 592 insertions(+) create mode 100644 bg-bg/logtalk-bg.html.markdown diff --git a/bg-bg/logtalk-bg.html.markdown b/bg-bg/logtalk-bg.html.markdown new file mode 100644 index 00000000..8ff9d7a1 --- /dev/null +++ b/bg-bg/logtalk-bg.html.markdown @@ -0,0 +1,592 @@ +--- +language: Logtalk +contributors: + - ["Paulo Moura", "http://github.com/pmoura"] +translators: + - ["vsraptor", "https://github.com/vsraptor"] +lang: bg-bg + +--- + +Logtalk е обектно-ориентиран (ОО) модерен логически език за програмиране, които разширява Prolog с възможности за капсулиране (еncapsulation) и многократно използване на кода без да компрометира декларативните възможности на езика. Logtalk е имплементиран така че да може да бъде адапртиран към всеки стандартен Prolog като back-end компилатор, тоест е напълно прозрачен за нормална Prolog програма. +Допълнително, Logtalk също може да интерпретира Prolog модули, като Logtalk обекти. + +Основната структурна единица за изграждане на програмни със Logtalk е чрез използване на обекти. +Logtalk поддържа както стандартния начин за изграждане на иерархий от класове познати ни от езици като Java, същто така и prototype-OOP познат ни от езици като JavaScript. +Запомнете че всичко стартира с дефинирането и създаването на обект. + + +## Syntax (Синтакс) + + +Logtalk използва стандартен Prolog синтакс, с минимум допълнителни оператори и директиви. +Важно последствие от това е че кода лесно се капсулира с много малко промени спрямо оригинален код. + +Операторите които Logtalk добавя към Prolog са : + + ::/2 - изпраща саобщение до обект (аналогично на метод в стандартните ООП езици) + ::/1 - изпраща саобщение до себе си (self) (тоест до обекта който е получил съобщението което обработваме в момента) + ^^/1 - super call (изпраща саобщение до наследен или импортиран предикат(predicate)) + + +## Entities and roles (Субекти и роли) + + +Logtalk предоставя обекти, портоколи и категории като първокласни-субекти (first-class entities). Връзката между тях описва ролята която субектите изпалняват. +Обектите могат да играят различни роли в зависимост от как ги дефинираме тоест какви директиви използваме при дефиницията. + +Например когато използваме обект А за да създадем нов обект Б, обект Б играе ролята на "инстанция", а обект А играе ролята на клас. +Ако използваме "extends"-дефиниция единия от обектите играе ролята на протоип(prototype) за другия. + + +## Defining an object (Дефиниране на обект) + + +Чрез дефинирането на обект ние капсулираме дефиницията на "предикатите". +Обекти могат да се създадат динамично или дефинират статично във код-файла. +Ето как дефинираме примерен обект : + +```logtalk +:- object(list). + + :- public(member/2). + member(Head, [Head| _]). + member(Head, [_| Tail]) :- + member(Head, Tail). + +:- end_object. +``` + +## Compiling source files (Компилиран) + + +Ако предположим че кода е записан във файл с име list.lgt, можем да го компилираме чрез logtalk_load/1 предиката или съкратения вариант {}/1. + + +```logtalk +?- {list}. +yes +``` + +## Sending a message to an object (Изпращане на събщение до обект) + + +Както казахме ::/2 infix оператор се използва за изпращане на съобщение до обекта. Както в Prolog, ние можем да backtrack-нем за алтернативни решения, понеже метода е просто стандартен предикат : + +```logtalk +?- list::member(X, [1,2,3]). +X = 1 ; +X = 2 ; +X = 3 +yes + +?- write_canonical(list::member(X, [1,2,3])). +::(list,member(_,[1,2,3])) +``` + +Кагато декларирме обект автоматично предикатите са капсулирани (еncapsulation), тоест извън обекта те са невидими за останалата част от програмата. Естествено има опции да променим това поведение чрез public, protected, или private предикати. + +```logtalk +:- object(scopes). + + :- private(bar/0). + bar. + + local. + +:- end_object. +``` + +Ако кода е записан в scopes.lgt фаил и се опитаме да изпратим саобщтение до частен(private) или локален предикат ще получим грешка: + +```logtalk +?- {scopes}. +yes + +?- catch(scopes::bar, Error, true). +Error = error( + permission_error(access, private_predicate, bar/0), + logtalk(scopes::bar, user) +) +yes + +?- catch(scopes::local, Error, true). +Error = error( + existence_error(predicate_declaration, local/0), + logtalk(scopes::local, user) +) +yes +``` + +Когато предиката е непознат за обекта това също генерира грешка. Например : + +```logtalk +?- catch(scopes::unknown, Error, true). +Error = error( + existence_error(predicate_declaration, unknown/0), + logtalk(scopes::unknown, user) +) +yes +``` + +## Протоколи (Defining and implementing a protocol) + + +За тези от вас свикнали със стандартно ООП, Protocols наподобяват Interfaces в Java. +Протоколите съдържат предикати които могат да бъдат в последствие имплементирани в обекти и категории : + +```logtalk +:- protocol(listp). + + :- public(member/2). + +:- end_protocol. + +:- object(list, + implements(listp)). + + member(Head, [Head| _]). + member(Head, [_| Tail]) :- + member(Head, Tail). + +:- end_object. +``` + +Обхвата(scope) на предикатите в протокола могат да бъде ограничени чрез protected или private клаузи. +Например: + +```logtalk +:- object(stack, + implements(private::listp)). + +:- end_object. +``` + +Всички субекти(entity) релации могат да бъдат пре-дефинирани с public, protected или private, подбно на начина показан по горе. + + +## Прототипи (Prototypes) + + +Всеки обект без instantiation или specialization спецификация с друг обект, играе ролята на прототип. +Прототип-обект може да предефинира и разщири протоипа-родител. + +```logtalk +% clyde, our prototypical elephant +:- object(clyde). + + :- public(color/1). + color(grey). + + :- public(number_of_legs/1). + number_of_legs(4). + +:- end_object. + +% fred, another elephant, is like clyde, except that he's white +:- object(fred, + extends(clyde)). + + color(white). + +:- end_object. +``` + +Когато системата отговаря на съобщение изпратено до обект който играе ролята на прототип, тя търси отговор първо в прототипа и ако не намери предикат делегира отговора на прототипа-родител-обект : + +```logtalk +?- fred::number_of_legs(N). +N = 4 +yes + +?- fred::color(C). +C = white +yes +``` + +Съобщението е валидно но няма да генерира грещка, ако предиката е дефиниран но не е деклариран/имплементиран. Това е така наречения closed-world assumption. +Например : + +```logtalk +:- object(foo). + + :- public(bar/0). + +:- end_object. +``` + +Ако заредим файла и се опитаме да извикаме bar/0, няма да получим отговор, както може да очакваме. Ако обаче предиката не е дори дефиниран, ще получим гращка : + +```logtalk +?- {foo}. +yes + +?- foo::bar. +no + +?- catch(foo::baz, Error, true). +Error = error( + existence_error(predicate_declaration, baz/0), + logtalk(foo::baz, user) +) +yes +``` + +## Класове и инстанции (Classes and instances) + + +За да саздадем обекти които играят ролята на класове и/или инстанции, трябва да използваме поне instantiation или specialization дефиниция с друг обект. Обектите които играят роля на мета-класове могат да се използват ако е нужно още за саздаване на инстанции на класа. +Следващия пример ще илюстрира как можем динамично да саздадаваме обекти : + +```logtalk +% a simple, generic, metaclass defining a new/2 predicate for its instances +:- object(metaclass, + instantiates(metaclass)). + + :- public(new/2). + new(Instance, Clauses) :- + self(Class), + create_object(Instance, [instantiates(Class)], [], Clauses). + +:- end_object. + +% a simple class defining age/1 and name/1 predicate for its instances +:- object(person, + instantiates(metaclass)). + + :- public([ + age/1, name/1 + ]). + + % a default value for age/1 + age(42). + +:- end_object. + +% a static instance of the class person +:- object(john, + instantiates(person)). + + name(john). + age(12). + +:- end_object. +``` + +Когато отговаряме на съобщение изпратено до обект който играе ролята на инстанция, системата валидира съобщението първо в текущия клас, след това класа-родител ако е необходимо. Ако съобщението е валидно тогава проверяваме инстанцията : + +```logtalk +?- person::new(Instance, [name(paulo)]). +Instance = o1 +yes + +?- o1::name(Name). +Name = paulo +yes + +?- o1::age(Age). +Age = 42 +yes + +?- john::age(Age). +Age = 12 +yes +``` + +## Категории (Categories) + + +Категорията е капсулран код който може да се рециклира (reuse) в различни обекти. Докато Протокола е само дефиниции Категорията е сащо и декларация/имплементация на предикатите които сме дефинирали. +В следващия пример ще дефинираме категории представящи автомобилни двигатели след което ще ги импортираме в автомобил-обекти : + + +```logtalk +% a protocol describing engine characteristics +:- protocol(carenginep). + + :- public([ + reference/1, + capacity/1, + cylinders/1, + horsepower_rpm/2, + bore_stroke/2, + fuel/1 + ]). + +:- end_protocol. + +% a typical engine defined as a category +:- category(classic, + implements(carenginep)). + + reference('M180.940'). + capacity(2195). + cylinders(6). + horsepower_rpm(94, 4800). + bore_stroke(80, 72.8). + fuel(gasoline). + +:- end_category. + +% a souped up version of the previous engine +:- category(sport, + extends(classic)). + + reference('M180.941'). + horsepower_rpm(HP, RPM) :- + ^^horsepower_rpm(ClassicHP, ClassicRPM), % "super" call + HP is truncate(ClassicHP*1.23), + RPM is truncate(ClassicRPM*0.762). + +:- end_category. + +% with engines (and other components), we may start "assembling" some cars +:- object(sedan, + imports(classic)). + +:- end_object. + +:- object(coupe, + imports(sport)). + +:- end_object. +``` + +Категориите се компилират отделно и разрешават импортираните обекти да бъдат обновени като просто обновим категориите без да е необходимо да прекомпилираме обекта: + +```logtalk +?- sedan::current_predicate(Predicate). +Predicate = reference/1 ; +Predicate = capacity/1 ; +Predicate = cylinders/1 ; +Predicate = horsepower_rpm/2 ; +Predicate = bore_stroke/2 ; +Predicate = fuel/1 +yes +``` + +## Hot patching + + +Категориите още могат да се използват за промяна на обекти "в движение", след като вече са били инстанциирани. +Например : + +```logtalk +:- object(buggy). + + :- public(p/0). + p :- write(foo). + +:- end_object. +``` + +Да предположим че обекта изпечатва грешното съобщение p/0 : + +```logtalk +?- {buggy}. +yes + +?- buggy::p. +foo +yes +``` + +Ако кода който описва този обект не е наличен и трябва да коригираме приложението, ние можем просто да създадем категория която да коригира необходимия предикат : + +```logtalk +:- category(patch, + complements(buggy)). + + % fixed p/0 def + p :- write(bar). + +:- end_category. +``` + +След компилиране и зареждане на категорията ще получим : + +```logtalk +?- {patch}. +yes + +?- buggy::p. +bar +yes +``` + + +## Parametric objects and categories + + +Обектите и категориите могат да се параметризират ако използваме за индентификатор комплексен-термин вместо атом. +Параметрите са логически променливи достъпни за всички капсулирани предикати. +Пример с геометрични кръгове : + +```logtalk +:- object(circle(_Radius, _Color)). + + :- public([ + area/1, perimeter/1 + ]). + + area(Area) :- + parameter(1, Radius), + Area is pi*Radius*Radius. + + perimeter(Perimeter) :- + parameter(1, Radius), + Perimeter is 2*pi*Radius. + +:- end_object. +``` + +Параметричните-обекти се използват като всеки друг обект, обикновенно осигуряваики стойности за параметрите когато изпращаме съобщение. + +```logtalk +?- circle(1.23, blue)::area(Area). +Area = 4.75291 +yes +``` + +Параметричните-обекти още осигуряват лесен начин за ассоцииране на различни предикати със нормални Prolog предикати. +Prolog факти могат да бъдат интерпретирани като посредници (proxies). +Например следните клаузи на circle/2 предикат : + + +```logtalk +circle(1.23, blue). +circle(3.71, yellow). +circle(0.39, green). +circle(5.74, black). +circle(8.32, cyan). +``` + +можем лесно да изчислим площа на всички кръгове : + +```logtalk +?- findall(Area, {circle(_, _)}::area(Area), Areas). +Areas = [4.75291, 43.2412, 0.477836, 103.508, 217.468] +yes +``` + +{Goal}::Message формата доказва(proves) Goal и изпраща съобщение до генерирания термин. + + +## Събития и мониторинг (Events and monitors) + + +Logtalk поддържа event-driven програмиране чрез дефинирането на събития и монитори за тези събития. +Събитие е просто изпращане на съобщение към обект. При обработването на съобщение системата разпознава before-събитие и after-събитие. +Мониторите дефинират предикати които ще прихаванат тези събития (before/3 и after/3). +Нампример следния монитор ще прихаване съобщенията изпратени чрез ::/2 : + +```logtalk +:- object(tracer, + implements(monitoring)). % built-in protocol for event handlers + + :- initialization(define_events(_, _, _, _, tracer)). + + before(Object, Message, Sender) :- + write('call: '), writeq(Object), write(' <-- '), writeq(Message), + write(' from '), writeq(Sender), nl. + + after(Object, Message, Sender) :- + write('exit: '), writeq(Object), write(' <-- '), writeq(Message), + write(' from '), writeq(Sender), nl. + +:- end_object. +``` + +Ето как можем да проследим реакцията на изпращане на съобщение : + +```logtalk +?- list::member(X, [1,2,3]). + +call: list <-- member(X, [1,2,3]) from user +exit: list <-- member(1, [1,2,3]) from user +X = 1 ; +exit: list <-- member(2, [1,2,3]) from user +X = 2 ; +exit: list <-- member(3, [1,2,3]) from user +X = 3 +yes +``` + +Събития могат да се изтрият динамично чрез define_events/5 и abolish_events/5 предикати. + + +## Lambda expressions + + +Logtalk поддържа lambda expressions. Lambda параметрите се предават чрез списък към (>>)/2 infix оператор свързвайки ги с lambda. +Ето няколко примера : + +```logtalk +?- {library(metapredicates_loader)}. +yes + +?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys). +Ys = [2,4,6] +yes +``` + +Currying се поддържа : + +```logtalk +?- meta::map([X]>>([Y]>>(Y is 2*X)), [1,2,3], Ys). +Ys = [2,4,6] +yes +``` + +Lambda free variables can be expressed using the extended syntax {Free1, ...}/[Parameter1, ...]>>Lambda. + + +## Макроси (Macros) + + +Термини и Цели могат да бъдат пре-интерпретирани (expanded) по време на компилация ако специфицираме hook-обект който дефинира прецедурите на пре-интерпретиране. +Нека следният обект е записан във фаил source.lgt : + +```logtalk +:- object(source). + + :- public(bar/1). + bar(X) :- foo(X). + + foo(a). foo(b). foo(c). + +:- end_object. +``` + +и следния hooк-обект е записан в my_macros.lgt, който пре-интерпретира foo/1 предиката : + +```logtalk +:- object(my_macros, + implements(expanding)). % built-in protocol for expanding predicates + + term_expansion(foo(Char), baz(Code)) :- + char_code(Char, Code). % standard built-in predicate + + goal_expansion(foo(X), baz(X)). + +:- end_object. +``` + +След зареждането на файла с макроси ние можем да пре-интерпретираме ползайки hook-флаг за компилатора : + +```logtalk +?- logtalk_load(my_macros), logtalk_load(source, [hook(my_macros)]). +yes + +?- source::bar(X). +X = 97 ; +X = 98 ; +X = 99 +true +``` + +## Допълнителна информация (Further information) + + +Посетете сайта на [Logtalk website](http://logtalk.org) за повече информация. + -- cgit v1.2.3 From bd1eaee9fdd5addb901f3809e1df2a13055fb05c Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 24 Oct 2018 22:42:04 +0530 Subject: Fix frontmatter --- bg-bg/logtalk-bg.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/bg-bg/logtalk-bg.html.markdown b/bg-bg/logtalk-bg.html.markdown index 8ff9d7a1..e788b17d 100644 --- a/bg-bg/logtalk-bg.html.markdown +++ b/bg-bg/logtalk-bg.html.markdown @@ -1,5 +1,6 @@ --- language: Logtalk +filename: llearnlogtalk-bg.lgt contributors: - ["Paulo Moura", "http://github.com/pmoura"] translators: -- cgit v1.2.3 From 4268b506c84887a332f5389723472be360e6385a Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Wed, 24 Oct 2018 22:06:22 +0200 Subject: Fix separation of paragraphs, spacing after etc. and LaTeX commands. Also use LaTeX's \emph instead of TeX's \em command --- latex.html.markdown | 58 +++++++++++++++++++++++++++++------------------------ 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/latex.html.markdown b/latex.html.markdown index 253c8139..874efeeb 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] - ["Svetlana Golubeva", "https://attillax.github.io/"] + - ["Oliver Kopp", "http://orcid.org/0000-0001-6962-4290"] filename: learn-latex.tex --- @@ -38,7 +39,7 @@ filename: learn-latex.tex \author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\ Svetlana Golubeva} \date{\today} -\title{Learn \LaTeX \hspace{1pt} in Y Minutes!} +\title{Learn \LaTeX{} in Y Minutes!} % Now we're ready to begin the document % Everything before this line is called "The Preamble" @@ -61,7 +62,7 @@ Svetlana Golubeva} % but before the main sections of the body. % This command is available in the document classes article and report. \begin{abstract} - \LaTeX \hspace{1pt} documentation written as \LaTeX! How novel and totally not + \LaTeX{} documentation written as \LaTeX! How novel and totally not my idea! \end{abstract} @@ -74,7 +75,7 @@ Hello, my name is Colton and together we're going to explore \LaTeX! This is the text for another section. I think it needs a subsection. \subsection{This is a subsection} % Subsections are also intuitive. -I think we need another one +I think we need another one. \subsubsection{Pythagoras} Much better now. @@ -87,10 +88,15 @@ However not all sections have to be numbered! \section{Some Text notes} %\section{Spacing} % Need to add more information about space intervals -\LaTeX \hspace{1pt} is generally pretty good about placing text where it should +\LaTeX{} is generally pretty good about placing text where it should go. If -a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash -\hspace{1pt} to the source code. \\ +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash{} +to the source code. + +Separate paragraphs by empty lines. + +You need to add a dot after abbreviations (if not followed by a comma), because otherwise the spacing after the dot is too large: +E.g., i.e., etc.\ are are such abbreviations. \section{Lists} Lists are one of the easiest things to create in \LaTeX! I need to go shopping @@ -109,15 +115,15 @@ tomorrow, so let's make a grocery list. \section{Math} -One of the primary uses for \LaTeX \hspace{1pt} is to produce academic articles +One of the primary uses for \LaTeX{} is to produce academic articles or technical papers. Usually in the realm of math and science. As such, -we need to be able to add special symbols to our paper! \\ +we need to be able to add special symbols to our paper! Math has many symbols, far beyond what you can find on a keyboard; -Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ +Set and relation symbols, arrows, operators, and Greek letters to name a few. Sets and relations play a vital role in many mathematical research papers. -Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ +Here's how you state all x that belong to X, $\forall$ x $\in$ X. % Notice how I needed to add $ signs before and after the symbols. This is % because when writing, we are in text-mode. % However, the math symbols only exist in math-mode. @@ -128,16 +134,16 @@ Here's how you state all x that belong to X, $\forall$ x $\in$ X. \\ \[a^2 + b^2 = c^2 \] My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. -I haven't found a Greek letter yet that \LaTeX \hspace{1pt} doesn't know -about! \\ +I haven't found a Greek letter yet that \LaTeX{} doesn't know +about! Operators are essential parts of a mathematical document: trigonometric functions ($\sin$, $\cos$, $\tan$), logarithms and exponentials ($\log$, $\exp$), -limits ($\lim$), etc. +limits ($\lim$), etc.\ have per-defined LaTeX commands. Let's write an equation to see how it's done: -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ Fractions (Numerator-denominators) can be written in these forms: @@ -146,7 +152,7 @@ $$ ^{10}/_{7} $$ % Relatively complex fractions can be written as % \frac{numerator}{denominator} -$$ \frac{n!}{k!(n - k)!} $$ \\ +$$ \frac{n!}{k!(n - k)!} $$ We can also insert equations in an ``equation environment''. @@ -174,7 +180,7 @@ Summations and Integrals are written with sum and int commands: \section{Figures} -Let's insert a Figure. Figure placement can get a little tricky. +Let's insert a figure. Figure placement can get a little tricky. I definitely have to lookup the placement options each time. \begin{figure}[H] % H here denoted the placement option. @@ -201,9 +207,9 @@ We can also insert Tables in the same way as figures. \end{tabular} \end{table} -\section{Getting \LaTeX \hspace{1pt} to not compile something (i.e. Source Code)} -Let's say we want to include some code into our \LaTeX \hspace{1pt} document, -we would then need \LaTeX \hspace{1pt} to not try and interpret that text and +\section{Getting \LaTeX{} to not compile something (i.e.\ Source Code)} +Let's say we want to include some code into our \LaTeX{} document, +we would then need \LaTeX{} to not try and interpret that text and instead just print it to the document. We do this with a verbatim environment. @@ -218,9 +224,10 @@ environment. \section{Compiling} By now you're probably wondering how to compile this fabulous document -and look at the glorious glory that is a \LaTeX \hspace{1pt} pdf. -(yes, this document actually does compile). \\ -Getting to the final document using \LaTeX \hspace{1pt} consists of the following +and look at the glorious glory that is a \LaTeX{} pdf. +(yes, this document actually does compile). + +Getting to the final document using \LaTeX{} consists of the following steps: \begin{enumerate} \item Write the document in plain text (the ``source code''). @@ -231,7 +238,7 @@ steps: \end{verbatim} \end{enumerate} -A number of \LaTeX \hspace{1pt}editors combine both Step 1 and Step 2 in the +A number of \LaTeX{} editors combine both Step 1 and Step 2 in the same piece of software. So, you get to see Step 1, but not Step 2 completely. Step 2 is still happening behind the scenes\footnote{In cases, where you use references (like Eqn.~\ref{eq:pythagoras}), you may need to run Step 2 @@ -267,9 +274,8 @@ That's all for now! \begin{thebibliography}{1} % similar to other lists, the \bibitem command can be used to list items % each entry can then be cited directly in the body of the text - \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em -https://en.wikibooks.org/wiki/LaTeX} - \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} + \bibitem{latexwiki} The amazing \LaTeX{} wikibook: \emph{https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} An actual tutorial: \emph{http://www.latex-tutorial.com} \end{thebibliography} % end the document -- cgit v1.2.3 From 30cdf4b25327e01c751db384e42692fd95178db1 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 26 Oct 2018 02:35:15 +0530 Subject: Fix tuple unpacking example in python3, closes #3130 (#3328) --- python3.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 7683bc60..c7fbf342 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -281,7 +281,8 @@ a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # You can also do extended unpacking a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 # Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 +d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f +# respectively such that d = 4, e = 5 and f = 6 # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 -- cgit v1.2.3 From dba905ffd2929ac78509d019bc8b609699ee11cb Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 26 Oct 2018 03:25:48 +0530 Subject: Fix YAML, closes #3172 (#3329) * Fix yamllint errors * Fix link --- yaml.html.markdown | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 52658453..ab0f9d55 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -14,6 +14,8 @@ significant newlines and indentation, like Python. Unlike Python, however, YAML doesn't allow literal tab characters for indentation. ```yaml +--- # document start + # Comments in YAML look like this. ################ @@ -83,22 +85,22 @@ a_nested_map: # An example ? - Manchester United - Real Madrid -: [ 2001-01-01, 2002-02-02 ] +: [2001-01-01, 2002-02-02] # Sequences (equivalent to lists or arrays) look like this # (note that the '-' counts as indentation): a_sequence: -- Item 1 -- Item 2 -- 0.5 # sequences can contain disparate types. -- Item 4 -- key: value - another_key: another_value -- - - This is a sequence - - inside another sequence -- - - Nested sequence indicators - - can be collapsed + - Item 1 + - Item 2 + - 0.5 # sequences can contain disparate types. + - Item 4 + - key: value + another_key: another_value + - + - This is a sequence + - inside another sequence + - - - Nested sequence indicators + - can be collapsed # Since YAML is a superset of JSON, you can also write JSON-style maps and # sequences: @@ -170,9 +172,11 @@ set2: item1: null item2: null item3: null + +... # document end ``` ### More Resources + [YAML official website](http://yaml.org/) -+ [Online YAML Validator](http://codebeautify.org/yaml-validator) ++ [Online YAML Validator](http://www.yamllint.com/) -- cgit v1.2.3 From b3d01a51a86ef38e613d464d1e328502e8e728c7 Mon Sep 17 00:00:00 2001 From: Saurabh Sandav Date: Sat, 27 Oct 2018 11:24:10 +0530 Subject: Update link to run Kotlin in the browser --- kotlin.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 6ff7c1dc..81242bac 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -448,5 +448,5 @@ fun testOperator() { ### Further Reading * [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/) -* [Try Kotlin in your browser](http://try.kotlinlang.org/) +* [Try Kotlin in your browser](https://play.kotlinlang.org/) * [A list of Kotlin resources](http://kotlin.link/) -- cgit v1.2.3 From ec1111c156c7420a12c5967bbd659eb61582b9cb Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 16:08:16 +0530 Subject: Fix formatting --- smalltalk.html.markdown | 55 +++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index a253df55..57e558b2 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -11,22 +11,22 @@ contributors: Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`. - -##Allowable characters: +## Allowable characters: - a-z - A-Z - 0-9 - .+/\*~<>@%|&? - blank, tab, cr, ff, lf -##Variables: +## Variables: - variables must be declared before use - shared vars must begin with uppercase - local vars must begin with lowercase - reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk` -##Variable scope: -- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` +## Variable scope: +- Global: defined in Dictionary Smalltalk and accessible by all objects in system +- Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` - Method Temporary: local to a method - Block Temporary: local to a block - Pool: variables in a Dictionary object @@ -54,7 +54,7 @@ Transcript cr. "carriage return / l Transcript endEntry. "flush the output buffer" ``` -##Assignment: +## Assignment: ``` | x y | x _ 4. "assignment (Squeak) <-" @@ -73,7 +73,7 @@ y := x deepCopy. "copy object and ins y := x veryDeepCopy. "complete tree copy using a dictionary" ``` -##Constants: +## Constants: ``` | b | b := true. "true constant" @@ -91,7 +91,6 @@ x := $ . "character constant x := #aSymbol. "symbol constants" x := #(3 2 1). "array constants" x := #('abc' 2 $a). "mixing of types allowed" - ``` ## Booleans: @@ -130,7 +129,6 @@ b := x isFloat. "test if object is f b := x isNumber. "test if object is number" b := $A isUppercase. "test if upper case character" b := $A isLowercase. "test if lower case character" - ``` ## Arithmetic expressions: @@ -188,7 +186,6 @@ x := Float infinity. "infinity" x := Float nan. "not-a-number" x := Random new next; yourself. x next. "random number stream (0.0 to 1.0)" x := 100 atRandom. "quick random number" - ``` ##Bitwise Manipulation: @@ -205,7 +202,6 @@ x := 16r80 highbit. "position of highest b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver" b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" - ``` ## Conversion: @@ -221,7 +217,6 @@ x := 3.99 storeString. "convert object to s x := 15 radix: 16. "convert to string in given base" x := 15 printStringBase: 16. x := 15 storeStringBase: 16. - ``` ## Blocks: @@ -245,7 +240,8 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu ## Method calls: - unary methods are messages with no arguments - binary methods -- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance) +- keyword methods are messages with selectors including colons standard categories/protocols: +- initialize-release (methods called for new instance) - accessing (get/set methods) - testing (boolean tests - is) - comparing (boolean tests with parameter @@ -254,6 +250,7 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu - updating (receive notification of changes) - private (methods private to class) - instance-creation (class methods for creating instance) + ``` | x | x := 2 sqrt. "unary message" @@ -268,7 +265,7 @@ Transcript "Cascading - send mu x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" ``` -##Conditional Statements: +## Conditional Statements: ``` | x | x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" @@ -330,7 +327,6 @@ y := x asciiValue. "convert to numeric y := x asString. "convert to string" b := $A <= $B. "comparison" y := $A max: $B. - ``` ## Symbol: @@ -428,7 +424,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -##OrderedCollection: acts like an expandable array +## OrderedCollection: acts like an expandable array ``` | b x y sum max | x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -471,7 +467,9 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## SortedCollection: like OrderedCollection except order of elements determined by sorting criteria +## SortedCollection: +like OrderedCollection except order of elements determined by sorting criteria + ``` | b x y sum max | x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -513,7 +511,9 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Bag: like OrderedCollection except elements are in no particular order +## Bag: +like OrderedCollection except elements are in no particular order + ``` | b x y sum max | x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -544,8 +544,12 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Set: like Bag except duplicates not allowed -## IdentitySet: uses identity test (== rather than =) +## Set: +like Bag except duplicates not allowed + +## IdentitySet: +uses identity test (== rather than =) + ``` | b x y sum max | x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -604,7 +608,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -##Associations: +## Associations: ``` | x y | x := #myVar->'hello'. @@ -613,7 +617,9 @@ y := x value. ``` ## Dictionary: -## IdentityDictionary: uses identity test (== rather than =) +## IdentityDictionary: +uses identity test (== rather than =) + ``` | b x y | x := Dictionary new. "allocate collection" @@ -939,13 +945,8 @@ x := FillInTheBlank request: 'Prompt Me'. "prompt user for inp Utilities openCommandKeyHelp ``` - - - ## Ready For More? -### Free Online - * [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) * [smalltalk dot org](http://www.smalltalk.org/) * [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) -- cgit v1.2.3 From 3e6ff8f257422c7b9deb295bbf5b508245095363 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 16:17:59 +0530 Subject: More fixes --- smalltalk.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 57e558b2..d9edbf06 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -188,7 +188,7 @@ x := Random new next; yourself. x next. "random number strea x := 100 atRandom. "quick random number" ``` -##Bitwise Manipulation: +## Bitwise Manipulation: ``` | b x | x := 16rFF bitAnd: 16r0F. "and bits" @@ -381,7 +381,9 @@ y := x asSet. "convert string to s y := x shuffled. "randomly shuffle string" ``` -## Array: Fixed length collection +## Array: +Fixed length collection + - ByteArray: Array limited to byte elements (0-255) - WordArray: Array limited to word elements (0-2^32) @@ -424,7 +426,9 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## OrderedCollection: acts like an expandable array +## OrderedCollection: +acts like an expandable array + ``` | b x y sum max | x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" @@ -616,7 +620,6 @@ y := x key. y := x value. ``` -## Dictionary: ## IdentityDictionary: uses identity test (== rather than =) -- cgit v1.2.3 From b99967e809e8ad6497920b1792486c772bbc0c70 Mon Sep 17 00:00:00 2001 From: Tim Rowledge Date: Sat, 27 Oct 2018 16:52:56 +0530 Subject: Fix content --- smalltalk.html.markdown | 172 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 117 insertions(+), 55 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index d9edbf06..b4a0669f 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -3,44 +3,94 @@ language: smalltalk filename: smalltalk.st contributors: - ["Jigyasa Grover", "https://github.com/jig08"] + - ["tim Rowledge", "tim@rowledge.org"] --- -- Smalltalk is an object-oriented, dynamically typed, reflective programming language. +- Smalltalk is a fully object-oriented, dynamically typed, reflective programming language with no 'non-object' types. - Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." - It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`. -## Allowable characters: +## The Basics +### Everything is an object +Yes, everything. Integers are instances of one of the numeric classes. Classes are instances of the class Metaclass and are just as manipulable as any other object. All classes are part of a single class tree; no disjoint class trees. Stack frames are objects and can be manipulated, which is how the debugger works. There are no pointers into memory locations that you can dereference and mess with. + +### Functions are not called; messages are sent to objects +Work is done by sending messages to objects, which decide how to respond to that message and run a method as a result, which eventually returns some object to the original message sending code. +The system knows the class of the object receiving a message and looks up the message in that class's list of methods. If it is not found, the lookup continues in the super class until either it is found or the root of the classes is reached and there is still no relevant method. +If a suitable method is found the code is run, and the same process keeps on going with all the methods sent by that method and so on forever. +If no suitable method is found an exception is raised, which typically results in a user interface notifier to tell the user that the message was not understood. It is entirely possible to catch the exception and do something to fix the problem, which might range from 'ignore it' to 'load some new packages for this class and try again'. +A method (more strictly an instance of the class CompiledMethod) is a chunk of Smalltalk code that has been compiled into bytecodes. Executing methods start at the beginning and return to the sender when a return is encountered (we use ^ to signify 'return the follwing object') or the end of the code is reached, in which case the current object running the code is returned. + +### Simple syntax +Smalltalk has a simple syntax with very few rules. +The most basic operation is to send a message to an object +`anObject aMessage` + +There are three sorts of messages +- unary - a single string that may be several words conjoined in what we call camelcase form, with no arguments. For example 'size', 'reverseBytes', 'convertToLargerFormatPixels' +- binary - a small set of symbols of the sort often used for arithmetic operations in most languages, requiring a single argument. For example '+', '//', '@'. We do not use traditional arithmetic precedence, something to keep an eye on. +- keyword - the general form where multiple arguments can be passed. As with the unary form we use camelcase to join words together but arguments are inserted in the midst of the message with colons used to separate them lexically. For example 'setTemperature:', 'at:put:', 'drawFrom:to:lineWidth:fillColor:' + +#### An example +`result := myObject doSomethingWith: thatObject` +We are sending the message 'doSomethingWith:' to myObject. This happens to be a message that has a single argument but that's not important yet. +'myObject' is a 'MyExampleClass' instance so the system looks at the list of messages understood by MyExampleClass +- beClever +- doWierdThing: +- doSomethingWith + +In searching we see what initially looks like a match - but no, it lacks the final colon. So we find the super class of MyExampleClass - BigExampleClass. Which has a list of known messages of its own +- beClever +- doSomethingWith: +- buildCastleInAir +- annoyUserByDoing: + +We find a proper exact match and start to execute the code +``` +doSomethingWith: argumentObject +"A comment about what this code is meant to do and any known limitations, problems, where it might be further documented etc" +self size > 4 ifTrue: [^argumentObject sizeRelatingTo: self]. +``` + +Everything here except the `^` involves sending more messages. Event the `ifTrue:` that you might think is a language control structure is just Smalltalk code. +We start by sending `size` to `self`. `self` is the object currently running the code - so in this case it is the myObject we started with. `size` is a very common message that we might anticipate tells us something about how big an object is; you could look it up with the Smalltalk tools very simply. The result we get is then sent the message `>` with the plain old integer 4 (which is an object too; no strange primitive types to pollute the system here) and nobody should be surprised the `>` is a comparison that answers true or false. That boolean (which is actually a Boolean object in Smalltalk) is sent the message `ifTrue:` with the block of code between the `[]` as its argument; obvioulsy a true boolean might be expected to run that block of code and a false to ignore it. +If the block is run then we do some more message sending to the argument object and noting the `^` we return the answer back to our starting point and it gets assigned to `result`. If the block is ignored we seem to run out of code and so `self` is returned and assigned to `result`. + +## Smalltalk quick reference cheat-sheet +Taken from [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) + +#### Allowable characters: - a-z - A-Z - 0-9 - .+/\*~<>@%|&? - blank, tab, cr, ff, lf -## Variables: -- variables must be declared before use -- shared vars must begin with uppercase -- local vars must begin with lowercase -- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk` +#### Variables: +- variable names must be declared before use but are untyped +- shared vars (globals, class vars) conventionally begin with uppercase (except the reserved names shown below) +- local vars (instance vars, temporaries, method & block arguments) conventionally begin with lowercase +- reserved names: `nil`, `true`, `false`, `self`, `super`, and `thisContext` -## Variable scope: -- Global: defined in Dictionary Smalltalk and accessible by all objects in system +#### Variable scope: +- Global: defined in a Dictionary named 'Smalltalk' and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` - Method Temporary: local to a method - Block Temporary: local to a block -- Pool: variables in a Dictionary object -- Method Parameters: automatic local vars created as a result of message call with params -- Block Parameters: automatic local vars created as a result of value: message call -- Class: shared with all instances of one class & its subclasses -- Class Instance: unique to each instance of a class -- Instance Variables: unique to each instance +- Pool: variables in a Dictionary object, possibly shared with classes not directly related by inheritance +- Method Parameters: automatic method temp vars that name the incoming parameters. Cannot be assigned to +- Block Parameters: automatic block temp vars that name the incoming parameters. Cannot be assigned to +- Class: shared with all instances of a class & its subclasses +- Class Instance: unique to each instance of a class. Too commonly confused with class variables +- Instance Variables: unique to each instance of a class -`"Comments are enclosed in quotes"` +`"Comments are enclosed in quotes and may be arbitrary length"` -`"Period (.) is the statement separator"` +`"Period (.) is the statement separator. Not required on last line of a method"` -## Transcript: +#### Transcript: ``` Transcript clear. "clear to transcript window" Transcript show: 'Hello World'. "output string in transcript window" @@ -54,7 +104,7 @@ Transcript cr. "carriage return / l Transcript endEntry. "flush the output buffer" ``` -## Assignment: +#### Assignment: ``` | x y | x _ 4. "assignment (Squeak) <-" @@ -73,7 +123,7 @@ y := x deepCopy. "copy object and ins y := x veryDeepCopy. "complete tree copy using a dictionary" ``` -## Constants: +#### Constants: ``` | b | b := true. "true constant" @@ -93,7 +143,7 @@ x := #(3 2 1). "array constants" x := #('abc' 2 $a). "mixing of types allowed" ``` -## Booleans: +#### Booleans: ``` | b x y | x := 1. y := 2. @@ -131,7 +181,7 @@ b := $A isUppercase. "test if upper case b := $A isLowercase. "test if lower case character" ``` -## Arithmetic expressions: +#### Arithmetic expressions: ``` | x | x := 6 + 3. "addition" @@ -188,7 +238,7 @@ x := Random new next; yourself. x next. "random number strea x := 100 atRandom. "quick random number" ``` -## Bitwise Manipulation: +#### Bitwise Manipulation: ``` | b x | x := 16rFF bitAnd: 16r0F. "and bits" @@ -204,7 +254,7 @@ b := 16rFF anyMask: 16r0F. "test if any bits se b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" ``` -## Conversion: +#### Conversion: ``` | x | x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" @@ -219,7 +269,7 @@ x := 15 printStringBase: 16. x := 15 storeStringBase: 16. ``` -## Blocks: +#### Blocks: - blocks are objects and may be assigned to a variable - value is last expression evaluated unless explicit return - blocks may be nested @@ -237,7 +287,7 @@ Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argu "x := [ | z | z := 1.]. *** localvars not available in squeak blocks" ``` -## Method calls: +#### Method calls: - unary methods are messages with no arguments - binary methods - keyword methods are messages with selectors including colons standard categories/protocols: @@ -265,7 +315,7 @@ Transcript "Cascading - send mu x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" ``` -## Conditional Statements: +#### Conditional Statements: ``` | x | x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" @@ -297,7 +347,7 @@ switch at: $C put: [Transcript show: 'Case C'; cr]. result := (switch at: $B) value. ``` -## Iteration statements: +#### Iteration statements: ``` | x y | x := 4. y := 1. @@ -309,7 +359,7 @@ x timesRepeat: [y := y * 2]. "times repeat loop ( #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" ``` -## Character: +#### Character: ``` | x y | x := $A. "character assignment" @@ -329,7 +379,7 @@ b := $A <= $B. "comparison" y := $A max: $B. ``` -## Symbol: +#### Symbol: ``` | b x y | x := #Hello. "symbol assignment" @@ -351,7 +401,7 @@ y := x asBag. "convert symbol to b y := x asSet. "convert symbol to set collection" ``` -## String: +#### String: ``` | b x y | x := 'This is a string'. "string assignment" @@ -381,7 +431,7 @@ y := x asSet. "convert string to s y := x shuffled. "randomly shuffle string" ``` -## Array: +#### Array: Fixed length collection - ByteArray: Array limited to byte elements (0-255) @@ -426,7 +476,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## OrderedCollection: +#### OrderedCollection: acts like an expandable array ``` @@ -471,7 +521,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## SortedCollection: +#### SortedCollection: like OrderedCollection except order of elements determined by sorting criteria ``` @@ -515,7 +565,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Bag: +#### Bag: like OrderedCollection except elements are in no particular order ``` @@ -548,10 +598,10 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Set: +#### Set: like Bag except duplicates not allowed -## IdentitySet: +#### IdentitySet: uses identity test (== rather than =) ``` @@ -583,7 +633,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Interval: +#### Interval: ``` | b x y sum max | x := Interval from: 5 to: 10. "create interval object" @@ -612,7 +662,7 @@ y := x asBag. "convert to bag coll y := x asSet. "convert to set collection" ``` -## Associations: +#### Associations: ``` | x y | x := #myVar->'hello'. @@ -620,7 +670,8 @@ y := x key. y := x value. ``` -## IdentityDictionary: +#### Dictionary: +#### IdentityDictionary: uses identity test (== rather than =) ``` @@ -686,7 +737,7 @@ Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from S Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" ``` -## Internal Stream: +#### Internal Stream: ``` | b x ios | ios := ReadStream on: 'Hello read stream'. @@ -716,7 +767,7 @@ x := ios contents. b := ios atEnd. ``` -## FileStream: +#### FileStream: ``` | b x ios | ios := FileStream newFileNamed: 'ios.txt'. @@ -737,7 +788,7 @@ b := ios atEnd. ios close. ``` -## Date: +#### Date: ``` | x y | x := Date today. "create date for today" @@ -771,7 +822,7 @@ y := x printFormat: #(2 1 3 $/ 1 1). "print formatted dat b := (x <= Date today). "comparison" ``` -## Time: +#### Time: ``` | x y | x := Time now. "create time from current time" @@ -791,7 +842,7 @@ x := Time millisecondsToRun: [ "timing facility" b := (x <= Time now). "comparison" ``` -## Point: +#### Point: ``` | x y | x := 200@100. "obtain a new point" @@ -816,12 +867,12 @@ x := 200@100 min: 50@200. "min x and y" x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" ``` -## Rectangle: +#### Rectangle: ``` Rectangle fromUser. ``` -## Pen: +#### Pen: ``` | myPen | Display restoreAfter: [ @@ -848,7 +899,7 @@ Display height. "get display height" ]. ``` -## Dynamic Message Calling/Compiling: +#### Dynamic Message Calling/Compiling: ``` | receiver message result argument keyword1 keyword2 argument1 argument2 | "unary message" @@ -884,7 +935,7 @@ result := (Message sentTo: receiver. ``` -## Class/Meta-class: +#### Class/Meta-class: ``` | b x | x := String name. "class name" @@ -917,7 +968,7 @@ b := String isWords. "true if index insta Object withAllSubclasses size. "get total number of class entries" ``` -## Debugging: +#### Debugging: ``` | a b x | x yourself. "returns receiver" @@ -940,7 +991,7 @@ a := 'A1'. b := 'B2'. a become: b. "switch two objects" Transcript show: a, b; cr. ``` -## Misc +#### Misc ``` | x | "Smalltalk condenseChanges." "compress the change file" @@ -950,12 +1001,23 @@ Utilities openCommandKeyHelp ## Ready For More? -* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) -* [smalltalk dot org](http://www.smalltalk.org/) -* [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) +### Online Smalltalk systems +Most Smalltalks are either free as in OSS or have a free downloadable version with some payment required for commercial usage. +* [Squeak](https://www.squeak.org) +* [Pharo](http://pharo.org) +* [Smalltalk/X](https://www.exept.de/en/smalltalk-x.html) +* [Gemstone](http://gemtalksystems.com/) +* [VA Smalltalk](http://www.instantiations.com/products/vasmalltalk/) +* [VisualWorks Smalltalk](http://www.cincomsmalltalk.com/) + +### Online Smalltalk books and articles +* [Smalltalk Programming Resources](http://www.whoishostingthis.com/resources/smalltalk/) * [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) * [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) +* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) + +#### Historical doc * [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) +* [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) * [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) * [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) -* [Smalltalk Programming Resources](http://www.whoishostingthis.com/resources/smalltalk/) -- cgit v1.2.3 From b6e92255321071bac1a194112661e79cc6ea2f1b Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 16:59:35 +0530 Subject: Fix page title --- smalltalk.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index b4a0669f..87135cf4 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -1,5 +1,5 @@ --- -language: smalltalk +language: Smalltalk filename: smalltalk.st contributors: - ["Jigyasa Grover", "https://github.com/jig08"] -- cgit v1.2.3 From 3268606f95730da96fcb61dffc9fc5a6fc971fff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zden=C4=9Bk=20B=C3=B6hm?= Date: Sat, 27 Oct 2018 17:19:02 +0530 Subject: Fix text --- cs-cz/python3.html.markdown | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 581ed3a3..dbaae88b 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -76,9 +76,13 @@ False or True # => True # Používání logických operátorů s čísly 0 and 2 # => 0 -5 or 0 # => -5 -0 == False # => True -2 == True # => False -1 == True # => True + +# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". +# Stejně jako u hodnoty None. +# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ +0 is False # => True +2 is True # => False +1 is True # => True # Rovnost je == 1 == 1 # => True @@ -99,11 +103,11 @@ False or True # => True 2 < 3 < 2 # => False -# Řetězce používají " nebo ' a mohou obsahovat UTF8 znaky +# Řetězce používají " nebo ' a mohou obsahovat unicode znaky "Toto je řetězec." 'Toto je také řetězec.' -# Řetězce se také dají sčítat, ale nepoužívejte to +# Řetězce se také dají slučovat "Hello " + "world!" # => "Hello world!" # Dají se spojovat i bez '+' "Hello " "world!" # => "Hello world!" @@ -152,10 +156,12 @@ print("Jsem 3. Python 3.") # Konvence je používat male_pismo_s_podtrzitky nazev_promenne = 5 nazev_promenne # => 5 -# Názvy proměnných mohou obsahovat i UTF8 znaky +# Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. +# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: +# https://www.python.org/dev/peps/pep-3131/ název_proměnné = 5 -# Přístup k předtím nepoužité proměnné vyvolá výjimku +# Přístup k předtím nedefinované proměnné vyvolá výjimku # Odchytávání vyjímek - viz další kapitola neznama_promenna # Vyhodí NameError @@ -199,7 +205,7 @@ sez[::-1] # => [3, 4, 2, 1] # Odebírat prvky ze seznamu lze pomocí del del sez[2] # sez je nyní [1, 2, 3] -# Seznamy můžete sčítat +# Seznamy můžete slučovat # Hodnoty sez a jiny_seznam přitom nejsou změněny sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] -- cgit v1.2.3 From 62e9ea6b71d7c2cbb7b408f17fba32d355ea43ba Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 18:16:06 +0530 Subject: Explain regexp, closes #2197 --- yaml.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/yaml.html.markdown b/yaml.html.markdown index ab0f9d55..d51b2147 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -121,6 +121,10 @@ other_anchor: *anchor_name base: &base name: Everyone has same name +# The regexp << is called Merge Key Language-Independent Type. It is is used to +# indicate that all the keys of one or more specified maps should be inserted +# into the current map. + foo: &foo <<: *base age: 10 -- cgit v1.2.3 From f12f89ab0b9acc74a8c6ab1a78cae1708a004876 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 18:24:03 +0530 Subject: Explain initialize, closes #1467 --- red.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/red.html.markdown b/red.html.markdown index 3575032f..73baf462 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -103,7 +103,8 @@ type? my-integer integer! ; A variable can be initialized using another variable that gets initialized -; at the same time. +; at the same time. Initialize here refers to both declaring a variable and +; assigning a value to it. i2: 1 + i1: 1 ; Arithmetic is straightforward -- cgit v1.2.3 From 699ab98187ba01da8cf2874ef9048139a6727b5f Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 27 Oct 2018 18:32:40 +0530 Subject: Correct wording, closes #3098 --- yaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index d51b2147..8683971e 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -171,7 +171,7 @@ set: ? item3 or: {item1, item2, item3} -# Like Python, sets are just maps with null values; the above is equivalent to: +# Sets are just maps with null values; the above is equivalent to: set2: item1: null item2: null -- cgit v1.2.3 From 44c7eaad2488effb691d4a0f4e9ded32c9ff360b Mon Sep 17 00:00:00 2001 From: Will L Fife Date: Sat, 27 Oct 2018 23:39:11 -0700 Subject: Add the distributed source control management tool mercurial. --- mercurial.html.markdown | 399 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 399 insertions(+) create mode 100644 mercurial.html.markdown diff --git a/mercurial.html.markdown b/mercurial.html.markdown new file mode 100644 index 00000000..f7644f33 --- /dev/null +++ b/mercurial.html.markdown @@ -0,0 +1,399 @@ +--- +category: tool +tool: hg +contributors: + - ["Will L. Fife", "http://github.com/sarlalian"] +filename: LearnHG.txt +--- + +Mercurial is a free, distributed source control management tool. It offers you +the power to efficiently handle projects of any size while using an intuitive +interface. It is easy to use and hard to break, making it ideal for anyone +working with versioned files. + +## Versioning Concepts + +### What is version control? + +Version control is a system that records changes to a file(s), over time. + +### Centralized Versioning VS Distributed Versioning + + +* Centralized version control focuses on synchronizing, tracking, and backing +up files. +* Distributed version control focuses on sharing changes. Every change has a +unique id. +* Distributed systems have no defined structure. You could easily have a SVN +style, centralized system, with mercurial. + + +### Why Use Mercurial + +* Distributed Architecture +* Fast +* Platform Independent +* Extensible +* Easy to use +* Open Source + + +#### Distributed Architecture + +Traditional version control systems such as Subversion are typical +client-server architectures with a central server to store the revisions of a +project. In contrast, Mercurial is truly distributed, giving each developer a +local copy of the entire development history. This way it works independent of +network access or a central server. Committing, branching and merging are fast +and cheap. + + +#### Fast + +Mercurial's implementation and data structures are designed to be fast. You can +generate diffs between revisions, or jump back in time within seconds. +Therefore Mercurial is perfectly suitable for large projects such as OpenJDK +([hg](http://hg.openjdk.java.net/jdk7/jdk7)) or NetBeans +([hg](http://hg.netbeans.org/)). + +#### Platform Independent + +Mercurial was written with platform independence in mind. Therefore most of +Mercurial is written in Python, with a small part in portable C for performance +reasons. As a result, binary releases are available on all major platforms. + + +#### Extensible + +The functionality of Mercurial can be increased with extensions, either by +activating the official ones which are shipped with Mercurial or downloading +some [from the wiki](https://www.mercurial-scm.org/wiki/UsingExtensions) or by +[writing your own](https://www.mercurial-scm.org/wiki/WritingExtensions). +Extensions are written in Python and can change the workings of the basic +commands, add new commands and access all the core functions of Mercurial. + + +#### Easy to Use + +Mercurial sports a consistent command set in which most subversion users feel +right at home. Potentially dangerous actions are available via extensions you +need to enable, so the basic interface is easy to use, easy to learn and hard +to break. The [Quick Start](https://www.mercurial-scm.org/quickstart) should +get you going in a just few minutes. + +#### Open Source + +Mercurial is free software licensed under the terms of the [GNU General Public +License Version 2](http://www.gnu.org/licenses/gpl-2.0.txt) or any later +version. + + +## Terminology + +| Term | Definition | +| ------------- | ---------------------------------- | +| Repository | Collection of revisions | +| hgrc | A file which stores defaults for a repository. Global is ~/.hgrc and local is .hgrc inside the repository | +| revision | Committed changeset, by REV number | +| changeset | Set of work changes saved as diffs | +| diff | Changes between files | +| tag | Name for a specific revision | +| parent(s) | Immediate ancestor(s) of revision or work | +| branch | Child of a revision | +| head | A head is a changeset with no child changesets | +| merge | The process of merging two HEADS | +| tip | Latest revision in any branch | +| patch | All diffs between two revisions | +| bundle | Patch with permis­sions and rename support | + + +## Commands + +### init + +Create a new repository in the given directory, the settings and stored +information are in a directory named ".hg" + +```bash +$ hg init +``` + +### help + +Will give you access to a very detailed description of each command. + +```bash +# Quickly check what commands are available +$ hg help + +# Get help on a specific command +# hg help +$ hg help add +$ hg help commit +$ hg help init +``` + +### status + +Show the differences between what is on disk and what is committed to the current +branch or tag. + + +```bash +# Will display the status of files +$ hg status + +# Get help on the status subcommand +$ hg help status + +``` + +### add + +Will add the specified files to the repository on the next commit + +```bash +# Add a file in the current directory +$ hg add filename.rb + +# Add a file in a sub directory +$ hg add foo/bar/filename.rb + +# Add files by pattern +$ hg add *.rb +``` + +### branch + +Set or show the current branch name + +*Branch names are permanent and global. Use 'hg bookmark' to create a +light-weight bookmark instead. See 'hg help glossary' for more information +about named branches and bookmarks.* + +```bash +# With no argument it shows the current branch name +$ hg branch + +# With a name argument it will change the current branch. +$ hg branch new_branch +marked working directory as branch new_branch +(branches are permanent and global, did you want a bookmark?) +``` + +### tag + +Add one or more tags for the current or given revision + +Tags are used to name particular revisions of the repository and are very +useful to compare different revisions, to go back to significant earlier +versions or to mark branch points as releases, etc. Changing an existing tag +is normally disallowed; use -f/--force to override. + +```bash +# List tags +$ hg tags +tip 2:efc8222cd1fb +v1.0 0:37e9b57123b3 + +# Create a new tag on the current revision +$ hg tag v1.1 + +# Create a tag on a specific revision +$ hg tag -r efc8222cd1fb v1.1.1 +``` + +### clone + +Create a copy of an existing repository in a new directory. + +If no destination directory name is specified, it defaults to the basename of +the source. + +```bash +# Clone a remote repo to a local directory +$ hg clone https://some-mercurial-server.example.com/reponame + +# Clone a local repo to a remote server +$ hg clone . ssh://username@some-mercurial-server.example.com/newrepo + +# Clone a local repo to a local repo +$ hg clone . /tmp/some_backup_dir +``` + +### commit / ci + +Commit changes to the given files into the repository. + +```bash +# Commit with a message +$ hg commit -m 'This is a commit message' + +# Commit all added / removed files in the currrent tree +$ hg commit -A 'Adding and removing all existing files in the tree' + +# amend the parent of the working directory with a new commit that contains the +# changes in the parent in addition to those currently reported by 'hg status', +$ hg commit --amend -m "Correct message" +``` + +### diff + +Show differences between revisions for the specified files using the unified diff format. + +```bash +# Show the diff between the current directory and a previous revision +$ hg diff -r 10 + +# Show the diff between two previous revisions +$ hg diff -r 30 -r 20 +``` + +### grep + +Search revision history for a pattern in specified files + +```bash +# Search files for a specific phrase +$ hg grep "TODO:" +``` + +### log / history + +Show revision history of entire repository or files. If no revision range is +specified, the default is "tip:0" unless --follow is set, in which case the +working directory parent is used as the starting revision. + +```bash +# Show the history of the entire repository +$ hg log + +# Show the history of a single file +$ hg log myfile.rb + +# Show the revision changes as an ASCII art DAG with the most recent changeset +# at the top. +$ hg log -G +``` + +### merge + +Merge another revision into working directory + +```bash +# Merge changesets to local repository +$ hg merge + +# Merge from a named branch or revision into the current local branch +$ hg merge branchname_or_revision + +# After successful merge, commit the changes +hg commit +``` + +### move / mv / rename + +Rename files; equivalent of copy + remove. Mark dest as copies of sources; +mark sources for deletion. If dest is a directory, copies are put in that +directory. If dest is a file, there can only be one source. + +```bash +# Rename a single file +$ hg mv foo.txt bar.txt + +# Rename a directory +$ hg mv some_directory new_directory +``` + +### pull + +Pull changes from a remote repository to a local one. + +```bash +# List remote paths +$ hg paths +remote1 = http://path/to/remote1 +remote2 = http://path/to/remote2 + +# Pull from remote 1 +$ hg pull remote1 + +# Pull from remote 2 +$ hg pull remote2 +``` + +### push + +Push changesets from the local repository to the specified destination. + +```bash +# List remote paths +$ hg paths +remote1 = http://path/to/remote1 +remote2 = http://path/to/remote2 + +# Pull from remote 1 +$ hg push remote1 + +# Pull from remote 2 +$ hg push remote2 +``` + +### rebase + +Move changeset (and descendants) to a different branch + +Rebase uses repeated merging to graft changesets from one part of history +(the source) onto another (the destination). This can be useful for +linearizing *local* changes relative to a master development tree. + +* Draft the commits back to the source revision. +* -s is the source, ie. what you are rebasing. +* -d is the destination, which is where you are sending it. + +```bash +# Put the commits into draft status +# This will draft all subsequent commits on the relevant branch +$ hg phase --draft --force -r 1206 + +# Rebase from from revision 102 over revision 208 +$ hg rebase -s 102 -d 208 +``` + +### revert + +Restore files to their checkout state. With no revision specified, revert the +specified files or directories to the contents they had in the parent of the +working directory. This restores the contents of files to an unmodified state +and unschedules adds, removes, copies, and renames. If the working directory +has two parents, you must explicitly specify a revision. + +```bash +# Reset a specific file to its checked out state +$ hg revert oops_i_did_it_again.txt + +# Revert a specific file to its checked out state without leaving a .orig file +# around +$ hg revert -C oops_i_did_it_again.txt + +# Revert all changes +$ hg revert -a +``` + +### rm / remove + +Remove the specified files on the next commit. + +```bash +# Remove a spcific file +$ hg remove go_away.txt + +# Remove a group of files by pattern +$ hg remove *.txt +``` + +## Further Information + +* [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guid) +* [Mercurial Quick Start](https://www.mercurial-scm.org/wiki/QuickStart) +* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) \ No newline at end of file -- cgit v1.2.3 From f8a96c4889a600b8ffee918a3e2746fae35becc4 Mon Sep 17 00:00:00 2001 From: Will L Fife Date: Sat, 27 Oct 2018 23:56:48 -0700 Subject: Some additional changes to existing wording --- mercurial.html.markdown | 76 +++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 44 deletions(-) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index f7644f33..1d991384 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -6,26 +6,17 @@ contributors: filename: LearnHG.txt --- -Mercurial is a free, distributed source control management tool. It offers you -the power to efficiently handle projects of any size while using an intuitive -interface. It is easy to use and hard to break, making it ideal for anyone -working with versioned files. +Mercurial is a free, distributed source control management tool. It offers +you the power to efficiently handle projects of any size while using an +intuitive interface. It is easy to use and hard to break, making it ideal for +anyone working with versioned files. ## Versioning Concepts ### What is version control? -Version control is a system that records changes to a file(s), over time. - -### Centralized Versioning VS Distributed Versioning - - -* Centralized version control focuses on synchronizing, tracking, and backing -up files. -* Distributed version control focuses on sharing changes. Every change has a -unique id. -* Distributed systems have no defined structure. You could easily have a SVN -style, centralized system, with mercurial. +Version control is a system that keeps track fo changes to a set of file(s) +and/or directorie(s) over time. ### Why Use Mercurial @@ -40,27 +31,25 @@ style, centralized system, with mercurial. #### Distributed Architecture -Traditional version control systems such as Subversion are typical -client-server architectures with a central server to store the revisions of a -project. In contrast, Mercurial is truly distributed, giving each developer a -local copy of the entire development history. This way it works independent of -network access or a central server. Committing, branching and merging are fast -and cheap. +Traditionally version control systems such as CVS and Subversion are a client server +architecture with a central server to store the revsion history of a project. Mercurial however +is a truly distributed architecture, giving each devloper a full local copy of the entire +development history. It works independently of a central server. #### Fast -Mercurial's implementation and data structures are designed to be fast. You can -generate diffs between revisions, or jump back in time within seconds. -Therefore Mercurial is perfectly suitable for large projects such as OpenJDK -([hg](http://hg.openjdk.java.net/jdk7/jdk7)) or NetBeans +Mercurial is implemented to be fast. You are able to generate diffs between +revsions, and switch between tags and branches with little time and effort. +Mercurial is used by large projects such as OpenJDK +([hg](http://hg.openjdk.java.net/jdk7/jdk7)) and NetBeans ([hg](http://hg.netbeans.org/)). #### Platform Independent -Mercurial was written with platform independence in mind. Therefore most of -Mercurial is written in Python, with a small part in portable C for performance -reasons. As a result, binary releases are available on all major platforms. +Mercurial was written to be highly platform independent. Much of Mercurial is +written in Python, with small performance critical parts written in portable +C. Binary releases are available for all major platforms. #### Extensible @@ -75,11 +64,10 @@ commands, add new commands and access all the core functions of Mercurial. #### Easy to Use -Mercurial sports a consistent command set in which most subversion users feel -right at home. Potentially dangerous actions are available via extensions you -need to enable, so the basic interface is easy to use, easy to learn and hard -to break. The [Quick Start](https://www.mercurial-scm.org/quickstart) should -get you going in a just few minutes. +The Mercurial command set is consistent with what subversion users would +expect, so they are likely to feel right at home. Most dangerous actions +are part of extensions that need to be enabled to be used. + #### Open Source @@ -92,18 +80,18 @@ version. | Term | Definition | | ------------- | ---------------------------------- | -| Repository | Collection of revisions | -| hgrc | A file which stores defaults for a repository. Global is ~/.hgrc and local is .hgrc inside the repository | -| revision | Committed changeset, by REV number | -| changeset | Set of work changes saved as diffs | -| diff | Changes between files | -| tag | Name for a specific revision | -| parent(s) | Immediate ancestor(s) of revision or work | -| branch | Child of a revision | +| Repository | A repository is a collection of revisions | +| hgrc | A configuration file which stores the defaults for a repository. | +| revision | A committed changeset: has a REV number | +| changeset | Set of changes saved as diffs | +| diff | Changes between file(s) | +| tag | A named named revision | +| parent(s) | Immediate ancestor(s) of a revison | +| branch | A child of a revision | | head | A head is a changeset with no child changesets | -| merge | The process of merging two HEADS | -| tip | Latest revision in any branch | -| patch | All diffs between two revisions | +| merge | The process of merging two HEADS | +| tip | The latest revision in any branch | +| patch | All of the diffs between two revisions | | bundle | Patch with permis­sions and rename support | -- cgit v1.2.3 From cc2b3dca73edfb6231a79bf483730af28e7a99d7 Mon Sep 17 00:00:00 2001 From: Will Fife Date: Sun, 28 Oct 2018 00:19:49 -0700 Subject: Update mercurial.html.markdown --- mercurial.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index 1d991384..f757dd7c 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -2,7 +2,7 @@ category: tool tool: hg contributors: - - ["Will L. Fife", "http://github.com/sarlalian"] + - ["Will L. Fife", "http://github.com/sarlalian"] filename: LearnHG.txt --- @@ -384,4 +384,4 @@ $ hg remove *.txt * [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guid) * [Mercurial Quick Start](https://www.mercurial-scm.org/wiki/QuickStart) -* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) \ No newline at end of file +* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) -- cgit v1.2.3 From af302ce02acec2b188ec9acb23746740864a52aa Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Sun, 28 Oct 2018 04:08:10 -0400 Subject: Solve minor typos & update some missing translations --- es-es/matlab-es.html.markdown | 60 +++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index 813d379c..99125b0c 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -13,14 +13,14 @@ lang: es-es MATLAB significa 'MATrix LABoratory'. Es un poderoso lenguaje de computación numérica comúnmente usado en ingeniería y matemáticas. -Si tiene algún comentario, no dude en ponerse en contacto conmigo en +Si tiene algún comentario, no dude en ponerse en contacto el autor en [@the_ozzinator](https://twitter.com/the_ozzinator), o [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). ```matlab -%% Una sección de código comienza con dos símbolos de porcentaje. Los títulos de la sección van en la misma línea. +%% Una sección de código comienza con dos símbolos de porcentaje. Los títulos de la sección van en la misma líneas. % Los comentarios comienzan con un símbolo de porcentaje. -W + %{ Los Comentarios de multiples lineas se ven @@ -43,7 +43,7 @@ load learnmatlab.mat y A = A * 2; plot(A); -%% Las secciones de códigos también son conocidas como celdas de código o modo celda (no ha de ser confundido con arreglo de celdas) +%% Las secciones de código también son conocidas como celdas de código o modo celda (no ha de ser confundido con arreglo de celdas) % Los comandos pueden abarcar varias líneas, usando '...' @@ -81,11 +81,11 @@ format short % 4 decimales en un número flotante format long % 15 decimales format bank % solo dos dígitos después del punto decimal - para cálculos financieros fprintf('texto') % imprime "texto" en la pantalla -disp('texto') % imprime "text" en la pantalla +disp('texto') % imprime "texto" en la pantalla % Variables y expresiones myVariable = 4 % Espacio de trabajo de aviso muestra la variable recién creada -myVariable = 4; % Semi-colon suprime la salida a la Ventana de Comando +myVariable = 4; % Punto y coma suprime la salida a la Ventana de Comando 4 + 6 % ans = 10 8 * myVariable % ans = 32 2 ^ 3 % ans = 8 @@ -121,16 +121,16 @@ A( A > 5 ) % devuelve un vector que contiene los elementos en A para los que la condición es verdadera % Cadenas -a = 'MyCadena' +a = 'MiCadena' length(a) % ans = 8 a(2) % ans = y -[a,a] % ans = MyStringMyString +[a,a] % ans = MiCadenaMiCadena % Celdas a = {'uno', 'dos', 'tres'} a(1) % ans = 'uno' - retorna una celda -char(a(1)) % ans = one - retorna una cadena +char(a(1)) % ans = uno - retorna una cadena % Estructuras A.b = {'uno','dos'}; @@ -139,7 +139,7 @@ A.d.e = false; % Vectores x = [4 32 53 7 1] -x(2) % ans = 32, índices en Matlab comienzan 1, no 0 +x(2) % ans = 32, los índices en Matlab comienzan 1, no 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -157,7 +157,7 @@ A = [1 2 3; 4 5 6; 7 8 9] % 4 5 6 % 7 8 9 -A(2,3) % ans = 6, A(row, column) +A(2,3) % ans = 6, A(fila, columna) A(6) % ans = 8 % (concatena implícitamente columnas en el vector, luego indexa en base a esto) @@ -238,11 +238,11 @@ A.' % Versión concisa de transposición (sin tomar complejo conjugado) % Elemento por elemento Aritmética vs. Matriz Aritmética % Por sí solos, los operadores aritméticos actúan sobre matrices completas. Cuando preceden % por un punto, actúan en cada elemento en su lugar. Por ejemplo: -A * B % Matrix multiplication -A .* B % Multiple each element in A by its corresponding element in B +A * B % Multiplicación de matrices +A .* B % Multiplica cada elemento en A por su elemento correspondiente en B -% There are several pairs of functions, where one acts on each element, and -% the other (whose name ends in m) acts on the whole matrix. +% Hay varios pares de funciones, donde una actúa sobre cada elemento y +% la otra (cuyo nombre termina en m) actúa sobre la matriz completa. exp(A) % exponencializar cada elemento expm(A) % calcular la matriz exponencial sqrt(A) % tomar la raíz cuadrada de cada elemento @@ -276,7 +276,7 @@ fplot (@(x) x^2, [2,5]) % Un diagrama con el eje y logarítmico... grid on % Muestra la cuadrícula; apague con 'grid off'. axis square % Hace que la región actual de los ejes sea cuadrada. -axis equal % Establezce la relación de aspecto para que las unidades de datos sean las mismas en todas las direcciones. +axis equal % Establece la relación de aspecto para que las unidades de datos sean las mismas en todas las direcciones. scatter(x, y); % Gráfico de dispersión hist(x); % Histograma @@ -306,12 +306,12 @@ h = plot(x, y); % Puedes guardar un control de una figura cuando la creas set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') -% '-' es línea continua, '---' discontinua, ':' punteada, '-.' dash-dot, 'ninguno' no es línea +% '--' es línea continua, '---' discontinua, ':' punteada, '-.' dash-dot, 'none' es sin línea get (h, 'LineStyle') % La función gca devuelve un mango a los ejes para la figura actual -set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis +set(gca, 'XDir', 'reverse'); % invierte la dirección del eje x % Para crear una figura que contenga varios ejes en posiciones de mosaico, use 'subplot' subplot(2,3,1); % seleccione la primera posición en una grilla de subtramas de 2 por 3 @@ -329,7 +329,7 @@ cd /path/to/move/into % cambia de directorio % Las variables se pueden guardar en archivos .mat save('myFileName.mat') % Guarda las variables en su espacio de trabajo -load('myFileName.mat') % Carga las variables guardadas en Workspace +load('myFileName.mat') % Carga las variables guardadas en espacio de trabajo % M-file Scripts % Un archivo de script es un archivo externo que contiene una secuencia de instrucciones. @@ -338,7 +338,7 @@ load('myFileName.mat') % Carga las variables guardadas en Workspace % M-file Functions % Al igual que los scripts, y tienen la misma extensión .m -% Pero puede aceptar argumentos de entrada y devolver una salida +% Pero pueden aceptar argumentos de entrada y devolver una salida % Además, tienen su propio espacio de trabajo (es decir, diferente alcance variable). % El nombre de la función debe coincidir con el nombre del archivo (por lo tanto, guarde este ejemplo como double_input.m). % 'help double_input.m' devuelve los comentarios en la línea que comienza la función @@ -374,16 +374,16 @@ fopen(filename) % Salida disp(a) % Imprime el valor de la variable a -disp('Hello World') % Imprime una cadena +disp('Hola Mundo') % Imprime una cadena fprintf % Imprime en la ventana de comandos con más control % Declaraciones condicionales (los paréntesis son opcionales, pero buen estilo) if (a > 15) - disp('Greater than 15') + disp('Mayor que 15') elseif (a == 23) - disp('a is 23') + disp('a es 23') else - disp('neither condition met') + disp('Ninguna condicion se ha cumplido') end % Bucles @@ -469,7 +469,7 @@ linspace(x1, x2, n) % Devuelve n puntos equiespaciados, con min x1 y max x2 inv(A) % Inverso de la matriz A det(A) % Determinante de A eig(A) % Valores propios y vectores propios de A -trace(A) % Traza de la matriz: equivalente a la suma (diag (A)) +trace(A) % Traza de la matriz: equivalente a sum(diag(A)) isempty(A) % Determina si la matriz está vacía all(A) % Determina si todos los elementos son distintos de cero o verdaderos any(A) % Determina si alguno de los elementos es distinto de cero o verdadero @@ -480,8 +480,8 @@ tril(x) % Devuelve la parte triangular inferior de x cross(A,B) % Devuelve el producto cruzado de los vectores A y B dot(A,B) % Devuelve un producto escalar de dos vectores (debe tener la misma longitud) transpose(A) % Devuelve la transposición de A -fliplr(A) % Voltee la matriz de izquierda a derecha -flipud(A) % Voltear la matriz de arriba hacia abajo +fliplr(A) % Voltea la matriz de izquierda a derecha +flipud(A) % Voltea la matriz de arriba hacia abajo % Factorizaciones de matrices [L, U, P] = lu(A) % Descomposición LU: PA = LU, L es triangular inferior, U es triangular superior, P es matriz de permutación @@ -494,7 +494,7 @@ min % componente más pequeño length % longitud de un vector sort % ordenar en orden ascendente sum % suma de elementos -prod % product of elements +prod % producto de elementos mode % valor modal median % valor mediano mean % valor medio @@ -507,7 +507,7 @@ find(x) % Encuentra todos los elementos distintos de cero de x y devuelve sus í % Clases % Matlab puede soportar programación orientada a objetos. -% Las clases deben colocarse en un archivo del nombre de la clase con una extensión .m. +% Las clases deben colocarse en un archivo del nombre de la clase con la extensión .m. % Para comenzar, creamos una clase simple para almacenar puntos de referencia de GPS. % Comience WaypointClass.m classdef WaypointClass % El nombre de la clase. @@ -540,7 +540,7 @@ end % Podemos crear un objeto de la clase usando el constructor a = WaypointClass(45.0, 45.0) -% Las propiedades de clase se comportan exactamente como Matlab Structures. +% Las propiedades de clase se comportan exactamente como estructuras de Matlab. a.latitude = 70.0 a.longitude = 25.0 -- cgit v1.2.3 From 85a98dc3af78cb5e860f478b08e754343a7518d0 Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Sun, 28 Oct 2018 04:14:45 -0400 Subject: Solve one unfinished translation & a tilde --- es-es/matlab-es.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index 99125b0c..9f1656bb 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -22,7 +22,7 @@ Si tiene algún comentario, no dude en ponerse en contacto el autor en % Los comentarios comienzan con un símbolo de porcentaje. %{ -Los Comentarios de multiples lineas se +Los Comentarios de multiples líneas se ven como esto @@ -33,7 +33,7 @@ esto % seguida por un clic en el botón de “Ejecutar Sección” % o usando Ctrl+Shift+Enter (Windows) o Cmd+Shift+Return (OS X) -%% This is the start of a code section +%% Este es el comienzo de una sección de código % Una forma de usar las secciones es separar un código de inicio costoso que no cambia, como cargar datos load learnmatlab.mat y -- cgit v1.2.3 From 067a5df121f3541539321a2a9f32713fd5ebb0f2 Mon Sep 17 00:00:00 2001 From: Bhoomtawath Plinsut Date: Tue, 27 Feb 2018 17:29:12 +0700 Subject: Fix solidity --- solidity.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index c0074b33..f654b470 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -109,10 +109,9 @@ contract SimpleBank { // CapWords /// @notice Get balance /// @return The balance of the user - // 'constant' prevents function from editing state variables; + // 'view' (ex: constant) prevents function from editing state variables; // allows function to run locally/off blockchain - // NOTE: 'constant' on functions is an alias to 'view', but this is deprecated and is planned to be dropped in version 0.5.0. - function balance() constant public returns (uint) { + function balance() view public returns (uint) { return balances[msg.sender]; } } @@ -342,25 +341,26 @@ function increment(uint x, uint y) returns (uint x, uint y) { // Call previous functon uint (a,b) = increment(1,1); -// 'constant' (alias for 'view') +// 'view' (alias for 'constant') // indicates that function does not/cannot change persistent vars -// Constant function execute locally, not on blockchain +// View function execute locally, not on blockchain +// Noted: constant keyword will soon be deprecated. uint y = 1; -function increment(uint x) constant returns (uint x) { +function increment(uint x) view returns (uint x) { x += 1; y += 1; // this line would fail - // y is a state variable, and can't be changed in a constant function + // y is a state variable, and can't be changed in a view function } -// 'pure' is more strict than 'constant', and does not +// 'pure' is more strict than 'view' or 'constant', and does not // even allow reading of state vars // The exact rules are more complicated, so see more about -// constant/pure: +// view/pure: // http://solidity.readthedocs.io/en/develop/contracts.html#view-functions // 'Function Visibility specifiers' -// These can be placed where 'constant' is, including: +// These can be placed where 'view' is, including: // public - visible externally and internally (default for function) // external - only visible externally (including a call made with this.) // private - only visible in the current contract -- cgit v1.2.3 From ecf0baab1ce6595b0c944d0b881614d8fd42aef9 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 28 Oct 2018 17:57:02 +0530 Subject: Add author name to contributor section --- solidity.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index f654b470..acf750f7 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -4,6 +4,7 @@ filename: learnSolidity.sol contributors: - ["Nemil Dalal", "https://www.nemil.com"] - ["Joseph Chow", ""] + - ["Bhoomtawath Plinsut", "https://github.com/varshard"] --- Solidity lets you program on [Ethereum](https://www.ethereum.org/), a -- cgit v1.2.3 From 3b536e441239431be4ea3ae9f51c4e72cec464f9 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Sun, 28 Oct 2018 11:52:57 -0500 Subject: [tmux/en] adding info about copy mode --- tmux.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/tmux.html.markdown b/tmux.html.markdown index 1214a5ba..b28a4f59 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -78,6 +78,7 @@ combinations called 'Prefix' keys. p # Change to the previous window { # Swap the current pane with the previous pane } # Swap the current pane with the next pane + ] # Enter Copy Mode to copy text or view history. s # Select a new session for the attached client interactively -- cgit v1.2.3 From f7242c2e6cb061c03619790827b0b8b3aab2b82f Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Sun, 28 Oct 2018 12:15:17 -0500 Subject: Enforcing 80 char linelength --- html.html.markdown | 111 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 83 insertions(+), 28 deletions(-) diff --git a/html.html.markdown b/html.html.markdown index 04b9f501..4d225aca 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -7,25 +7,41 @@ translators: - ["Robert Steed", "https://github.com/robochat"] --- -HTML stands for HyperText Markup Language. +HTML stands for HyperText Markup Language. + It is a language which allows us to write pages for the world wide web. -It is a markup language, it enables us to write webpages using code to indicate how text and data should be displayed. -In fact, html files are simple text files. -What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags. -This markup serves to give significance to the text that it encloses. -Like other computer languages, HTML has many versions. Here we will talk about HTML5. +It is a markup language, it enables us to write webpages using code to indicate +how text and data should be displayed. In fact, html files are simple text +files. + +What is this markup? It is a method of organising the page's data by +surrounding it with opening tags and closing tags. This markup serves to give +significance to the text that it encloses. Like other computer languages, HTML +has many versions. Here we will talk about HTML5. -**NOTE :** You can test the different tags and elements as you progress through the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see their effects, understand how they work and familiarise yourself with the language. -This article is concerned principally with HTML syntax and some useful tips. +**NOTE :** You can test the different tags and elements as you progress through +the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see +their effects, understand how they work and familiarise yourself with the +language. This article is concerned principally with HTML syntax and some +useful tips. ```html + + - + + @@ -33,7 +49,9 @@ This article is concerned principally with HTML syntax and some useful tips.

Hello, world!

- Come look at what this shows + + Come look at what this shows +

This is a paragraph.

This is another paragraph.

    @@ -44,7 +62,9 @@ This article is concerned principally with HTML syntax and some useful tips. - + @@ -58,10 +78,17 @@ This article is concerned principally with HTML syntax and some useful tips. - + - My Site + + My Site @@ -69,13 +96,28 @@ This article is concerned principally with HTML syntax and some useful tips. -

    Hello, world!

    - - Come look at what this shows -

    This is a paragraph.

    + +

    Hello, world!

    + + + + + Come look at what this shows + + + +

    This is a paragraph.

    This is another paragraph.

    -
      - + + + +
      • This is an item in a non-enumerated list (bullet list)
      • This is another item
      • And this is the last item on the list
      • @@ -86,21 +128,33 @@ This article is concerned principally with HTML syntax and some useful tips. - - - + + + - - - + +
        First Header
        + + + + + + + - + + + + @@ -111,9 +165,10 @@ This article is concerned principally with HTML syntax and some useful tips. ## Usage -HTML is written in files ending with `.html` or `.htm`. The mime type is `text/html`. +HTML is written in files ending with `.html` or `.htm`. The mime type is +`text/html`. -## To Learn More +## To Learn More * [wikipedia](https://en.wikipedia.org/wiki/HTML) * [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) -- cgit v1.2.3 From 7825aa838433851d03c393bceb06716bdcfafb66 Mon Sep 17 00:00:00 2001 From: Will L Fife Date: Sun, 28 Oct 2018 11:31:13 -0700 Subject: Multiple changes - Remove double newlines - Merge lists - fix locations where lines are > 80 chars. - Remove excess whitespace in table --- mercurial.html.markdown | 122 +++++++++++++++++++----------------------------- 1 file changed, 49 insertions(+), 73 deletions(-) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index f757dd7c..d1cac66c 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -18,82 +18,58 @@ anyone working with versioned files. Version control is a system that keeps track fo changes to a set of file(s) and/or directorie(s) over time. - ### Why Use Mercurial -* Distributed Architecture -* Fast -* Platform Independent -* Extensible -* Easy to use -* Open Source - - -#### Distributed Architecture - -Traditionally version control systems such as CVS and Subversion are a client server -architecture with a central server to store the revsion history of a project. Mercurial however -is a truly distributed architecture, giving each devloper a full local copy of the entire -development history. It works independently of a central server. - - -#### Fast - -Mercurial is implemented to be fast. You are able to generate diffs between -revsions, and switch between tags and branches with little time and effort. -Mercurial is used by large projects such as OpenJDK -([hg](http://hg.openjdk.java.net/jdk7/jdk7)) and NetBeans -([hg](http://hg.netbeans.org/)). - -#### Platform Independent - -Mercurial was written to be highly platform independent. Much of Mercurial is -written in Python, with small performance critical parts written in portable -C. Binary releases are available for all major platforms. - - -#### Extensible - -The functionality of Mercurial can be increased with extensions, either by -activating the official ones which are shipped with Mercurial or downloading -some [from the wiki](https://www.mercurial-scm.org/wiki/UsingExtensions) or by -[writing your own](https://www.mercurial-scm.org/wiki/WritingExtensions). -Extensions are written in Python and can change the workings of the basic -commands, add new commands and access all the core functions of Mercurial. - - -#### Easy to Use - -The Mercurial command set is consistent with what subversion users would -expect, so they are likely to feel right at home. Most dangerous actions -are part of extensions that need to be enabled to be used. - - -#### Open Source - -Mercurial is free software licensed under the terms of the [GNU General Public -License Version 2](http://www.gnu.org/licenses/gpl-2.0.txt) or any later -version. - +* Distributed Architecture - Traditionally version control systems such as CVS +and Subversion are a client server architecture with a central server to +store the revsion history of a project. Mercurial however is a truly +distributed architecture, giving each devloper a full local copy of the +entire development history. It works independently of a central server. + +* Fast - Traditionally version control systems such as CVS and Subversion are a +client server architecture with a central server to store the revsion history +of a project. Mercurial however is a truly distributed architecture, giving +each devloper a full local copy of the entire development history. It works +independently of a central server. + +* Platform Independent - Mercurial was written to be highly platform +independent. Much of Mercurial is written in Python, with small performance +critical parts written in portable C. Binary releases are available for all +major platforms. + +* Extensible - The functionality of Mercurial can be increased with extensions, +either by activating the official ones which are shipped with Mercurial or +downloading some [from the +wiki](https://www.mercurial-scm.org/wiki/UsingExtensions) or by [writing your +own](https://www.mercurial-scm.org/wiki/WritingExtensions). Extensions are +written in Python and can change the workings of the basic commands, add new +commands and access all the core functions of Mercurial. + +* Easy to use - The Mercurial command set is consistent with what subversion +users would expect, so they are likely to feel right at home. Most dangerous +actions are part of extensions that need to be enabled to be used. + +* Open Source - Mercurial is free software licensed under the terms of the [GNU +General Public License Version 2](http://www.gnu.org/licenses/gpl-2.0.txt) or +any later version. ## Terminology -| Term | Definition | +| Term | Definition | | ------------- | ---------------------------------- | -| Repository | A repository is a collection of revisions | -| hgrc | A configuration file which stores the defaults for a repository. | -| revision | A committed changeset: has a REV number | -| changeset | Set of changes saved as diffs | -| diff | Changes between file(s) | -| tag | A named named revision | -| parent(s) | Immediate ancestor(s) of a revison | -| branch | A child of a revision | -| head | A head is a changeset with no child changesets | -| merge | The process of merging two HEADS | -| tip | The latest revision in any branch | -| patch | All of the diffs between two revisions | -| bundle | Patch with permis­sions and rename support | - +| Repository | A repository is a collection of revisions | +| hgrc | A configuration file which stores the defaults for a repository. | +| revision | A committed changeset: has a REV number | +| changeset | Set of changes saved as diffs | +| diff | Changes between file(s) | +| tag | A named named revision | +| parent(s) | Immediate ancestor(s) of a revison | +| branch | A child of a revision | +| head | A head is a changeset with no child changesets | +| merge | The process of merging two HEADS | +| tip | The latest revision in any branch | +| patch | All of the diffs between two revisions | +| bundle | Patch with permis­sions and rename support | ## Commands @@ -133,7 +109,6 @@ $ hg status # Get help on the status subcommand $ hg help status - ``` ### add @@ -227,7 +202,8 @@ $ hg commit --amend -m "Correct message" ### diff -Show differences between revisions for the specified files using the unified diff format. +Show differences between revisions for the specified files using the unified +diff format. ```bash # Show the diff between the current directory and a previous revision @@ -384,4 +360,4 @@ $ hg remove *.txt * [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guid) * [Mercurial Quick Start](https://www.mercurial-scm.org/wiki/QuickStart) -* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) +* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) \ No newline at end of file -- cgit v1.2.3 From 8aadea8c05698d5062d50b2a2c6af1189d018d57 Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Sun, 28 Oct 2018 22:48:42 -0600 Subject: PyQT Spanish translation --- es-es/pyqt-es.html.markdown | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 es-es/pyqt-es.html.markdown diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown new file mode 100644 index 00000000..2cbc4153 --- /dev/null +++ b/es-es/pyqt-es.html.markdown @@ -0,0 +1,89 @@ +--- +category: tool +tool: PyQT +filename: learnpyqt.py +contributors: + - ["Nathan Hughes", "https://github.com/sirsharpest"] +translators: + - ["Adrian Rocamora", "https://github.com/adrianrocamora"] +--- + +**Qt** es un sistema altamente reconocido que permite desarrollar software multiplataforma que puede correr en diferentes entornos de software y hardware con pocos o ningún cambio. Aun así conserva la velocidad y poder de una palicacion nativa. **Qt** fue originalmente escrito en *C++*. + + +This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192 +), some of the code examples should result in the same functionality +this version just having been done using pyqt! + +Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk](https://github.com/vortexxx192), parte del código ejemplo debería resultar en la misma funcionalidad ¡pero usando python con PyQT! + +```python +import sys +from PyQt4 import QtGui + +def window(): + # Crear el objeto de la aplicación + app = QtGui.QApplication(sys.argv) + # Crear un widget en el que colocaremos nuestra etiqueta + w = QtGui.QWidget() + # Agregamos nuesta etiqueta al widget + b = QtGui.QLabel(w) + # Agregamos texto a nuestra etiqueta + b.setText("Hello World!") + # Fijemos información de posición y tamaño del widget + w.setGeometry(100, 100, 200, 50) + b.move(50, 20) + # Proporcionemos un título a nuestra ventana + w.setWindowTitle("PyQt") + # Mostremos todo + w.show() + # Ejecutemos lo que hayamos solicitado ya inicializado el resto + sys.exit(app.exec_()) + +if __name__ == '__main__': + window() + +``` + +In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. +Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information. + +Para poder hacer uso de las funciones más avanzades en **pyqt** necestiamos agregar elementos adicionales. +Aquí mostramos cómo introducir una caja de dialogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información. + +```Python +import sys +from PyQt4.QtGui import * +from PyQt4.QtCore import * + + +def window(): + app = QApplication(sys.argv) + w = QWidget() + # Crear un botón y adjuntarlo al widget w + b = QPushButton(w) + b.setText("Press me") + b.move(50, 50) + # Indicar al botón b que llame esta función cuando reciba un click + # Nótese la falta de "()" en la llamada de la función + b.clicked.connect(showdialog) + w.setWindowTitle("PyQt Dialog") + w.show() + sys.exit(app.exec_()) + +# Esta funcion debería crear una ventana de diálogo con un botón +# que espera a recibir un click y luego sale del programa +def showdialog(): + d = QDialog() + b1 = QPushButton("ok", d) + b1.move(50, 50) + d.setWindowTitle("Dialog") + # Esta modalidad le indica al popup que bloquee al padre mientras esté activo + d.setWindowModality(Qt.ApplicationModal) + # Al recibir un click me gustaría que el proceso termine + b1.clicked.connect(sys.exit) + d.exec_() + +if __name__ == '__main__': + window() +``` -- cgit v1.2.3 From 9458db1072dab5bd0e0a274be879925178672b13 Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Mon, 29 Oct 2018 00:49:20 -0400 Subject: Initial es-es translation for lambda --- es-es/lambda-calculus-es.html.markdown | 215 +++++++++++++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 es-es/lambda-calculus-es.html.markdown diff --git a/es-es/lambda-calculus-es.html.markdown b/es-es/lambda-calculus-es.html.markdown new file mode 100644 index 00000000..56d4c02e --- /dev/null +++ b/es-es/lambda-calculus-es.html.markdown @@ -0,0 +1,215 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] + - ["Yan Hui Hang", "http://github.com/yanhh0"] +translators: + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +--- + +# Cálculo Lambda + +Cálculo Lambda (Cálculo-λ), originalmente creado por +[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +es el lenguaje de programación más pequeño del mundo. +A pesar de no tener números, cadenas, valores booleanos o cualquier +tipo de datos no funcional, el cálculo lambda se puede utilizar para +representar cualquier máquina de Turing. + +El cálculo lambda se compone de 3 elementos: **variables**, **funciones** y +**aplicaciones**. + +| Nombre | Sintaxis | Ejemplo | Explicación | +|-------------|------------------------------------|-----------|-----------------------------------------------| +| Variable | `` | `x` | una variable llamada "x" | +| Función | `λ.` | `λx.x` | una función con parametro "x" y cuerpo "x" | +| Aplicación | `` | `(λx.x)a` | llamando a la función "λx.x" con el argumento "a" | + +La función más básica es la función de identidad: `λx.x` que es equivalente a +`f(x) = x`. La primera "x" es el argumento de la función y la segunda es el +cuerpo de la función. + +## Variables Libres vs. Enlazadas: + +- En la función `λx.x`, "x" se llama una variable enlazada porque está tanto en + el cuerpo de la función como en el parámetro. +- En `λx.y`, "y" se llama variable libre porque nunca se declara de antemano. + +## Evaluación: + +Evaluación se realiza a través de +[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +que es, esencialmente, sustitución de ámbito léxico. + +Al evaluar la expresión `(λx.x)a`, reemplazamos todas las ocurrencias de "x" +en el cuerpo de la función con "a". + +- `(λx.x)a` evalúa a: `a` +- `(λx.y)a` evalúa a: `y` + +Incluso puedes crear funciones de orden superior: + +- `(λx.(λy.x))a` evalúa a: `λy.a` + +Aunque el cálculo lambda tradicionalmente solo admite funciones +de un solo parámetro, podemos crear funciones multiparamétricas usando +una técnica llamada [currying](https://en.wikipedia.org/wiki/Currying). + +- `(λx.λy.λz.xyz)` es equivalente a `f(x, y, z) = ((x y) z)` + +Algunas veces `λxy.` es usado indistintamente con: `λx.λy.` + +---- + +Es importante reconocer que el cálculo lambda tradicional **no tiene números, +caracteres ni ningún tipo de datos que no sea de función.** + +## Lógica Booleana: + +No hay "Verdadero" o "Falso" en el cálculo lambda. Ni siquiera hay un 1 o un 0. + +En vez: + +`T` es representado por: `λx.λy.x` + +`F` es representado por: `λx.λy.y` + +Primero, podemos definir una función "if" `λbtf` que devuelve +`t` si `b` es Verdadero y `f` si `b` es Falso + +`IF` es equivalente a: `λb.λt.λf.b t f` + +Usando `IF` podemos definir los operadores lógicos booleanos básicos: + +`a AND b` es equivalente a: `λab.IF a b F` + +`a OR b` es equivalente a: `λab.IF a T b` + +`a NOT b` es equivalente a: `λa.IF a F T` + +*Note: `IF a b c` es esencialmente diciendo: `IF((a b) c)`* + +## Numeros: + +Aunque no hay números en el cálculo lambda, podemos codificar números usando +[Númeral de Church](https://en.wikipedia.org/wiki/Church_encoding). + +Para cualquier número n: n = λf.f n así: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +Para incrementar un númeral de Church, usamos la función sucesora +`S(n) = n + 1` que es: + +`S = λn.λf.λx.f((n f) x)` + +Usando el sucesor, podemos definir AGREGAR: + +`AGREGAR = λab.(a S)n` + +**Desafío:** intenta definir tu propia función de multiplicación! + +## Vamos más pequeño: SKI, SK y Iota + +### Combinador de SKI + +Sean S, K, I las siguientes funciones: + +`I x = x` + +`K x y = x` + +`S x y z = x z (y z)` + +Podemos convertir una expresión en el cálculo lambda en una expresión +en el cálculo del combinador de SKI: + +1. `λx.x = I` +2. `λx.c = Kc` +3. `λx.(y z) = S (λx.y) (λx.z)` + +Tome el número 2 de Church por ejemplo: + +`2 = λf.λx.f(f x)` + +Para la parte interior `λx.f(f x)`: +``` + λx.f(f x) += S (λx.f) (λx.(f x)) (case 3) += S (K f) (S (λx.f) (λx.x)) (case 2, 3) += S (K f) (S (K f) I) (case 2, 1) +``` + +Asi que: +``` + 2 += λf.λx.f(f x) += λf.(S (K f) (S (K f) I)) += λf.((S (K f)) (S (K f) I)) += S (λf.(S (K f))) (λf.(S (K f) I)) (case 3) +``` + +Para el primer argumento `λf.(S (K f))`: +``` + λf.(S (K f)) += S (λf.S) (λf.(K f)) (case 3) += S (K S) (S (λf.K) (λf.f)) (case 2, 3) += S (K S) (S (K K) I) (case 2, 3) +``` + +Para el segundo argumento `λf.(S (K f) I)`: +``` + λf.(S (K f) I) += λf.((S (K f)) I) += S (λf.(S (K f))) (λf.I) (case 3) += S (S (λf.S) (λf.(K f))) (K I) (case 2, 3) += S (S (K S) (S (λf.K) (λf.f))) (K I) (case 1, 3) += S (S (K S) (S (K K) I)) (K I) (case 1, 2) +``` + +Uniéndolos: +``` + 2 += S (λf.(S (K f))) (λf.(S (K f) I)) += S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I)) +``` + +Al expandir esto, terminaríamos con la misma expresión para el número 2 de Church nuevamente. + +### Cálculo del combinador SKI + +El cálculo del combinador SKI puede reducirse aún más. Podemos eliminar +el combinador I observando que `I = SKK`. Podemos sustituir +todos los 'I' con `SKK`. + +### Combinador Iota + +El cálculo del combinador SK todavía no se encuentra en su expresión mínima. +Definiendo: + +``` +ι = λf.((f S) K) +``` + +Tenemos que: + +``` +I = ιι +K = ι(ιI) = ι(ι(ιι)) +S = ι(K) = ι(ι(ι(ιι))) +``` + +## Para una lectura más avanzada: + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) +5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) -- cgit v1.2.3 From b5929c289dd9d0e7f9a854939b03ff047cf0acfb Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Sun, 28 Oct 2018 22:53:03 -0600 Subject: 80 cols fix --- es-es/pyqt-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 2cbc4153..407a2933 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -78,7 +78,7 @@ def showdialog(): b1 = QPushButton("ok", d) b1.move(50, 50) d.setWindowTitle("Dialog") - # Esta modalidad le indica al popup que bloquee al padre mientras esté activo + # Esta modalidad le indica al popup que bloquee al padre mientras activo d.setWindowModality(Qt.ApplicationModal) # Al recibir un click me gustaría que el proceso termine b1.clicked.connect(sys.exit) -- cgit v1.2.3 From c021c15692c36ed09bf90e8b3481a59b4377e236 Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Sun, 28 Oct 2018 22:56:21 -0600 Subject: Removed leftover English content --- es-es/pyqt-es.html.markdown | 8 -------- 1 file changed, 8 deletions(-) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 407a2933..be9704e2 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -10,11 +10,6 @@ translators: **Qt** es un sistema altamente reconocido que permite desarrollar software multiplataforma que puede correr en diferentes entornos de software y hardware con pocos o ningún cambio. Aun así conserva la velocidad y poder de una palicacion nativa. **Qt** fue originalmente escrito en *C++*. - -This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192 -), some of the code examples should result in the same functionality -this version just having been done using pyqt! - Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk](https://github.com/vortexxx192), parte del código ejemplo debería resultar en la misma funcionalidad ¡pero usando python con PyQT! ```python @@ -45,9 +40,6 @@ if __name__ == '__main__': ``` -In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. -Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information. - Para poder hacer uso de las funciones más avanzades en **pyqt** necestiamos agregar elementos adicionales. Aquí mostramos cómo introducir una caja de dialogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información. -- cgit v1.2.3 From ee2a35a980f8003c67f6c61ae82d4d0c06152be2 Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Sun, 28 Oct 2018 22:59:58 -0600 Subject: Spacing fixes --- es-es/pyqt-es.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index be9704e2..6f880547 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -17,22 +17,22 @@ import sys from PyQt4 import QtGui def window(): - # Crear el objeto de la aplicación + # Crear el objeto de la aplicación app = QtGui.QApplication(sys.argv) - # Crear un widget en el que colocaremos nuestra etiqueta + # Crear un widget en el que colocaremos nuestra etiqueta w = QtGui.QWidget() - # Agregamos nuesta etiqueta al widget + # Agregamos nuesta etiqueta al widget b = QtGui.QLabel(w) - # Agregamos texto a nuestra etiqueta + # Agregamos texto a nuestra etiqueta b.setText("Hello World!") - # Fijemos información de posición y tamaño del widget + # Fijemos información de posición y tamaño del widget w.setGeometry(100, 100, 200, 50) b.move(50, 20) - # Proporcionemos un título a nuestra ventana + # Proporcionemos un título a nuestra ventana w.setWindowTitle("PyQt") - # Mostremos todo + # Mostremos todo w.show() - # Ejecutemos lo que hayamos solicitado ya inicializado el resto + # Ejecutemos lo que hayamos solicitado ya inicializado el resto sys.exit(app.exec_()) if __name__ == '__main__': -- cgit v1.2.3 From d3c2d89f9ef7213238b649c24629575db50fe8ab Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Sun, 28 Oct 2018 23:01:55 -0600 Subject: Missing accent --- es-es/pyqt-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 6f880547..30b7b71f 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -63,7 +63,7 @@ def window(): w.show() sys.exit(app.exec_()) -# Esta funcion debería crear una ventana de diálogo con un botón +# Esta función debería crear una ventana de diálogo con un botón # que espera a recibir un click y luego sale del programa def showdialog(): d = QDialog() -- cgit v1.2.3 From 816047086834dc6ebb72e46bebc7d4b3e725d9b8 Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Mon, 29 Oct 2018 03:25:13 -0400 Subject: Initial es-es translation for Pascal --- es-es/pascal-es.html.markdown | 204 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 es-es/pascal-es.html.markdown diff --git a/es-es/pascal-es.html.markdown b/es-es/pascal-es.html.markdown new file mode 100644 index 00000000..d1e0345a --- /dev/null +++ b/es-es/pascal-es.html.markdown @@ -0,0 +1,204 @@ +--- +language: Pascal +filename: learnpascal.pas +contributors: + - ["Ganesha Danu", "http://github.com/blinfoldking"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +--- + + +>Pascal es un lenguaje de programación imperativo y de procedimiento, que Niklaus Wirth diseñó en 1968–69 y publicó en 1970, como un lenguaje pequeño y eficiente destinado a fomentar las buenas prácticas de programación utilizando programación estructurada y estructuración de datos. Se nombra en honor al matemático, filósofo y físico francés Blaise Pascal. fuente: [wikipedia](https://en.wikipedia.org/wiki/Pascal_(programming_language)) + +Para compilar y ejecutar un programa pascal puede usar un compilador pascal gratuito. [Descargar aquí](https://www.freepascal.org/) + +```pascal +//Anatomía de un programa en Pascal +//Esto es un comentario +{ + Esto es un + comentario multilínea +} + +//nombre del programa +program learn_pascal; //<-- no olvides el punto y coma + +const + { + Aquí es donde se debe declarar valores constantes. + } +type + { + Aquí es donde se debe declarar un tipo de datos personalizado + } +var + { + aquí es donde se debe declarar una variable + } + +//área principal del programa +begin + { + área para declarar su instrucción + } +end. // El final de un área principal del programa debe requerir un símbolo "." +``` + +```pascal +//declarando variable +//puedes hacer esto +var a:integer; +var b:integer; +//o esto +var + a : integer; + b : integer; +//o esto +var a,b : integer; +``` + +```pascal +program Learn_More; +//Aprendamos sobre los tipos de datos y sus operaciones. + +const + PI = 3.141592654; + GNU = 'GNU's Not Unix'; + // las constantes se nombran convencionalmente usando CAPS (mayúscula) + // sus valores son fijos y no se pueden cambiar durante el tiempo de ejecución + // tiene cualquier tipo de datos estándar (enteros, reales, booleanos, characteres, cadenas) + +type + ch_array : array [0..255] of char; + // los son nuevos 'tipos' que especifican la longitud y el tipo de datos + // esto define un nuevo tipo de datos que contiene 255 caracteres + // (esto es funcionalmente equivalente a una variable string[256]) + md_array : array of array of integer; + // los arreglos anidados son equivalentes a los arreglos multidimensionales + // puede definir arreglos de longitud cero (0) que son de tamaño dinámico + // esta es una matriz bidimensional de enteros + +//Declarando variables +var + int, c, d : integer; + // Tres variables que contienen números enteros. + // los enteros son de 16 bits y están limitados al rango [-32,768..32,767] + r : real; + // una variable que contiene un número real como tipos de datos + // el rango de los reales pueden variar entre [3.4E-38..3.4E38] + bool : boolean; + // una variable que contiene un valor booleano (True/False) + ch : char; + // una variable que contiene un valor de carácter + // Las variables char se almacenan como tipos de datos de 8 bits, por lo que no hay UTF + str : string; + // una variable no estándar que contiene un valor de cadena + // Las cadenas son una extensión incluida en la mayoría de los compiladores de Pascal. + // se almacenan como una matriz de caracteres con una longitud predeterminada de 255. + s : string[50]; + // una cadena con longitud máxima de 50 caracteres. + // puede especificar la longitud de la cadena para minimizar el uso de memoria + my_str: ch_array; + // Puedes declarar variables de tipos personalizados. + my_2d : md_array; + // Las matrices de tamaño dinámico deben dimensionarse antes de que puedan usarse. + + // tipos de datos enteros adicionales + b : byte; // rango [0..255] + shi : shortint; // rango [-128..127] + smi : smallint; // rango [-32,768..32,767] (entero estandar) + w : word; // rango [0..65,535] + li : longint; // rango [-2,147,483,648..2,147,483,647] + lw : longword; // rango [0..4,294,967,295] + c : cardinal; // longword + i64 : int64; // rango [-9223372036854775808..9223372036854775807] + qw : qword; // rango [0..18,446,744,073,709,551,615] + + // tipos reales adicionales + rr : real; // rango depende de la plataforma (i.e., 8-bit, 16-bit, etc.) + rs : single; // rango [1.5E-45..3.4E38] + rd : double; // rango [5.0E-324 .. 1.7E308] + re : extended; // rango [1.9E-4932..1.1E4932] + rc : comp; // rango [-2E64+1 .. 2E63-1] + +Begin + int := 1;// como asignar un valor a una variable + r := 3.14; + ch := 'a'; + str := 'manzana'; + bool := true; + //pascal no es un lenguaje sensible a mayúsculas y minúsculas + //operación aritmética + int := 1 + 1; // int = 2 sobrescribiendo la asignacion anterior + int := int + 1; // int = 2 + 1 = 3; + int := 4 div 2; //int = 2 operación de división donde el resultado será redondeado. + int := 3 div 2; //int = 1 + int := 1 div 2; //int = 0 + + bool := true or false; // bool = true + bool := false and true; // bool = false + bool := true xor true; // bool = false + + r := 3 / 2; // un operador de división para reales + r := int; // Puede asignar un entero a una variable real pero no a la inversa + + c := str[1]; // asigna la primera letra de str a c + str := 'hola' + 'mundo'; // combinando cadenas + + my_str[0] := 'a'; // asignación de matriz necesita un índice + + setlength(my_2d,10,10); // inicializa matrices de tamaño dinámico: matriz 10 × 10 + for c := 0 to 9 do // los arreglos comienzan en 0 y terminan en longitud - 1 + for d := 0 to 9 do // Para los contadores de bucle hay que declarar variables. + my_2d[c,d] := c * d; + // aborda las matrices multidimensionales con un único conjunto de corchete + +End. +``` + +```pascal +program Functional_Programming; + +Var + i, dummy : integer; + +function factorial_recursion(const a: integer) : integer; +{ calcula recursivamente el factorial del parámetro entero a } + +// Declare variables locales dentro de la función. +// e.g.: +// Var +// local_a : integer; + +Begin + If a >= 1 Then + // devuelva valores de las funciones asignando un valor al nombre de la función + factorial_recursion := a * factorial_recursion(a-1) + Else + factorial_recursion := 1; +End; // termine una función usando un punto y coma después de la instrucción End. + +procedure get_integer(var i : integer; dummy : integer); +{ obten la entrada del usuario y almacenarla en el parámetro entero i. + los parámetros que preceden a 'var' son variables, lo que significa que su valor + puede cambiar fuera del parámetro. Los parámetros de valor (sin 'var') como 'dummy' + son estáticos y los cambios realizados dentro del alcance de la función/procedimiento + no afectan la variable que se pasa como parámetro } + +Begin + write('Escriba un entero: '); + readln(i); + dummy := 4; // dummy no cambiará el valor fuera del procedimiento +End; + +Begin // bloque de programa principal + dummy := 3; + get_integer(i, dummy); + writeln(i, '! = ', factorial_recursion(i)); + // outputs i! + writeln('dummy = ', dummy); // siempre muestra '3' ya que dummy no ha cambiado. +End. + +``` + -- cgit v1.2.3 From a7ff86c11f09dedbdbcfef8930c3214cd3becf99 Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Mon, 29 Oct 2018 10:42:10 +0100 Subject: rearange text to make it more readable rearange text to make it more readable --- de-de/git-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index d2222d2c..7c68d785 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -20,7 +20,7 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. -### Zentrale im Vergleich mit verteilter Versionverwaltung +### Vergleich zwischen Zentraler und verteilter Versionverwaltung * Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. * Verteilte Versionsverwaltung konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. -- cgit v1.2.3 From 01a2a75933ac337a31c2700618c61c067545caae Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Mon, 29 Oct 2018 12:06:57 +0100 Subject: wrong use of and wrong use of and --- de-de/asciidoc-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown index 60f8fa61..24100e0b 100644 --- a/de-de/asciidoc-de.html.markdown +++ b/de-de/asciidoc-de.html.markdown @@ -104,7 +104,7 @@ Um eine nummerierte Liste zu erstellen verwendest du Punkte. . item 3 ``` -Um Listen zu verschachteln musst du zusätzliche Sternchen und Punkte hinzufügen. Dies ist bis zu fünf Mal möglich. +Um Listen zu verschachteln musst du zusätzliche Sternchen beziehungsweise Punkte hinzufügen. Dies ist bis zu fünf Mal möglich. ``` * foo 1 -- cgit v1.2.3 From 4def7beeab6d82eb256e9266b4be884c644dd595 Mon Sep 17 00:00:00 2001 From: Bob DuCharme Date: Mon, 29 Oct 2018 18:16:47 -0400 Subject: Adding SQL entry --- sql.html.markdown | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 sql.html.markdown diff --git a/sql.html.markdown b/sql.html.markdown new file mode 100644 index 00000000..0dc07eb5 --- /dev/null +++ b/sql.html.markdown @@ -0,0 +1,106 @@ +--- +language: SQL +filename: learnsql.sql +contributors: +- ["Bob DuCharme", "http://bobdc.com/"] +lang: en-en +--- + +Structured Query Language (SQL) is an ISO standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences. + +Implementations typically provide a command line prompt where you can enter the commands shown here interactively, and they also offer a way to execute a series of these commands stored in a script file. (Showing that you’re done with the interactive prompt is a good example of something that isn’t standardized--most SQL implementations support the keywords QUIT, EXIT, or both.) + +Several of these sample commands assume that the [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/) available on [github](https://github.com/datacharmer/test_db) has already been loaded. The github files are scripts of commands, similar to the relevant commands below, that create and populate tables of data about a fictional company’s employees. The syntax for running these scripts will depend on the SQL implementation you are using. A utility that you run from the operating system prompt is typical. + + +``` +# Comments start with a pound sign. End each command with a semicolon. + +# SQL is not case-sensitive about keywords. The sample commands here +# follow the convention of spelling them in upper-case because it makes +# it easier to distinguish them from database, table, and column names. + +# Create and delete a database. Database and table names are case-sensitive. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +# List available databases. +SHOW DATABASES; + +# Use a particular existing database. +USE employees; + +# Select all rows and columns from the current database's departments table. +# Default activity is for the interpreter to scroll the results on your screen. +SELECT * FROM departments; + +# Retrieve all rows from the departments table, +# but only the dept_no and dept_name columns. +# Splitting up commands across lines is OK. +SELECT dept_no, + dept_name FROM departments; + +# Retrieve all departments columns, but just 5 rows. +SELECT * FROM departments LIMIT 5; + +# Retrieve dept_name column values from the departments +# table where the dept_name value has the substring "en". +SELECT dept_name FROM departments WHERE dept_name LIKE "%en%"; + +# Retrieve all columns from the departments table where the dept_name +# column starts with an "S" and has exactly 4 characters after it. +SELECT * FROM departments WHERE dept_name LIKE "S____"; + +# Select title values from the titles table but don't show duplicates. +SELECT DISTINCT title FROM titles; + +# Same as above, but sorted (case-sensitive) by the title values. +SELECT DISTINCT title FROM titles ORDER BY title; + +# Show the number of rows in the departments table. +SELECT COUNT(*) FROM departments; + +# Show the number of rows in the departments table that +# have "en" as a substring of the dept_name value. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE "%en%"; + +# A JOIN of information from multiple tables: the titles table shows +# who had what job titles, by their employee numbers, from what +# date to what date. Retrieve this information, but instead of the +# employee number, use the employee number as a cross-reference to +# the employees table to get each employee's first and last name +# instead. (And only get 10 rows.) + +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +# List all the tables in all the databases. Implementations typically provide +# their own shortcut command to do this with the database currently in use. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +# Create a table called tablename1, with the two columns shown, for +# the database currently in use. Lots of other options are available +# for how you specify the columns, such as their datatypes. +CREATE TABLE tablename1 (`fname` VARCHAR(20),`lname` VARCHAR(20)); + +# Insert a row of data into the table tablename1. This assumes that the +# table has been defined to accept these values as appropriate for it. +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +# In tablename1, change the fname value to "John" +# for all rows that have an lname value of "Mutt". +UPDATE tablename1 SET fname="John" WHERE lname="Mutt"; + +# Delete rows from the tablename1 table +# where the lname value begins with "M". +DELETE FROM tablename1 WHERE lname like "M%"; + +# Delete all rows from the tablename1 table, leaving the empty table. +DELETE FROM tablename1; + +# Remove the entire tablename1 table. +DROP TABLE tablename1; +``` -- cgit v1.2.3 From 1aefbde39eb79a9c8c8a4944522851ab465ee65b Mon Sep 17 00:00:00 2001 From: Adrian Rocamora Date: Tue, 30 Oct 2018 11:29:30 -0600 Subject: Fixes requested by maintainer --- es-es/pyqt-es.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 30b7b71f..1d2f0fe3 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -1,14 +1,14 @@ --- category: tool tool: PyQT -filename: learnpyqt.py +filename: learnpyqt-es.py contributors: - ["Nathan Hughes", "https://github.com/sirsharpest"] translators: - ["Adrian Rocamora", "https://github.com/adrianrocamora"] --- -**Qt** es un sistema altamente reconocido que permite desarrollar software multiplataforma que puede correr en diferentes entornos de software y hardware con pocos o ningún cambio. Aun así conserva la velocidad y poder de una palicacion nativa. **Qt** fue originalmente escrito en *C++*. +**Qt** es un sistema altamente reconocido que permite desarrollar software multiplataforma que puede correr en diferentes entornos de software y hardware con pocos o ningún cambio. Aun así conserva la velocidad y poder de una aplicación nativa. **Qt** fue originalmente escrito en *C++*. Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk](https://github.com/vortexxx192), parte del código ejemplo debería resultar en la misma funcionalidad ¡pero usando python con PyQT! @@ -21,7 +21,7 @@ def window(): app = QtGui.QApplication(sys.argv) # Crear un widget en el que colocaremos nuestra etiqueta w = QtGui.QWidget() - # Agregamos nuesta etiqueta al widget + # Agregamos nuestra etiqueta al widget b = QtGui.QLabel(w) # Agregamos texto a nuestra etiqueta b.setText("Hello World!") @@ -40,8 +40,8 @@ if __name__ == '__main__': ``` -Para poder hacer uso de las funciones más avanzades en **pyqt** necestiamos agregar elementos adicionales. -Aquí mostramos cómo introducir una caja de dialogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información. +Para poder hacer uso de las funciones más avanzades en **pyqt** necesitamos agregar elementos adicionales. +Aquí mostramos cómo introducir una caja de diálogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información. ```Python import sys -- cgit v1.2.3 From a41c5d77c29c6775e060a1f559584810e1390bd8 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Tue, 30 Oct 2018 12:40:01 -0500 Subject: Updating the line length to 80 --- typescript.html.markdown | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 9158f123..6feaca45 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -5,13 +5,19 @@ contributors: filename: learntypescript.ts --- -TypeScript is a language that aims at easing development of large scale applications written in JavaScript. -TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. +TypeScript is a language that aims at easing development of large scale +applications written in JavaScript. TypeScript adds common concepts such as +classes, modules, interfaces, generics and (optional) static typing to +JavaScript. It is a superset of JavaScript: all JavaScript code is valid +TypeScript code so it can be added seamlessly to any project. The TypeScript +compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](/docs/javascript). +This article will focus only on TypeScript extra syntax, as opposed to +[JavaScript](/docs/javascript). -To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. +To test TypeScript's compiler, head to the +[Playground] (http://www.typescriptlang.org/Playground) where you will be able +to type code, have auto completion and directly see the emitted JavaScript. ```ts // There are 3 basic types in TypeScript @@ -19,7 +25,8 @@ let isDone: boolean = false; let lines: number = 42; let name: string = "Anders"; -// But you can omit the type annotation if the variables are derived from explicit literals +// But you can omit the type annotation if the variables are derived +// from explicit literals let isDone = false; let lines = 42; let name = "Anders"; @@ -114,7 +121,7 @@ class Point { } // Classes can be explicitly marked as implementing an interface. -// Any missing properties will then cause an error at compile-time. +// Any missing properties will then cause an error at compile-time. class PointPerson implements Person { name: string move() {} -- cgit v1.2.3 From 70a2200201f4d3d91ca9f08902dd16d653b10cd2 Mon Sep 17 00:00:00 2001 From: Will Fife Date: Tue, 30 Oct 2018 13:04:56 -0700 Subject: Update Ansible docs (#3353) - Add the additional resources section - change instances of ```yml to ```yaml for consistency - Remove extra trailing whitespace --- ansible.html.markdown | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index a319a89d..cb365e0f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,7 +6,7 @@ contributors: filename: LearnAnsible.txt --- -```yml +```yaml --- "{{ Ansible }}" is an orchestration tool written in Python. @@ -14,7 +14,7 @@ filename: LearnAnsible.txt ## Example An example playbook to install apache and configure log level -```yml +```yaml --- - hosts: apache @@ -163,7 +163,7 @@ This example-playbook would execute (on all hosts defined in the inventory) two * `ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal -```yml +```yaml - hosts: all tasks: @@ -213,7 +213,7 @@ It is a great way to introduce `object oriented` management for your application Role can be included in your playbook (executed via your playbook). -```yml +```yaml - hosts: all tasks: @@ -427,7 +427,7 @@ You can use the jinja in the CLI too ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost ``` In fact - jinja is used to template parts of the playbooks too -```yml +```yaml #check part of this playbook: playbooks/roles/sys_debug/tasks/debug_time.yml - local_action: shell date +'%F %T' register: ts @@ -638,18 +638,19 @@ But ansible is way more! It provides an execution plans, an API, library, callba It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism that would warn you about some change automatically (this can be achieved with reasonable effort) -Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. +Official GUI Tool (web inferface) - Ansible Tower - is great, but it is expensive. There is no 'small enterprice' payment plan, however Ansible AWX is the free open source version we were all waiting for. #### Pros -It is an agent-less tools In most scenarios, it use ssh as a transport layer. +It is an agent-less tools In most scenarios, it use ssh as a transport layer. In some way you can use it as 'bash on steroids'. It is very-very-very easy to start. If you are familiar with ssh concept - you already know Ansible (ALMOST). My personal record is: 'I did show "how to install and use ansible" (for simple raspberry pi cluster management) - it took me 30 seconds to deliver a complete working example !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! It executes 'as is' - other tools (salt, puppet, chef - might execute in different scenario than you would expect) Documentation is at the world-class standard! The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. +Writing own modules and extension is fairly easy. +Ansible AWX is the open source version of Ansible Tower we have been waiting for, which provides an excellent UI. #### Neutral Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. @@ -657,7 +658,12 @@ Migration Ansible<->Salt is failrly easy - so if you would need an event-driven #### Some concepts Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -The simplest way is to execute remote command in more controlled way (still using ssh). +The simplest way is to execute remote command in more controlled way (still using ssh). On the other hand - in advanced scope - you can wrap Ansible (use python Ansible code as a library) with your own Python scrips! This is awesome! It would act a bit like Fabric then. +## Additional Resources +* [Servers For Hackers: An Ansible Tutorial](https://serversforhackers.com/c/an-ansible-tutorial) +* [A system administrator's guide to getting started with Ansible - FAST!](https://www.redhat.com/en/blog/system-administrators-guide-getting-started-ansible-fast) +* [Ansible Tower](https://www.ansible.com/products/tower) - Ansible Tower provides a web UI, dashboard and rest interface to ansible. +* [Ansible AWX](https://github.com/ansible/awx) - The Open Sourc version of Ansible Tower. \ No newline at end of file -- cgit v1.2.3 From bf6be6f4dd91bdf1a829359a379a8181f261aaef Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 31 Oct 2018 02:29:41 +0530 Subject: [mercurial/en] Multiple fixes (#3355) * Fix filename and doc title * Remove unecessary newlines, fix line length * Correct doc name capitalization, add periods * Fix subhead capitalization --- mercurial.html.markdown | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index d1cac66c..330beb35 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -1,9 +1,9 @@ --- category: tool -tool: hg +tool: Mercurial contributors: - ["Will L. Fife", "http://github.com/sarlalian"] -filename: LearnHG.txt +filename: LearnMercurial.txt --- Mercurial is a free, distributed source control management tool. It offers @@ -18,37 +18,30 @@ anyone working with versioned files. Version control is a system that keeps track fo changes to a set of file(s) and/or directorie(s) over time. -### Why Use Mercurial +### Why use Mercurial? * Distributed Architecture - Traditionally version control systems such as CVS and Subversion are a client server architecture with a central server to store the revsion history of a project. Mercurial however is a truly distributed architecture, giving each devloper a full local copy of the entire development history. It works independently of a central server. - * Fast - Traditionally version control systems such as CVS and Subversion are a client server architecture with a central server to store the revsion history of a project. Mercurial however is a truly distributed architecture, giving each devloper a full local copy of the entire development history. It works independently of a central server. - * Platform Independent - Mercurial was written to be highly platform independent. Much of Mercurial is written in Python, with small performance critical parts written in portable C. Binary releases are available for all major platforms. - * Extensible - The functionality of Mercurial can be increased with extensions, either by activating the official ones which are shipped with Mercurial or -downloading some [from the -wiki](https://www.mercurial-scm.org/wiki/UsingExtensions) or by [writing your -own](https://www.mercurial-scm.org/wiki/WritingExtensions). Extensions are -written in Python and can change the workings of the basic commands, add new -commands and access all the core functions of Mercurial. - +downloading some [from the wiki](https://www.mercurial-scm.org/wiki/UsingExtensions) or by [writing your own](https://www.mercurial-scm.org/wiki/WritingExtensions). Extensions are written in +Python and can change the workings of the basic commands, add new commands and +access all the core functions of Mercurial. * Easy to use - The Mercurial command set is consistent with what subversion users would expect, so they are likely to feel right at home. Most dangerous actions are part of extensions that need to be enabled to be used. - * Open Source - Mercurial is free software licensed under the terms of the [GNU General Public License Version 2](http://www.gnu.org/licenses/gpl-2.0.txt) or any later version. @@ -76,7 +69,7 @@ any later version. ### init Create a new repository in the given directory, the settings and stored -information are in a directory named ".hg" +information are in a directory named `.hg`. ```bash $ hg init @@ -102,7 +95,6 @@ $ hg help init Show the differences between what is on disk and what is committed to the current branch or tag. - ```bash # Will display the status of files $ hg status @@ -113,7 +105,7 @@ $ hg help status ### add -Will add the specified files to the repository on the next commit +Will add the specified files to the repository on the next commit. ```bash # Add a file in the current directory @@ -128,7 +120,7 @@ $ hg add *.rb ### branch -Set or show the current branch name +Set or show the current branch name. *Branch names are permanent and global. Use 'hg bookmark' to create a light-weight bookmark instead. See 'hg help glossary' for more information @@ -146,7 +138,7 @@ marked working directory as branch new_branch ### tag -Add one or more tags for the current or given revision +Add one or more tags for the current or given revision. Tags are used to name particular revisions of the repository and are very useful to compare different revisions, to go back to significant earlier @@ -215,7 +207,7 @@ $ hg diff -r 30 -r 20 ### grep -Search revision history for a pattern in specified files +Search revision history for a pattern in specified files. ```bash # Search files for a specific phrase @@ -242,7 +234,7 @@ $ hg log -G ### merge -Merge another revision into working directory +Merge another revision into working directory. ```bash # Merge changesets to local repository @@ -305,7 +297,7 @@ $ hg push remote2 ### rebase -Move changeset (and descendants) to a different branch +Move changeset (and descendants) to a different branch. Rebase uses repeated merging to graft changesets from one part of history (the source) onto another (the destination). This can be useful for @@ -356,7 +348,7 @@ $ hg remove go_away.txt $ hg remove *.txt ``` -## Further Information +## Further information * [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guid) * [Mercurial Quick Start](https://www.mercurial-scm.org/wiki/QuickStart) -- cgit v1.2.3 From 327640986ae5d4ff38058addae0eb00411846ea9 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 31 Oct 2018 02:39:10 +0530 Subject: Add language code --- es-es/pyqt-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 1d2f0fe3..6d4fdde7 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Nathan Hughes", "https://github.com/sirsharpest"] translators: - ["Adrian Rocamora", "https://github.com/adrianrocamora"] +lang: es-es --- **Qt** es un sistema altamente reconocido que permite desarrollar software multiplataforma que puede correr en diferentes entornos de software y hardware con pocos o ningún cambio. Aun así conserva la velocidad y poder de una aplicación nativa. **Qt** fue originalmente escrito en *C++*. -- cgit v1.2.3 From 98f67a64fc62d9fec1515ccc220cc16e289d1d3a Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Tue, 30 Oct 2018 20:32:24 -0300 Subject: [Dynamic programming] Fixed links --- dynamic-programming.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index aed169fc..f5f1743c 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -42,9 +42,9 @@ for i=0 to n-1 ### Some Famous DP Problems -- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- [Floyd Warshall Algorithm - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- [Integer Knapsack Problem - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- [Longest Common Subsequence - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Online Resources -- cgit v1.2.3 From 933d4c4057ea3d0eeaa06c08fd866cdc8b2c0ed7 Mon Sep 17 00:00:00 2001 From: Felipe N Souza Date: Tue, 30 Oct 2018 22:14:17 -0300 Subject: [clojure-macros] Fixed links (#3351) * [clojure-macros] Fixed links * [clojure-macros] Fixed link --- clojure-macros.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown index 3864f676..6154d570 100644 --- a/clojure-macros.html.markdown +++ b/clojure-macros.html.markdown @@ -142,11 +142,8 @@ You'll want to be familiar with Clojure. Make sure you understand everything in ### Further Reading -Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/) -[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) +[Writing Macros](http://www.braveclojure.com/writing-macros/) -Official docs -[http://clojure.org/macros](http://clojure.org/macros) +[Official docs](http://clojure.org/macros) -When to use macros? -[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) +[When to use macros?](https://lispcast.com/when-to-use-a-macro/) -- cgit v1.2.3 From 360349bf35a301b8c4586798560d410c892a1540 Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Tue, 30 Oct 2018 22:15:10 -0300 Subject: [Dynamic programming-PT/BR] Fixed links --- pt-br/dynamic-programming-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 518660a3..93171955 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -64,9 +64,9 @@ grafo acíclico dirigido. ## Alguns Problemas Famosos de Programação Dinâmica -- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- [Floyd Warshall Algorithm - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- [Integer Knapsack Problem - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- [Longest Common Subsequence - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Recursos Online (EN) -- cgit v1.2.3 From 5f169e74da198b66cbc24efd63a662d752b49935 Mon Sep 17 00:00:00 2001 From: fnscoder Date: Tue, 30 Oct 2018 22:30:47 -0300 Subject: [clojure-macros/ms-my] Fixed links --- ms-my/clojure-macros-my.html.markdown | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/ms-my/clojure-macros-my.html.markdown b/ms-my/clojure-macros-my.html.markdown index 099f376e..325f92e0 100644 --- a/ms-my/clojure-macros-my.html.markdown +++ b/ms-my/clojure-macros-my.html.markdown @@ -144,11 +144,8 @@ Biasakan diri dengan Clojure terlebih dahulu. Pastikan anda memahami semuanya di ### Bacaaan Lanjut -Writing Macros daripada [Clojure for the Brave and True](http://www.braveclojure.com/) -[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) +[Writing Macros daripada](http://www.braveclojure.com/writing-macros/) -Dokumen rasmi -[http://clojure.org/macros](http://clojure.org/macros) +[Dokumen rasmi](http://clojure.org/macros) -Bila perlu guna macro? -[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) +[Bila perlu guna macro?](https://lispcast.com/when-to-use-a-macro/) -- cgit v1.2.3 From 52c878ca1f332eb61d4884807d51099cf926b403 Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Tue, 30 Oct 2018 23:06:20 -0300 Subject: [Dynamic programmimg-DE/DE] --- de-de/dynamic-programming-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index afa9a17c..58568b3b 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -68,9 +68,9 @@ for i=0 to n-1 ### Einige bekannte DP Probleme -- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- [Floyd Warshall Algorithm - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- [Integer Knapsack Problem - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- [Longest Common Subsequence - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Online Ressourcen -- cgit v1.2.3 From 3027bf2c3030aa5277f8e14c8bd5f9fb753faf97 Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Tue, 30 Oct 2018 23:29:14 -0300 Subject: [Dynamic programmimg-DE/DE] --- fr-fr/dynamic-programming-fr.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index 54cca001..0a22b58b 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -42,9 +42,9 @@ Le même concept peut être appliqué pour trouver le chemin le plus long dans u ### Problèmes classiques de programmation dynamique -- L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Problème du sac à dos(EN) - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- [L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]) +- [Problème du sac à dos(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- [Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Online Resources -- cgit v1.2.3 From 791f1bc9cfb7efdc95f0302c82bda661efa57681 Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Tue, 30 Oct 2018 23:07:12 -0400 Subject: Fix some tildes & update spanish docs references --- es-es/lambda-calculus-es.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/es-es/lambda-calculus-es.html.markdown b/es-es/lambda-calculus-es.html.markdown index 56d4c02e..fb8527e4 100644 --- a/es-es/lambda-calculus-es.html.markdown +++ b/es-es/lambda-calculus-es.html.markdown @@ -11,7 +11,7 @@ translators: # Cálculo Lambda Cálculo Lambda (Cálculo-λ), originalmente creado por -[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +[Alonzo Church](https://es.wikipedia.org/wiki/Alonzo_Church), es el lenguaje de programación más pequeño del mundo. A pesar de no tener números, cadenas, valores booleanos o cualquier tipo de datos no funcional, el cálculo lambda se puede utilizar para @@ -23,7 +23,7 @@ El cálculo lambda se compone de 3 elementos: **variables**, **funciones** y | Nombre | Sintaxis | Ejemplo | Explicación | |-------------|------------------------------------|-----------|-----------------------------------------------| | Variable | `` | `x` | una variable llamada "x" | -| Función | `λ.` | `λx.x` | una función con parametro "x" y cuerpo "x" | +| Función | `λ.` | `λx.x` | una función con parámetro "x" y cuerpo "x" | | Aplicación | `` | `(λx.x)a` | llamando a la función "λx.x" con el argumento "a" | La función más básica es la función de identidad: `λx.x` que es equivalente a @@ -39,7 +39,7 @@ cuerpo de la función. ## Evaluación: Evaluación se realiza a través de -[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +[β-Reduction](https://es.wikipedia.org/wiki/C%C3%A1lculo_lambda#%CE%B2-reducci%C3%B3n), que es, esencialmente, sustitución de ámbito léxico. Al evaluar la expresión `(λx.x)a`, reemplazamos todas las ocurrencias de "x" @@ -54,7 +54,7 @@ Incluso puedes crear funciones de orden superior: Aunque el cálculo lambda tradicionalmente solo admite funciones de un solo parámetro, podemos crear funciones multiparamétricas usando -una técnica llamada [currying](https://en.wikipedia.org/wiki/Currying). +una técnica llamada [Currificación](https://es.wikipedia.org/wiki/Currificación). - `(λx.λy.λz.xyz)` es equivalente a `f(x, y, z) = ((x y) z)` @@ -90,7 +90,7 @@ Usando `IF` podemos definir los operadores lógicos booleanos básicos: *Note: `IF a b c` es esencialmente diciendo: `IF((a b) c)`* -## Numeros: +## Números: Aunque no hay números en el cálculo lambda, podemos codificar números usando [Númeral de Church](https://en.wikipedia.org/wiki/Church_encoding). @@ -147,7 +147,7 @@ Para la parte interior `λx.f(f x)`: = S (K f) (S (K f) I) (case 2, 1) ``` -Asi que: +Así que: ``` 2 = λf.λx.f(f x) @@ -210,6 +210,6 @@ S = ι(K) = ι(ι(ι(ιι))) 1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) 2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) -3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +3. [Wikipedia - Lambda Calculus](https://es.wikipedia.org/wiki/Cálculo_lambda) 4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) 5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) -- cgit v1.2.3 From 5e73ed609788e91dd2cc5c8a0528d1c9ba80895a Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Wed, 31 Oct 2018 01:03:36 -0400 Subject: Finish coldfusion translation --- es-es/coldfusion-es.html.markdown | 329 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 es-es/coldfusion-es.html.markdown diff --git a/es-es/coldfusion-es.html.markdown b/es-es/coldfusion-es.html.markdown new file mode 100644 index 00000000..5bddcb85 --- /dev/null +++ b/es-es/coldfusion-es.html.markdown @@ -0,0 +1,329 @@ +--- +language: coldfusion +filename: learncoldfusion.cfm +contributors: + - ["Wayne Boka", "http://wboka.github.io"] + - ["Kevin Morris", "https://twitter.com/kevinmorris"] +translators: + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +--- + +ColdFusion es un lenguaje de scripting para desarrollo web. +[Lea más aquí](Http://www.adobe.com/products/coldfusion-family.html) + +### CFML +_**C**old**F**usion **M**arkup **L**anguage_ +ColdFusion comenzó como un lenguaje basado en etiquetas. Casi toda la funcionalidad está disponible usando etiquetas. + +```cfm +Se han proporcionado etiquetas HTML para facilitar la lectura. + +" ---> + + + +

        Variables simples

        + +

        Set miVariable to "miValor"

        + +

        Set miNumero to 3.14

        + + + + +

        Muestra miVariable: #miVariable#

        +

        Muestra miNumero: #miNumero#

        + +
        + +

        Variables complejas

        + + +

        Establecer miArreglo1 en una matriz de 1 dimensión utilizando la notación literal o de corchete

        + + +

        Establecer miArreglo2 en una matriz de 1 dimensión usando la notación de funciones

        + + + +

        Contenidos de miArreglo1

        + +

        Contenidos de miArreglo2

        + + + + +

        Operadores

        +

        Aritméticos

        +

        1 + 1 = #1 + 1#

        +

        10 - 7 = #10 - 7#

        +

        15 * 10 = #15 * 10#

        +

        100 / 5 = #100 / 5#

        +

        120 % 5 = #120 % 5#

        +

        120 mod 5 = #120 mod 5#

        + +
        + + +

        Comparación

        +

        Notación estándar

        +

        Is 1 eq 1? #1 eq 1#

        +

        Is 15 neq 1? #15 neq 1#

        +

        Is 10 gt 8? #10 gt 8#

        +

        Is 1 lt 2? #1 lt 2#

        +

        Is 10 gte 5? #10 gte 5#

        +

        Is 1 lte 5? #1 lte 5#

        + +

        Notación alternativa

        +

        Is 1 == 1? #1 eq 1#

        +

        Is 15 != 1? #15 neq 1#

        +

        Is 10 > 8? #10 gt 8#

        +

        Is 1 < 2? #1 lt 2#

        +

        Is 10 >= 5? #10 gte 5#

        +

        Is 1 <= 5? #1 lte 5#

        + +
        + + +

        Estructuras de Control

        + + + +

        Condición a probar: "#miCondicion#"

        + + + #miCondicion#. Estamos probando. + + #miCondicion#. Procede con cuidado!!! + + miCondicion es desconocido + + +
        + + +

        Bucles

        +

        Bucle For

        + +

        Index equals #i#

        +
        + +

        Bucle For Each (Variables complejas)

        + +

        Establecer miArreglo3 to [5, 15, 99, 45, 100]

        + + + + +

        Index equals #i#

        +
        + +

        Establecer myArray4 to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]

        + + + + +

        Index equals #s#

        +
        + +

        Declaración Switch

        + +

        Establecer miArreglo5 to [5, 15, 99, 45, 100]

        + + + + + + +

        #i# es un múltiplo de 5.

        +
        + +

        #i# es noventa y nueve.

        +
        + +

        #i# no es 5, 15, 45, or 99.

        +
        +
        +
        + +
        + +

        Tipos de conversión

        + + + +
        First Header Second Header
        first row, first column first row, first column first row, second column
        second row, first column second row, second column
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        ValorComo booleanoComo numeroComo fechaComo cadena
        "Si"TRUE1Error"Si"
        "No"FALSE0Error"No"
        TRUETRUE1Error"Yes"
        FALSEFALSE0Error"No"
        NúmeroTrue si el número no es 0; False de lo contrario.NúmeroConsulte "Date-time values" anteriormente en este capítulo.Representación de cadena del número (for example, "8").
        CadenaSi representa una fecha y hora (ver la siguiente columna), se convierte al valor numérico del objeto de fecha y hora correspondiente.
        Si es una fecha, hora o marca de tiempo ODBC (por ejemplo, "{ts '2001-06-14 11:30:13'}", o si se expresa en un formato de fecha u hora estándar de EE. UU., incluido al usar nombres de mes completos o abreviados, se convierte al valor de fecha y hora correspondiente.
        Los días de la semana o la puntuación inusual dan como resultado un error.
        Generalmente se permiten guiones, barras diagonales y espacios.
        Cadena
        FechaErrorEl valor numérico del objeto fecha-hora.Fechaun timestamp de ODBC .
        + +
        + +

        Componentes

        + +Código de referencia (las funciones deben devolver algo para admitir IE) +``` +```cfs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +sayHola() +

        #sayHola()#

        +getHola() +

        #getHola()#

        +getMundo() +

        #getMundo()#

        +setHola("Hola") +

        #setHola("Hola")#

        +setMundo("mundo") +

        #setMundo("mundo")#

        +sayHola() +

        #sayHola()#

        +getHola() +

        #getHola()#

        +getMundo() +

        #getMundo()#

        +``` + +### CFScript +_**C**old**F**usion **S**cript_ +En los últimos años, el lenguaje ColdFusion ha agregado sintaxis de script para simular la funcionalidad de etiquetas. Cuando se utiliza un servidor CF actualizado, casi todas las funciones están disponibles mediante la sintaxis de script. + +## Otras lecturas + +Los enlaces que se proporcionan a continuación son solo para comprender el tema, siéntase libre de buscar en Google y encuentrar ejemplos específicos. + +1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) +2. [Open Source Documentation](http://cfdocs.org/) -- cgit v1.2.3 From 1b1acc6f3ed7d24733fbacee2d3a6bf6df7c66a4 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Wed, 31 Oct 2018 08:23:24 -0300 Subject: Update csharp-pt.html.markdown Translation of comments (line 98 and 99) and correction of comments (line 62) --- pt-br/csharp-pt.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..2b61a8fa 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -59,7 +59,7 @@ namespace Learning.CSharp Console.Write("World"); /////////////////////////////////////////////////// - // Tpos e Variáveis + // Tipos e Variáveis // // Declare uma variável usando /////////////////////////////////////////////////// @@ -95,8 +95,9 @@ namespace Learning.CSharp float fooFloat = 234.5f; // Precision: 7 digits // f is used to denote that this variable value is of type float - // Decimal - a 128-bits data type, with more precision than other floating-point types, - // suited for financial and monetary calculations + // Decimal - um tipo de dados de 128 bits, com mais precisão do que outros tipos de ponto flutuante, + // adequado para cálculos financeiros e monetários + decimal fooDecimal = 150.3m; // Boolean - true & false -- cgit v1.2.3 From 6d23388f632bc2149a59269a6456ad2bea5552c0 Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 08:33:18 -0300 Subject: [typescript/pt-br] Removed duplicate text --- pt-br/typescript-pt.html.markdown | 7 ------- 1 file changed, 7 deletions(-) diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown index f072b257..077aa2cc 100644 --- a/pt-br/typescript-pt.html.markdown +++ b/pt-br/typescript-pt.html.markdown @@ -8,13 +8,6 @@ translators: lang: pt-br --- -TypeScript is a language that aims at easing development of large scale applications written in JavaScript. -TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. - -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). - - Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript. Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript. É um super conjunto de JavaScript: todo o código JavaScript é o código do texto dactilografado válido para que possa ser adicionados diretamente a qualquer projeto. O compilador emite typescript JavaScript. -- cgit v1.2.3 From cb9b22fa54cf29eda343904cef7a26c6860270e8 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Wed, 31 Oct 2018 08:37:56 -0300 Subject: [ruby/pt-br] Update ruby-pt.html.markdown Translation of comment. --- pt-br/ruby-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 1078f6c5..7ae28ac2 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -71,7 +71,7 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true -# Strings são objects +# Strings são objetos 'Eu sou uma string'.class #=> String "Eu também sou uma string".class #=> String -- cgit v1.2.3 From f08c02338ae371ecffe07f18a11caee64100b8b1 Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 08:40:34 -0300 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..f0d01e6e 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -294,9 +294,9 @@ on a new line! ""Wow!"", the masses cried"; case 3: monthString = "March"; break; - // You can assign more than one case to an action - // But you can't add an action without a break before another case - // (if you want to do this, you would have to explicitly add a goto case x + // Você pode declarar mais de um "case" para uma ação + // Mas você não pode adicionar uma ação sem um "break" antes de outro "case" + // (se você quiser fazer isso, você tem que explicitamente adicionar um "goto case x") case 6: case 7: case 8: -- cgit v1.2.3 From 8bad4d109cff8165d1dddf5796db41a4f8273128 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Wed, 31 Oct 2018 08:41:41 -0300 Subject: [csharp/pt-br] Update csharp-pt.html.markdown Translation of comments. --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..c310ce2e 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -522,7 +522,7 @@ on a new line! ""Wow!"", the masses cried"; foreach (var key in responses.Keys) Console.WriteLine("{0}:{1}", key, responses[key]); - // DYNAMIC OBJECTS (great for working with other languages) + // OBJETOS DINÂMICOS (ótimo para trabalhar com outros idiomas) dynamic student = new ExpandoObject(); student.FirstName = "First Name"; // No need to define class first! -- cgit v1.2.3 From fd5ee982bc9f2f10bafb8b4d7cf15c15e646da10 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Wed, 31 Oct 2018 08:45:05 -0300 Subject: [csharp/pt-br] Update csharp-pt.html.markdown Translation of comments. --- pt-br/csharp-pt.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..3d84f91f 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -522,7 +522,7 @@ on a new line! ""Wow!"", the masses cried"; foreach (var key in responses.Keys) Console.WriteLine("{0}:{1}", key, responses[key]); - // DYNAMIC OBJECTS (great for working with other languages) + // OBJETOS DINÂMICOS (ótimo para trabalhar com outros idiomas) dynamic student = new ExpandoObject(); student.FirstName = "First Name"; // No need to define class first! @@ -730,10 +730,10 @@ on a new line! ""Wow!"", the masses cried"; set { _hasTassles = value; } } - // You can also define an automatic property in one line - // this syntax will create a backing field automatically. - // You can set an access modifier on either the getter or the setter (or both) - // to restrict its access: + // Você também pode definir uma propriedade automática em uma linha +        // Esta sintaxe criará um campo de apoio automaticamente. +        // Você pode definir um modificador de acesso no getter ou no setter (ou ambos) +        // para restringir seu acesso: public bool IsBroken { get; private set; } // Properties can be auto-implemented -- cgit v1.2.3 From b0d213ca09f5453a1f957b202bc5b1cc20cc5cb9 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Wed, 31 Oct 2018 08:50:50 -0300 Subject: [csharp/pt-br] Update csharp-pt.html.markdown Translation of comments. --- pt-br/csharp-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..e5c7eed0 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -854,8 +854,8 @@ on a new line! ""Wow!"", the masses cried"; } /// - /// Used to connect to DB for LinqToSql example. - /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// Exemplo de como conectar-se ao DB via LinqToSql. +    /// EntityFramework First Code é impressionante (semelhante ao ActiveRecord de Ruby, mas bidirecional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// public class BikeRepository : DbContext -- cgit v1.2.3 From 049838460e27f0a9777ac92dfc2843a5f9056358 Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 08:51:04 -0300 Subject: [yaml/pt-br] Fixing translation --- pt-br/yaml-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 341ae675..569bde75 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -11,9 +11,9 @@ lang: pt-br YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e legível por seres humanos. -É um estrito subconjunto de JSON, com a adição de sintaticamente -novas linhas e recuo significativos, como Python. Ao contrário de Python, no entanto, -YAML não permite caracteres de tabulação literais em tudo. +It's a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, YAML doesn't allow literal tab characters for indentation. + +É um superconjunto de JSON, com a adição de indentação e quebras de linhas sintaticamente significativas, como Python. Ao contrário de Python, entretanto, YAML não permite o caracter literal tab para identação. ```yaml # Commentários em YAML são como este. -- cgit v1.2.3 From 1255d7166830068d6e1ed1e5b0532b858f3fdf14 Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 08:54:09 -0300 Subject: [xml/pt-bt] Better translation --- pt-br/xml-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown index f347f8ef..6710b387 100644 --- a/pt-br/xml-pt.html.markdown +++ b/pt-br/xml-pt.html.markdown @@ -10,8 +10,7 @@ lang: pt-br XML é uma linguagem de marcação projetada para armazenar e transportar dados. -Ao contrário de HTML, XML não especifica como exibir ou formatar os dados, -basta carregá-lo. +Ao contrário de HTML, XML não especifica como exibir ou formatar os dados, apenas o transporta. * Sintaxe XML -- cgit v1.2.3 From 34621899d314845bb116e922d8947db12056852d Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 09:01:02 -0300 Subject: [whip/pt-br] Better translation --- pt-br/whip-pt.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown index 989bae05..7bdeec25 100644 --- a/pt-br/whip-pt.html.markdown +++ b/pt-br/whip-pt.html.markdown @@ -15,13 +15,13 @@ Whip é um dialeto de Lisp feito para construir scripts e trabalhar com conceitos mais simples. Ele também copia muitas funções e sintaxe de Haskell (uma linguagem não correlata) -Esse documento foi escrito pelo próprio autor da linguagem. Então é isso. +Esse documento foi escrito pelo próprio autor da linguagem. Então é isso. ```scheme ; Comentário são como em Lisp. Pontos-e-vírgulas... ; A maioria das declarações de primeiro nível estão dentro de "listas" -; que nada mais são que coisas entre parêntesis separadas por espaços em branco +; que nada mais são que coisas entre parênteses separadas por espaços em branco nao_é_uma_lista (uma lista) @@ -64,7 +64,7 @@ false (not false) ; => true ; Mas a maioria das funções não-haskell tem atalhos -; o não atalho é um '!'. +; o atalho para "não" é um '!'. (! (! true)) ; => true ; Igualdade é `equal` ou `=`. @@ -114,7 +114,7 @@ undefined ; usada para indicar que um valor não foi informado (1 2 3) ; => [1, 2, 3] (sintaxe JavaScript) ; Dicionários em Whip são o equivalente a 'object' em JavaScript ou -; 'dict' em python ou 'hash' em Ruby: eles s]ão uma coleção desordenada +; 'dict' em python ou 'hash' em Ruby: eles são uma coleção desordenada de pares chave-valor. {"key1" "value1" "key2" 2 3 3} @@ -222,7 +222,7 @@ linguagens imperativas. (take 1 (1 2 3 4)) ; (1 2) ; Contrário de `take` (drop 1 (1 2 3 4)) ; (3 4) -; Menos valor em uma lista +; Menor valor em uma lista (min (1 2 3 4)) ; 1 ; Maior valor em uma lista (max (1 2 3 4)) ; 4 -- cgit v1.2.3 From ac42b7b824bdfb0b85852a7a4f9f82f281e99d76 Mon Sep 17 00:00:00 2001 From: Thiago Ribeiro Date: Wed, 31 Oct 2018 09:33:00 -0300 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index be14a1c8..10e8a201 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -336,28 +336,28 @@ on a new line! ""Wow!"", the masses cried"; } /////////////////////////////////////// - // CLASSES - see definitions at end of file + // CLASSES - Veja definições no fim do arquivo /////////////////////////////////////// public static void Classes() { - // See Declaration of objects at end of file + // Veja Declaração de objetos no fim do arquivo - // Use new to instantiate a class + // Use new para instanciar uma classe Bicycle trek = new Bicycle(); - // Call object methods - trek.SpeedUp(3); // You should always use setter and getter methods + // Chame métodos do objeto + trek.SpeedUp(3); // Você deve sempre usar métodos setter e getter trek.Cadence = 100; - // ToString is a convention to display the value of this Object. + // ToString é uma convenção para exibir o valor desse Objeto. Console.WriteLine("trek info: " + trek.Info()); - // Instantiate a new Penny Farthing + // Instancie um novo Penny Farthing PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); - } // End main method + } // Fim do método principal // CONSOLE ENTRY A console application must have a main method as an entry point public static void Main(string[] args) -- cgit v1.2.3 From a9c9379d4f359c79f3d44687ee19e65eaae4208c Mon Sep 17 00:00:00 2001 From: Thiago Ribeiro Date: Wed, 31 Oct 2018 09:54:59 -0300 Subject: [paren/pt-br] Small typos --- pt-br/paren-pt.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown index 464a69d2..92414ba3 100644 --- a/pt-br/paren-pt.html.markdown +++ b/pt-br/paren-pt.html.markdown @@ -182,8 +182,8 @@ a ; => (3 2) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Macros lhe permitem estender a sintaxe da linguagem. -;; Os macros no Paren são fáceis. -;; Na verdade, (defn) é um macro. +;; As macros no Paren são fáceis. +;; Na verdade, (defn) é uma macro. (defmacro setfn (nome ...) (set nome (fn ...))) (defmacro defn (nome ...) (def nome (fn ...))) @@ -191,6 +191,6 @@ a ; => (3 2) (defmacro infix (a op ...) (op a ...)) (infix 1 + 2 (infix 3 * 4)) ; => 15 -;; Macros não são higiênicos, você pode sobrescrever as variáveis já existentes! -;; Eles são transformações de códigos. +;; Macros não são higiênicas, você pode sobrescrever as variáveis já existentes! +;; Elas são transformações de códigos. ``` -- cgit v1.2.3 From e2637963b93d6fd610de994273713ccbd94a6522 Mon Sep 17 00:00:00 2001 From: Fer Date: Wed, 31 Oct 2018 10:38:22 -0300 Subject: [yaml/pt-br] Remove lines --- pt-br/yaml-pt.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 569bde75..0b71877e 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -11,8 +11,6 @@ lang: pt-br YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e legível por seres humanos. -It's a strict superset of JSON, with the addition of syntactically significant newlines and indentation, like Python. Unlike Python, however, YAML doesn't allow literal tab characters for indentation. - É um superconjunto de JSON, com a adição de indentação e quebras de linhas sintaticamente significativas, como Python. Ao contrário de Python, entretanto, YAML não permite o caracter literal tab para identação. ```yaml -- cgit v1.2.3 From e30222273bbf1aa10574e70a1c7d1557ed89ea7f Mon Sep 17 00:00:00 2001 From: bobdc Date: Wed, 31 Oct 2018 12:50:32 -0400 Subject: make edits requested by divayprakash https://github.com/adambard/learnxinyminutes-docs/pull/3349 --- sql.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sql.html.markdown b/sql.html.markdown index 0dc07eb5..8f200344 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -2,8 +2,8 @@ language: SQL filename: learnsql.sql contributors: -- ["Bob DuCharme", "http://bobdc.com/"] -lang: en-en + - ["Bob DuCharme", "http://bobdc.com/"] +https://github.com/adambard/learnxinyminutes-docs --- Structured Query Language (SQL) is an ISO standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences. @@ -13,7 +13,7 @@ Implementations typically provide a command line prompt where you can enter the Several of these sample commands assume that the [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/) available on [github](https://github.com/datacharmer/test_db) has already been loaded. The github files are scripts of commands, similar to the relevant commands below, that create and populate tables of data about a fictional company’s employees. The syntax for running these scripts will depend on the SQL implementation you are using. A utility that you run from the operating system prompt is typical. -``` +```sql # Comments start with a pound sign. End each command with a semicolon. # SQL is not case-sensitive about keywords. The sample commands here -- cgit v1.2.3 From c8020fa024b8007096a6650db306cf09143e6962 Mon Sep 17 00:00:00 2001 From: Ivan Alburquerque Date: Wed, 31 Oct 2018 12:59:56 -0400 Subject: Fix YAML frontmatter missing lang conf --- es-es/pascal-es.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/es-es/pascal-es.html.markdown b/es-es/pascal-es.html.markdown index d1e0345a..37ce7512 100644 --- a/es-es/pascal-es.html.markdown +++ b/es-es/pascal-es.html.markdown @@ -1,11 +1,12 @@ --- language: Pascal -filename: learnpascal.pas +filename: learnpascal-es.pas contributors: - ["Ganesha Danu", "http://github.com/blinfoldking"] - ["Keith Miyake", "https://github.com/kaymmm"] translators: - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +lang: es-es --- -- cgit v1.2.3 From 37758458ab226b08db33b80903420fc2bba9e594 Mon Sep 17 00:00:00 2001 From: Ivan Alburquerque Date: Wed, 31 Oct 2018 13:04:34 -0400 Subject: Fix YAML frontmatter missing lang conf --- es-es/lambda-calculus-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/lambda-calculus-es.html.markdown b/es-es/lambda-calculus-es.html.markdown index fb8527e4..d49545c2 100644 --- a/es-es/lambda-calculus-es.html.markdown +++ b/es-es/lambda-calculus-es.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Yan Hui Hang", "http://github.com/yanhh0"] translators: - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +lang: es-es --- # Cálculo Lambda -- cgit v1.2.3 From 45e7703613fe033c4a4def5c17cb19b471f84586 Mon Sep 17 00:00:00 2001 From: Ivan Alburquerque Date: Wed, 31 Oct 2018 13:06:16 -0400 Subject: Fix YAML frontmatter missing lang conf --- es-es/coldfusion-es.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/es-es/coldfusion-es.html.markdown b/es-es/coldfusion-es.html.markdown index 5bddcb85..b871c39e 100644 --- a/es-es/coldfusion-es.html.markdown +++ b/es-es/coldfusion-es.html.markdown @@ -1,11 +1,12 @@ --- language: coldfusion -filename: learncoldfusion.cfm +filename: learncoldfusion-es.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] - ["Kevin Morris", "https://twitter.com/kevinmorris"] translators: - - ["Ivan Alburquerque", "https://github.com/AlburIvan"] + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] +lang: es-es --- ColdFusion es un lenguaje de scripting para desarrollo web. -- cgit v1.2.3 From 58d64442141523c28d9e3d45017a5be33ae0ef97 Mon Sep 17 00:00:00 2001 From: Ivan Alburquerque Date: Wed, 31 Oct 2018 13:09:26 -0400 Subject: Fix YAML indentation issue --- es-es/coldfusion-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/coldfusion-es.html.markdown b/es-es/coldfusion-es.html.markdown index b871c39e..4c04fc1e 100644 --- a/es-es/coldfusion-es.html.markdown +++ b/es-es/coldfusion-es.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Wayne Boka", "http://wboka.github.io"] - ["Kevin Morris", "https://twitter.com/kevinmorris"] translators: - - ["Ivan Alburquerque", "https://github.com/AlburIvan"] + - ["Ivan Alburquerque", "https://github.com/AlburIvan"] lang: es-es --- -- cgit v1.2.3 From ce92551a34d800a28ec5e681b352753bc9aa1b73 Mon Sep 17 00:00:00 2001 From: fnscoder Date: Wed, 31 Oct 2018 14:20:02 -0300 Subject: [clojure-macros/zh-cn] Fixed links --- zh-cn/clojure-macro-cn.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macro-cn.html.markdown index 9324841e..23b2f203 100644 --- a/zh-cn/clojure-macro-cn.html.markdown +++ b/zh-cn/clojure-macro-cn.html.markdown @@ -142,11 +142,9 @@ lang: zh-cn ## 扩展阅读 -[Clojure for the Brave and True](http://www.braveclojure.com/)系列的编写宏 -http://www.braveclojure.com/writing-macros/ +[Clojure for the Brave and True](http://www.braveclojure.com/) +[系列的编写宏](http://www.braveclojure.com/writing-macros/) -官方文档 -http://clojure.org/macros +[官方文档](http://clojure.org/macros) -何时使用宏? -http://dunsmor.com/lisp/onlisp/onlisp_12.html +[何时使用宏?](https://lispcast.com/when-to-use-a-macro/) -- cgit v1.2.3 From ec8231e6c25a9db40705c5336105652bfb43b8c5 Mon Sep 17 00:00:00 2001 From: fnscoder Date: Wed, 31 Oct 2018 15:11:33 -0300 Subject: [python3/pr-br] Fixed typo --- pt-br/python3-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown index 9b6bd1b6..ea0617f4 100644 --- a/pt-br/python3-pt.html.markdown +++ b/pt-br/python3-pt.html.markdown @@ -105,9 +105,9 @@ False or True # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (operador 'is' e operador '==') is verifica se duas referenciam um -# mesmo objeto, mas == verifica se as variáveis apontam para o -# mesmo valor. +# (operador 'is' e operador '==') is verifica se duas variáveis +# referenciam um mesmo objeto, mas == verifica se as variáveis +# apontam para o mesmo valor. a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] b = a # b referencia o que está referenciado por a b is a # => True, a e b referenciam o mesmo objeto -- cgit v1.2.3 From 3aada35d9a938e1af78328c8ee170ac71846fb10 Mon Sep 17 00:00:00 2001 From: Henning Post Date: Wed, 31 Oct 2018 11:39:25 -0700 Subject: Mention parameterless main function --- kotlin.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 81242bac..9bc8b420 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -20,7 +20,9 @@ package com.learnxinyminutes.kotlin /* The entry point to a Kotlin program is a function named "main". -The function is passed an array containing any command line arguments. +The function is passed an array containing any command-line arguments. +Since Kotlin 1.3 the "main" function can also be defined without +any parameters. */ fun main(args: Array) { /* -- cgit v1.2.3 From e9622c01f4a22106546c58c6e3fc8d1f6ef42cb6 Mon Sep 17 00:00:00 2001 From: David Lima Date: Tue, 30 Oct 2018 20:16:06 -0300 Subject: Translate Haxe documentation to pt-br --- pt-br/haxe-pt.html.markdown | 795 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 795 insertions(+) create mode 100644 pt-br/haxe-pt.html.markdown diff --git a/pt-br/haxe-pt.html.markdown b/pt-br/haxe-pt.html.markdown new file mode 100644 index 00000000..13264dec --- /dev/null +++ b/pt-br/haxe-pt.html.markdown @@ -0,0 +1,795 @@ +--- +language: haxe +filename: LearnHaxe3-br.hx +contributors: + - ["Justin Donaldson", "https://github.com/jdonaldson/"] + - ["Dan Korostelev", "https://github.com/nadako/"] +translators: + - ["David Lima", "https://github.com/davelima/"] +lang: pt-br +--- + +Haxe é uma linguagem baseada na web que provê suporte a C++, C#, SWF/ActionScript, +Java e Neko byte code (também desenvolvida pelo autor de Haxe). Observe que +este guia é para a versão 3 de Haxe. Alguns pontos do guia são aplicáveis +para versões anteriores, mas é recomendado que você busque outras referências +para essas versões. + + +```csharp +/* + Bem vindo ao Aprenda Haxe 3 em 15 minutos. http://www.haxe.org + Este é um tutorial executável. Você pode compilar e rodar este tutorial + usando o compilador haxe, estando no mesmo diretório de LearnHaxe.hx: + $> haxe -main LearnHaxe3 -x out + + Olhe para os sinais de /* e */ em volta desses parágrafos. Nós estamos + dentro de um "Comentário multilinha". Nós podemos colocar observações aqui + e elas serão ignoradas pelo compilador. + + Comentários multilinha também são utilizados para gerar documentação haxedoc, + seguindo o estilo javadoc. Eles serão usados pelo haxedoc se precerem imediatamente + uma classe, uma função de uma classe ou uma variável de uma classe. + + */ + +// Duas barras, como as dessa linha, farão um comentário de linha única. + + +/* + Este será o primeiro código haxe de verdade, e está declarando um pacote vazio. + Não é necessário usar um pacote, mas ele será útil se você quiser criar + um namespace para o seu código (exemplo: org.seuapp.SuaClasse). + + Omitir a declaração de pacote é a mesma coisa que declarar um pacote vazio. + */ +package; // pacote vazio, sem namespace. + +/* + Pacotes são diretórios que contém módulos. Cada módulo é um arquivo .hx que + contém tipos definidos em um pacote. Nomes de pacotes (ex. org.seuapp) + devem estar em letras minúsculas, enquanto nomes de módulos devem começar + com uma letra maiúscula. Um módulo contem um ou mais tipos, cujo os nomes + também devem começar com uma letra maiúscula. + + Exemplo: a classe "org.seuapp.Foo" deve ter a estrutura de diretório org/module/Foo.hx, + sendo acessível do diretório do compilador ou caminho da classe. + + Se você importar código de outros arquivos, isso deve ser declarado antes + do restante do código. Haxe disponibiliza várias classes padrões para você + começar: + */ +import haxe.ds.ArraySort; + +// você pode importar várias classes/módulos de uma vez usando "*" +import haxe.ds.*; + +// você pode importar campos estáticos +import Lambda.array; + +// você também pode usar "*" para importar todos os campos estáticos +import Math.*; + +/* + Você também pode importar classes de uma forma diferente, habilitando-as para + extender a funcionalidade de outras classes, como um "mixin". Falaremos sobre + "using" em breve. + */ +using StringTools; + +/* + Typedefs são como variáveis... para tipos. Eles devem ser declarados antes + de qualquer código. Veremos isso em breve. + */ +typedef FooString = String; + +// Typedefs também podem referenciar tipos "estruturais". Também veremos isso em breve. +typedef FooObject = { foo: String }; + +/* + Esta é a definição da classe. É a classe principal do arquivo, visto que + possui o mesmo nome (LearnHaxe3) + */ +class LearnHaxe3{ + /* + Se você quiser que um determinado código rode automaticamente, você + precisa colocá-lo em uma função estática "main", e especificar a classe + nos argumentos do compilador. + Nesse caso, nós especificamos a classe "LearnHaxe3" no nos argumentos + do compilador acima. + */ + static function main(){ + + /* + Trace é o método padrão para imprimir expressões haxe na tela. + Temos diferentes métodos para conseguir isso em diferentes destinos. + Por exemplo: Java, C++, C#, etc. irão imprimir para stdout. + Javascript irá imprimir no console.log, e Flash irá imprimir para um + TextField anexado. Todos os "traces" imprimem também uma linha em branco + por padrão. Por fim, é possível prevenir um trace de ser exibido usando + o argumento "--no-traces" no compilador. + */ + trace("Olá mundo, com trace()!"); + + /* + Trace pode tratar qualquer tipo de valor ou objeto. O método tentará + imprimir a representação de uma expressão da melhor forma. Você também + pode concatenar strings usando o operador "+": + */ + trace( " Integer: " + 10 + " Float: " + 3.14 + " Boolean: " + true); + + /* + Em Haxe, é obrigatório separar expressões no mesmo bloco com ';'. Mas + é possível colocar duas expressões na mesma linha, dessa forma: + */ + trace('duas expressões..'); trace('uma linha'); + + + ////////////////////////////////////////////////////////////////// + // Tipos & Variáveis + ////////////////////////////////////////////////////////////////// + trace("***Tipos & Variáveis***"); + + /* + Vcoê pode atrelar valores e referências à estruturas usando a + palavra-chave "var": + */ + var um_inteiro:Int = 1; + trace(um_inteiro + " é o valor de um_inteiro"); + + + /* + Haxe é tipada estaticamente, então "um_inteiro" temos que declarar + um valor do tipo "Int", e o restante da expressão atrela o valor "1" + a esta variável. Em muitos casos, não é necessário declarar o tipo. + Aqui, o compilador haxe assume que o tipo de "outro_inteiro" deve + ser "Int" + */ + var outro_inteiro = 2; + trace(outro_inteiro + " é o valor de outro_inteiro"); + + // O método $type() imprime o tipo que o compilador assume: + $type(outro_inteiro); + + // Você também pode representar inteiros em hexadecimal: + var hex_inteiro = 0xffffff; + + /* + Haxe usa precisão de pltaforma para os tamanhos de Int e Float. + Ele também usa o comportamento de plataforma para sobrecarga. + (É possível ter outros tipos numéricos e comportamentos usando + bibliotecas especiais) + */ + + /* + Em adição a valores simples como Integers, Floats e Booleans, + Haxe disponibiliza implementações padrões de bibliotecas para + dados comuns de estrutura como strings, arrays, lists e maps: + */ + + var uma_string = "alguma" + 'string'; // strings podem estar entre aspas simples ou duplas + trace(uma_string + " é o valor de uma_string"); + + /* + Strings podem ser "interpoladas" se inserirmos variáveis em + posições específicas. A string deve estar entre aspas simples, e as + variáveis devem ser precedidas por "$". Expressões podem estar entre + ${...}. + */ + var x = 1; + var uma_string_interpolada = 'o valor de x é $x'; + var outra_string_interpolada = 'o valor de x + 1 é ${x + 1}'; + + /* + Strings são imutáveis, métodos retornarão uma cópia de partes + ou de toda a string. (Veja também a classe StringBuf) + */ + var uma_sub_string = a_string.substr(0,4); + trace(uma_sub_string + " é o valor de a_sub_string"); + + /* + Regex também são suportadas, mas não temos espaço suficiente para + entrar em muitos detalhes. + */ + var re = ~/foobar/; + trace(re.match('foo') + " é o valor de (~/foobar/.match('foo')))"); + + /* + Arrays são indexadas a partir de zero, dinâmicas e mutáveis. Valores + faltando são definidos como null. + */ + var a = new Array(); // um array que contém Strings + a[0] = 'foo'; + trace(a.length + " é o valor de a.length"); + a[9] = 'bar'; + trace(a.length + " é o valor de a.length (depois da modificação)"); + trace(a[3] + " é o valor de a[3]"); // null + + /* + Arrays são *genéricas*, então você pode indicar quais valores elas + contém usando um parâmetro de tipo: + */ + var a2 = new Array(); // um Array de Ints + var a3 = new Array>(); // um Array de Arrays (de Strings). + + /* + Mapas são estruturas simples de chave/valor. A chave e o valor podem + ser de qualquer tipo. + */ + var m = new Map(); // As chaves são strings, os valores são Ints. + m.set('foo', 4); + // Você também pode usar a notação de array; + m['bar'] = 5; + trace(m.exists('bar') + " é o valor de m.exists('bar')"); + trace(m.get('bar') + " é o valor de m.get('bar')"); + trace(m['bar'] + " é o valor de m['bar']"); + + var m2 = ['foo' => 4, 'baz' => 6]; // Syntaxe alternativa de map + trace(m2 + " é o valor de m2"); + + /* + Lembre-se, você pode usar descoberta de tipo. O compilador + Haxe irá decidir o tipo da variável assim que você passar um + argumento que define um parâmetro de tipo. + */ + var m3 = new Map(); + m3.set(6, 'baz'); // m3 agora é Map + trace(m3 + " é o valor de m3"); + + /* + Haxe possui mais algumas estruturas de dados padrões no módulo haxe.ds, + tais como List, Stack e BalancedTree + */ + + + ////////////////////////////////////////////////////////////////// + // Operadores + ////////////////////////////////////////////////////////////////// + trace("***OPERADORES***"); + + // aritmética básica + trace((4 + 3) + " é o valor de (4 + 3)"); + trace((5 - 1) + " é o valor de (5 - 1)"); + trace((2 * 4) + " é o valor de (2 * 4)"); + trace((8 / 3) + " é o valor de (8 / 3) (divisão sempre produz Floats)"); + trace((12 % 4) + " é o valor de (12 % 4)"); + + + // comparação básica + trace((3 == 2) + " é o valor de 3 == 2"); + trace((3 != 2) + " é o valor de 3 != 2"); + trace((3 > 2) + " é o valor de 3 > 2"); + trace((3 < 2) + " é o valor de 3 < 2"); + trace((3 >= 2) + " é o valor de 3 >= 2"); + trace((3 <= 2) + " é o valor de 3 <= 2"); + + // operadores bit-a-bit padrões + /* + ~ Complemento bit-a-bit unário + << Deslocamento a esquerda + >> Deslocamento a direita + >>> Deslocamento a direita com preenchimento de 0 + & Bit-a-bit AND + ^ Bit-a-bit OR exclusivo + | Bit-a-bit OR inclusivo + */ + + // incrementos + var i = 0; + trace("Incrementos e decrementos"); + trace(i++); //i = 1. Pós-incremento + trace(++i); //i = 2. Pré-incremento + trace(i--); //i = 1. Pós-decremento + trace(--i); //i = 0. Pré-decremento + + ////////////////////////////////////////////////////////////////// + // Estruturas de controle + ////////////////////////////////////////////////////////////////// + trace("***ESTRUTURAS DE CONTROLE***"); + + // operadores if + var j = 10; + if (j == 10){ + trace("isto é impresso"); + } else if (j > 10){ + trace("não é maior que 10, então não é impresso"); + } else { + trace("também não é impresso."); + } + + // temos também um if "ternário": + (j == 10) ? trace("igual a 10") : trace("diferente de 10"); + + /* + Por fim, temos uma outra forma de estrutura de controle que opera + e na hora da compilação: compilação condicional. + */ +#if neko + trace('olá de neko'); +#elseif js + trace('olá de js'); +#else + trace('olá de outra plataforma!'); +#end + /* + O código compilado irá mudar de acordo com o alvo de plataforma. + Se estivermos compilando para neko (-x ou -neko), só teremos a + saudação de neko. + */ + + + trace("Loops e Interações"); + + // loop while + var k = 0; + while(k < 100){ + // trace(counter); // irá iprimir números de 0 a 99 + k++; + } + + // loop do-while + var l = 0; + do{ + trace("do sempre rodará pelo menos uma vez"); + } while (l > 0); + + // loop for + /* + Não há loop for no estilo C para Haxe, pois é propenso + a erros e não é necessário. Ao invés disso, Haxe possui + uma versão muito mais simples e segura que usa Iterators + (veremos isso logo mais). + */ + var m = [1,2,3]; + for (val in m){ + trace(val + " é o valor de val no array m"); + } + + // Perceba que você pode iterar em um índice usando uma lista limitada + // (veremos isso em breve também) + var n = ['foo', 'bar', 'baz']; + for (val in 0...n.length){ + trace(val + " é o valor de val (um índice de n)"); + } + + + trace("Compreensões de array"); + + // Compreensões de array servem para que você posse iterar um array + // enquanto cria filtros e modificações + var n_filtrado = [for (val in n) if (val != "foo") val]; + trace(n_filtrado + " é o valor de n_filtrado"); + + var n_modificado = [for (val in n) val += '!']; + trace(n_modificado + " é o valor de n_modificado"); + + var n_filtrado_e_modificado = [for (val in n) if (val != "foo") val += "!"]; + trace(n_filtrado_e_modificado + " é o valor de n_filtrado_e_modificado"); + + ////////////////////////////////////////////////////////////////// + // Blocos Switch (Tipos de valor) + ////////////////////////////////////////////////////////////////// + trace("***BLOCOS SWITCH (Tipos de valor)***"); + + /* + Blocos Switch no Haxe são muito poderosos. Além de funcionar com + valores básicos como strings e ints, também funcionam com tipos + algébricos em enums (falaremos sobre enums depois). + Veja alguns exemplos de valor básico por enquanto: + */ + var meu_cachorro = "fido"; + var coisa_favorita = ""; + switch(meu_cachorro){ + case "fido" : favorite_thing = "osso"; + case "rex" : favorite_thing = "sapato"; + case "spot" : favorite_thing = "bola de tênis"; + default : favorite_thing = "algum brinquedo desconhecido"; + // case _ : favorite_thing = "algum brinquedo desconhecido"; // mesma coisa que default + } + // O case "_" acima é um valor "coringa" que + // que funcionará para qualquer coisa. + + trace("O nome do meu cachorro é " + meu_cachorro + + ", e sua coisa favorita é: " + + coisa_favorita); + + ////////////////////////////////////////////////////////////////// + // Declarações de expressão + ////////////////////////////////////////////////////////////////// + trace("***DECLARAÇÕES DE EXPRESSÃO***"); + + /* + As declarações de controle em Haxe são muito poderosas pois + toda declaração também é uma expressão, considere o seguinte: + */ + + // declarações if + var k = if (true) 10 else 20; + + trace("k igual a ", k); // retorna 10 + + var outra_coisa_favorita = switch(meu_cachorro) { + case "fido" : "ursinho"; + case "rex" : "graveto"; + case "spot" : "bola de futebol"; + default : "algum brinquedo desconhecido"; + } + + trace("O nome do meu cachorro é " + meu cachorro + + ", e sua outra coisa favorita é: " + + outra_coisa_favorita); + + ////////////////////////////////////////////////////////////////// + // Convertendo tipos de valores + ////////////////////////////////////////////////////////////////// + trace("***CONVERTENDO TIPOS DE VALORES***"); + + // Você pode converter strings em ints de forma bem fácil. + + // string para int + Std.parseInt("0"); // retorna 0 + Std.parseFloat("0.4"); // retorna 0.4; + + // int para string + Std.string(0); // retorna "0"; + // concatenar com strings irá converter automaticamente em string. + 0 + ""; // retorna "0"; + true + ""; // retorna "true"; + // Veja a documentação de parseamento em Std para mais detalhes. + + + ////////////////////////////////////////////////////////////////// + // Lidando com Tipos + ////////////////////////////////////////////////////////////////// + + /* + Como mencionamos anteriormente, Haxe é uma linguagem tipada + estaticamente. Tipagem estática é uma coisa maravilhosa. Isto + permite autocompletar mais preciso, e pode ser usado para checar + completamente o funcionamento de um programa. Além disso, o compilador + Haxe é super rápido. + + *ENTRETANTO*, há momentos em que você espera que o compilador apenas + deixe algo passar, e não lance um "type error" em um determinado caso. + + Para fazer isso, Haxe tem duas palavras-chave separadas. A primeira + é o tipo "Dynamic": + */ + var din: Dynamic = "qualquer tipo de variável, assim como essa string"; + + /* + Tudo o que você sabe sobre uma variável Dynamic é que o compilador + não irá mais se preocupar com o tipo dela. É como uma variável + "coringa": você pode usar isso ao invés de qualquer tipo de variável, + e você pode atrelar qualquer valor a essa variável. + + A outra (e mais extrema) opção é a palavra-chave "untyped": + */ + + untyped { + var x:Int = 'foo'; // não faz sentido! + var y:String = 4; // loucura! + } + + /* + A palavra-chave "untyped" opera em *blocos* inteiros de código, + ignorando qualquer verificação de tipo que seria obrigatória em + outros casos. Essa palavra-chave deve ser usada com muita cautela, + como em situações limitadas de compilação condicional onde a + verificação de tipo pode ser um obstáculo. + + No geral, ignorar verificações de tipo *não* é recomendado. Use + os modelos de enum, herança ou estrutural para garantir o correto + funcionamento do seu programa. Só quando você tiver certeza de que + nenhum desses modelos funcionam no seu caso, você deve usar "Dynamic" + ou "untyped". + */ + + ////////////////////////////////////////////////////////////////// + // Programação básica orientada a objetos + ////////////////////////////////////////////////////////////////// + trace("***PROGRAMAÇÃO BÁSICA ORIENTADA A OBJETOS***"); + + + /* + Cria uma instância da FooClass. As definicções dessas classes + estão no final do arquivo. + */ + var instancia_foo = new FooClass(3); + + // lê a variável pública normalmente + trace(instancia_foo.variavel_publica + " é o valor de instancia_foo.variavel_publica"); + + // nós podemos ler essa variável + trace(instancia_foo.publica_leitura + " é o valor de instancia_foo.publica_leitura"); + // mas não podemos escrever nela + // instancia_foo.publica_leitura = 4; // isso irá causar um erro se descomentado: + // trace(instancia_foo.public_escrita); // e isso também. + + // chama o método toString: + trace(instancia_foo + " é o valor de instancia_foo"); + // mesma coisa: + trace(instancia_foo.toString() + " é o valor de instancia_foo.toString()"); + + + /* + A instancia_foo é do tipo "FooClass", enquanto acceptBarInstance + é do tipo BarClass. Entretanto, como FooClass extende BarClass, + ela é aceita. + */ + BarClass.acceptBarInstance(instancia_foo); + + /* + As classes abaixo têm mais alguns exemplos avançados, o método + "example()" executará esses exemplos aqui: + */ + SimpleEnumTest.example(); + ComplexEnumTest.example(); + TypedefsAndStructuralTypes.example(); + UsingExample.example(); + + } + +} + +/* + Essa é a "classe filha" do classe principal LearnHaxe3 + */ +class FooClass extends BarClass implements BarInterface{ + public var variavel_publica:Int; // variáveis públicas são acessíveis de qualquer lugar + public var publica_leitura (default, null): Int; // somente leitura pública habilitada + public var publica_escrita (null, default): Int; // somente escrita pública habilitada + public var property (get, set): Int; // use este estilo para habilitar getters e setters + + // variáveis privadas não estão disponíveis fora da classe. + // veja @:allow para formas de fazer isso. + var _private:Int; // variáveis são privadas se não forem marcadas como públicas + + // um construtor público + public function new(arg:Int){ + // chama o construtor do objeto pai, já que nós extendemos a BarClass: + super(); + + this.variavel_publica = 0; + this._private = arg; + + } + + // getter para _private + function get_property() : Int { + return _private; + } + + // setter para _private + function set_property(val:Int) : Int { + _private = val; + return val; + } + + // função especial que é chamada sempre que uma instância é convertida em string. + public function toString(){ + return _private + " com o método toString()!"; + } + + // essa classe precisa ter essa função definida, pois ela implementa + // a interface BarInterface + public function baseFunction(x: Int) : String{ + // converte o int em string automaticamente + return x + " foi passado pela baseFunction!"; + } +} + +/* + Uma classe simples para extendermos +*/ +class BarClass { + var base_variable:Int; + public function new(){ + base_variable = 4; + } + public static function acceptBarInstance(b:BarClass){ + } +} + +/* + Uma interface simples para implementarmos +*/ +interface BarInterface{ + public function baseFunction(x:Int):String; +} + +////////////////////////////////////////////////////////////////// +// Declarações Enum e Switch +////////////////////////////////////////////////////////////////// + +/* + Enums no Haxe são muito poderosos. Resumidamente, enums são + um tipo com um número limitado de estados: + */ + +enum SimpleEnum { + Foo; + Bar; + Baz; +} + +// Uma classe que faz uso desse enum: + +class SimpleEnumTest{ + public static function example(){ + var e_explicit:SimpleEnum = SimpleEnum.Foo; // você pode especificar o nome "completo" + var e = Foo; // bas descoberta de tipo também funciona. + switch(e){ + case Foo: trace("e era Foo"); + case Bar: trace("e era Bar"); + case Baz: trace("e era Baz"); // comente esta linha e teremos um erro. + } + + /* + Isso não parece tão diferente de uma alteração simples de valor em strings. + Entretanto, se nós não incluirmos *todos* os estados, o compilador + reclamará. Você pode testar isso comentando a linha mencionada acima. + + Você também pode especificar um valor padrão (default) para enums: + */ + switch(e){ + case Foo: trace("e é Foo outra vez"); + default : trace("default funciona aqui também"); + } + } +} + +/* + Enums vão muito mais além que estados simples, nós também + podemos enumerar *construtores*, mas nós precisaremos de um + exemplo mais complexo de enum: + */ +enum ComplexEnum{ + IntEnum(i:Int); + MultiEnum(i:Int, j:String, k:Float); + SimpleEnumEnum(s:SimpleEnum); + ComplexEnumEnum(c:ComplexEnum); +} +// Observação: O enum acima pode incluir *outros* enums também, incluindo ele mesmo! +// Observação: Isto é o que chamamos de *Tipos de dado algébricos* em algumas outras linguagens. + +class ComplexEnumTest{ + public static function example(){ + var e1:ComplexEnum = IntEnum(4); // especificando o parâmetro enum + /* + Agora nós podemos usar switch no enum, assim como extrair qualquer + parâmetros que ele possa ter. + */ + switch(e1){ + case IntEnum(x) : trace('$x foi o parâmetro passado para e1'); + default: trace("Isso não deve ser impresso"); + } + + // outro parâmetro aqui que também é um enum... um enum enum? + var e2 = SimpleEnumEnum(Foo); + switch(e2){ + case SimpleEnumEnum(s): trace('$s foi o parâmetro passado para e2'); + default: trace("Isso não deve ser impresso"); + } + + // enum dentro de enum dentro de enum + var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); + switch(e3){ + // Você pode buscar por certos enums aninhados especificando-os + // explicitamente: + case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : { + trace('$i, $j, e $k foram passados dentro desse monstro aninhado.'); + } + default: trace("Isso não deve ser impresso"); + } + /* + Veja outros "tipos de dado algébricos" (GADT, do inglês) para mais + detalhes sobre o porque eles são tão úteis. + */ + } +} + +class TypedefsAndStructuralTypes { + public static function example(){ + /* + Aqui nós usaremos tipos typedef, ao invés de tipos base. + Lá no começo, nós definimos que o tipo "FooString" é um tipo "String". + */ + var t1:FooString = "alguma string"; + + /* + Aqui nós usamos typedefs para "tipos estruturais" também. Esses tipos + são definidos pela sua estrutura de campos, não por herança de classe. + Aqui temos um objeto anônimo com um campo String chamado "foo": + */ + + var anon_obj = { foo: 'hi' }; + + /* + A variável anon_obj não tem um tipo declarado, e é um objeto anônimo + de acordo com o compilador. Entretanto, lembra que lá no início nós + declaramos a typedef FooObj? Visto que o anon_obj tem a mesma estrutura, + nós podemos usar ele em qualquer lugar que um "FooObject" é esperado. + */ + + var f = function(fo:FooObject){ + trace('$fo foi passado para esta função'); + } + f(anon_obj); // chama a assinatura de FooObject com anon_obj. + + /* + Note que typedefs podem ter campos opcionais também, marcados com "?" + + typedef OptionalFooObj = { + ?optionalString: String, + requiredInt: Int + } + */ + + /* + Typedefs também funcionam com compilação condicional. Por exemplo, + nós poderíamos ter incluído isso no topo deste arquivo: + +#if( js ) + typedef Surface = js.html.CanvasRenderingContext2D; +#elseif( nme ) + typedef Surface = nme.display.Graphics; +#elseif( !flash9 ) + typedef Surface = flash8.MovieClip; +#elseif( java ) + typedef Surface = java.awt.geom.GeneralPath; +#end + + E teríamos apenas um tipo "Surface" para funcionar em todas + essas plataformas. + */ + } +} + +class UsingExample { + public static function example() { + + /* + A palavra-chave "using" é um tipo especial de import de classe que + altera o comportamento de qualquer método estático na classe. + + Neste arquivo, nós aplicamos "using" em "StringTools", que contém + alguns métodos estáticos para tratar tipos String. + */ + trace(StringTools.endsWith("foobar", "bar") + " deve ser verdadeiro!"); + + /* + Com um import "using", o primeiro argumento é extendido com o método. + O que isso significa? Bem, como "endsWith" tem um primeiro argumento + de tipo "String", isso significa que todos os tipos "String" agora + possuem o método "endsWith": + */ + trace("foobar".endsWith("bar") + " deve ser verdadeiro!"); + + /* + Essa técnica habilita uma grande quantidade de expressões para certos + tipos, e limita o escopo de modificações para um único arquivo. + + Note que a instância String *não* é modificada em tempo de execução. + O novo método adicionado não é uma parte da instância anexada, e o + compilador ainda irá gerar o código equivalente ao método estático. + */ + } + +} + +``` +Isso foi apenas o começo do que Haxe pode fazer. Para uma documentação de todos +os recursos de Haxe, veja o [manual](https://haxe.org/manual) e a +[documentação de API](https://api.haxe.org/). Para um diretório de bibliotecas de terceiros +disponíveis, veja a [Haxelib](https://lib.haxe.org/) + +Para tópicos mais avançados, dê uma olhada em: + +* [Tipos abstratos](https://haxe.org/manual/types-abstract.html) +* [Macros](https://haxe.org/manual/macro.html) +* [Recursos do compilador](https://haxe.org/manual/cr-features.html) + +Por fim, participe do [forum Haxe](https://community.haxe.org/), +ou no IRC [#haxe onfreenode](http://webchat.freenode.net/), ou no +[Chat Gitter](https://gitter.im/HaxeFoundation/haxe). -- cgit v1.2.3 From 89f7b984478df1098beab78d9180ceac18e64276 Mon Sep 17 00:00:00 2001 From: bobdc Date: Wed, 31 Oct 2018 15:40:15 -0400 Subject: Update sql.html.markdown --- sql.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/sql.html.markdown b/sql.html.markdown index 8f200344..0638a731 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -3,7 +3,6 @@ language: SQL filename: learnsql.sql contributors: - ["Bob DuCharme", "http://bobdc.com/"] -https://github.com/adambard/learnxinyminutes-docs --- Structured Query Language (SQL) is an ISO standard language for creating and working with databases stored in a set of tables. Implementations usually add their own extensions to the language; [Comparison of different SQL implementations](http://troels.arvin.dk/db/rdbms/) is a good reference on product differences. -- cgit v1.2.3 From d553a02345298eabe3eb5e567bdc478dff773c81 Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Wed, 31 Oct 2018 18:10:03 -0300 Subject: [Dynamic programming - FR/FR] Fixed links --- fr-fr/dynamic-programming-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index 0a22b58b..ea547dae 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -42,7 +42,7 @@ Le même concept peut être appliqué pour trouver le chemin le plus long dans u ### Problèmes classiques de programmation dynamique -- [L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]) +- [L'algorithme de Floyd Warshall(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) - [Problème du sac à dos(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) - [Plus longue sous-chaîne commune(EN) - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) -- cgit v1.2.3 From 0838b7203a481d2bfb82f03bb6f6dbe54ed8bbb2 Mon Sep 17 00:00:00 2001 From: LukaxFeh Date: Wed, 31 Oct 2018 18:16:41 -0300 Subject: [Dynamic programming - NL/NL] Fixed links --- nl-nl/dynamic-programming-nl.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nl-nl/dynamic-programming-nl.html.markdown b/nl-nl/dynamic-programming-nl.html.markdown index 5186a3bf..e56a9774 100644 --- a/nl-nl/dynamic-programming-nl.html.markdown +++ b/nl-nl/dynamic-programming-nl.html.markdown @@ -46,9 +46,9 @@ for i=0 to n-1 ### Enkele beroemde DP problemen -- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- [Floyd Warshall Algorithm - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- [Integer Knapsack Problem - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- [Longest Common Subsequence - Tutorial and C Program source code](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Online Bronnen -- cgit v1.2.3 From ca98611c099b2108c37c603440338d1b7ba6cdfb Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 2 Nov 2018 04:21:54 +0530 Subject: Fix exception handling example --- php.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 3b18aa60..40c9dd01 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -837,11 +837,14 @@ try { // Handle exception } -// When using try catch blocks in a namespaced environment use the following +// When using try catch blocks in a namespaced environment it is important to +// escape to the global namespace, because Exceptions are classes, and the +// Exception class exists in the global namespace. This can be done using a +// leading backslash to catch the Exception. try { // Do something -} catch (Exception $e) { +} catch (\Exception $e) { // Handle exception } -- cgit v1.2.3 From 833714f75ec5b61291c086a98238f4e570ea8fa8 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 2 Nov 2018 04:43:08 +0530 Subject: Update csharp-pt.html.markdown Remove unnecessary newline --- pt-br/csharp-pt.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 2b61a8fa..53fb11e9 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -97,7 +97,6 @@ namespace Learning.CSharp // Decimal - um tipo de dados de 128 bits, com mais precisão do que outros tipos de ponto flutuante, // adequado para cálculos financeiros e monetários - decimal fooDecimal = 150.3m; // Boolean - true & false -- cgit v1.2.3 From 2c6ec2ba23191a609c37cdaf190bdb60e0d1aa34 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 2 Nov 2018 05:04:53 +0530 Subject: Update markdown-cn.html.markdown Convert HTML tags to markdown syntax --- zh-cn/markdown-cn.html.markdown | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index e5996984..2bd8d11a 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -242,19 +242,21 @@ Markdown 最棒的地方就是便捷的书写链接。把链接文字放在中 Markdown同样支持引用形式的链接 -
        [点此链接][link1] 以获取更多信息!
        -[看一看这个链接][foobar] 如果你愿意的话。
        -
        -[link1]: http://test.com/ "Cool!"
        -[foobar]: http://foobar.biz/ "Alright!"
        +```md +[点此链接][link1] 以获取更多信息! +[看一看这个链接][foobar] 如果你愿意的话。 +[link1]: http://test.com/ +[foobar]: http://foobar.biz/ +``` 对于引用形式,链接的标题可以处于单引号中,括弧中或是忽略。引用名可以在文档的任何地方,并且可以随意命名,只要名称不重复。 “隐含式命名” 的功能可以让链接文字作为引用名 -
        [This][] is a link.
        -
        -[this]: http://thisisalink.com/
        +```md +[This][] is a link. +[This]: http://thisisalink.com/ +``` 但这并不常用 @@ -267,9 +269,10 @@ Markdown同样支持引用形式的链接 引用形式也同样起作用 -
        ![这是alt][myimage]
        -
        -[myimage]: relative/urls/cool/image.jpg "在此输入标题"
        +```md +![这是alt][myimage] +[myimage]: relative/urls/cool/image.jpg +``` ## 杂项 ### 自动链接 -- cgit v1.2.3 From 3dcb56bc220ce48e07f74ef2a912794480f884ea Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Fri, 2 Nov 2018 14:47:22 +0530 Subject: Fix R ggplot error, closes #2237 --- r.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/r.html.markdown b/r.html.markdown index e7486e60..a8b04be2 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -789,7 +789,7 @@ install.packages("ggplot2") require(ggplot2) ?ggplot2 pp <- ggplot(students, aes(x=house)) -pp + geom_histogram() +pp + geom_bar() ll <- as.data.table(list1) pp <- ggplot(ll, aes(x=time,price)) pp + geom_point() -- cgit v1.2.3 From eabb26c70eb207d98ebf5e14e8f1d94dfeb61c76 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 4 Nov 2018 09:26:31 -0800 Subject: Use dash commenting on sql doc instead --- sql.html.markdown | 82 +++++++++++++++++++++++++++---------------------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/sql.html.markdown b/sql.html.markdown index 0638a731..200f4f98 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -13,93 +13,93 @@ Several of these sample commands assume that the [MySQL employee sample database ```sql -# Comments start with a pound sign. End each command with a semicolon. +-- Comments start with two hyphens. End each command with a semicolon. -# SQL is not case-sensitive about keywords. The sample commands here -# follow the convention of spelling them in upper-case because it makes -# it easier to distinguish them from database, table, and column names. +-- SQL is not case-sensitive about keywords. The sample commands here +-- follow the convention of spelling them in upper-case because it makes +-- it easier to distinguish them from database, table, and column names. -# Create and delete a database. Database and table names are case-sensitive. +-- Create and delete a database. Database and table names are case-sensitive. CREATE DATABASE someDatabase; DROP DATABASE someDatabase; -# List available databases. +-- List available databases. SHOW DATABASES; -# Use a particular existing database. +-- Use a particular existing database. USE employees; -# Select all rows and columns from the current database's departments table. -# Default activity is for the interpreter to scroll the results on your screen. +-- Select all rows and columns from the current database's departments table. +-- Default activity is for the interpreter to scroll the results on your screen. SELECT * FROM departments; -# Retrieve all rows from the departments table, -# but only the dept_no and dept_name columns. -# Splitting up commands across lines is OK. +-- Retrieve all rows from the departments table, +-- but only the dept_no and dept_name columns. +-- Splitting up commands across lines is OK. SELECT dept_no, dept_name FROM departments; -# Retrieve all departments columns, but just 5 rows. +-- Retrieve all departments columns, but just 5 rows. SELECT * FROM departments LIMIT 5; -# Retrieve dept_name column values from the departments -# table where the dept_name value has the substring "en". +-- Retrieve dept_name column values from the departments +-- table where the dept_name value has the substring "en". SELECT dept_name FROM departments WHERE dept_name LIKE "%en%"; -# Retrieve all columns from the departments table where the dept_name -# column starts with an "S" and has exactly 4 characters after it. +-- Retrieve all columns from the departments table where the dept_name +-- column starts with an "S" and has exactly 4 characters after it. SELECT * FROM departments WHERE dept_name LIKE "S____"; -# Select title values from the titles table but don't show duplicates. +-- Select title values from the titles table but don't show duplicates. SELECT DISTINCT title FROM titles; -# Same as above, but sorted (case-sensitive) by the title values. +-- Same as above, but sorted (case-sensitive) by the title values. SELECT DISTINCT title FROM titles ORDER BY title; -# Show the number of rows in the departments table. +-- Show the number of rows in the departments table. SELECT COUNT(*) FROM departments; -# Show the number of rows in the departments table that -# have "en" as a substring of the dept_name value. +-- Show the number of rows in the departments table that +-- have "en" as a substring of the dept_name value. SELECT COUNT(*) FROM departments WHERE dept_name LIKE "%en%"; -# A JOIN of information from multiple tables: the titles table shows -# who had what job titles, by their employee numbers, from what -# date to what date. Retrieve this information, but instead of the -# employee number, use the employee number as a cross-reference to -# the employees table to get each employee's first and last name -# instead. (And only get 10 rows.) +-- A JOIN of information from multiple tables: the titles table shows +-- who had what job titles, by their employee numbers, from what +-- date to what date. Retrieve this information, but instead of the +-- employee number, use the employee number as a cross-reference to +-- the employees table to get each employee's first and last name +-- instead. (And only get 10 rows.) SELECT employees.first_name, employees.last_name, titles.title, titles.from_date, titles.to_date FROM titles INNER JOIN employees ON employees.emp_no = titles.emp_no LIMIT 10; -# List all the tables in all the databases. Implementations typically provide -# their own shortcut command to do this with the database currently in use. +-- List all the tables in all the databases. Implementations typically provide +-- their own shortcut command to do this with the database currently in use. SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'; -# Create a table called tablename1, with the two columns shown, for -# the database currently in use. Lots of other options are available -# for how you specify the columns, such as their datatypes. +-- Create a table called tablename1, with the two columns shown, for +-- the database currently in use. Lots of other options are available +-- for how you specify the columns, such as their datatypes. CREATE TABLE tablename1 (`fname` VARCHAR(20),`lname` VARCHAR(20)); -# Insert a row of data into the table tablename1. This assumes that the -# table has been defined to accept these values as appropriate for it. +-- Insert a row of data into the table tablename1. This assumes that the +-- table has been defined to accept these values as appropriate for it. INSERT INTO tablename1 VALUES('Richard','Mutt'); -# In tablename1, change the fname value to "John" -# for all rows that have an lname value of "Mutt". +-- In tablename1, change the fname value to "John" +-- for all rows that have an lname value of "Mutt". UPDATE tablename1 SET fname="John" WHERE lname="Mutt"; -# Delete rows from the tablename1 table -# where the lname value begins with "M". +-- Delete rows from the tablename1 table +-- where the lname value begins with "M". DELETE FROM tablename1 WHERE lname like "M%"; -# Delete all rows from the tablename1 table, leaving the empty table. +-- Delete all rows from the tablename1 table, leaving the empty table. DELETE FROM tablename1; -# Remove the entire tablename1 table. +-- Remove the entire tablename1 table. DROP TABLE tablename1; ``` -- cgit v1.2.3 From f363c6459f31665ef3d635a6a22cc25ef6a146b5 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 4 Nov 2018 09:37:45 -0800 Subject: Use single quotes --- sql.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/sql.html.markdown b/sql.html.markdown index 200f4f98..392b0edf 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -27,7 +27,7 @@ DROP DATABASE someDatabase; SHOW DATABASES; -- Use a particular existing database. -USE employees; +USE employees; -- Select all rows and columns from the current database's departments table. -- Default activity is for the interpreter to scroll the results on your screen. @@ -43,12 +43,12 @@ SELECT dept_no, SELECT * FROM departments LIMIT 5; -- Retrieve dept_name column values from the departments --- table where the dept_name value has the substring "en". -SELECT dept_name FROM departments WHERE dept_name LIKE "%en%"; +-- table where the dept_name value has the substring 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; -- Retrieve all columns from the departments table where the dept_name --- column starts with an "S" and has exactly 4 characters after it. -SELECT * FROM departments WHERE dept_name LIKE "S____"; +-- column starts with an 'S' and has exactly 4 characters after it. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; -- Select title values from the titles table but don't show duplicates. SELECT DISTINCT title FROM titles; @@ -60,8 +60,8 @@ SELECT DISTINCT title FROM titles ORDER BY title; SELECT COUNT(*) FROM departments; -- Show the number of rows in the departments table that --- have "en" as a substring of the dept_name value. -SELECT COUNT(*) FROM departments WHERE dept_name LIKE "%en%"; +-- have 'en' as a substring of the dept_name value. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; -- A JOIN of information from multiple tables: the titles table shows -- who had what job titles, by their employee numbers, from what @@ -89,13 +89,13 @@ CREATE TABLE tablename1 (`fname` VARCHAR(20),`lname` VARCHAR(20)); -- table has been defined to accept these values as appropriate for it. INSERT INTO tablename1 VALUES('Richard','Mutt'); --- In tablename1, change the fname value to "John" --- for all rows that have an lname value of "Mutt". -UPDATE tablename1 SET fname="John" WHERE lname="Mutt"; +-- In tablename1, change the fname value to 'John' +-- for all rows that have an lname value of 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; -- Delete rows from the tablename1 table --- where the lname value begins with "M". -DELETE FROM tablename1 WHERE lname like "M%"; +-- where the lname value begins with 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; -- Delete all rows from the tablename1 table, leaving the empty table. DELETE FROM tablename1; -- cgit v1.2.3 From 45d49bc05ede7bb038dbdc7e8f5962497645bb3b Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 4 Nov 2018 09:52:15 -0800 Subject: Eschew backticks in sql --- sql.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql.html.markdown b/sql.html.markdown index 392b0edf..2bece208 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -83,7 +83,7 @@ WHERE TABLE_TYPE='BASE TABLE'; -- Create a table called tablename1, with the two columns shown, for -- the database currently in use. Lots of other options are available -- for how you specify the columns, such as their datatypes. -CREATE TABLE tablename1 (`fname` VARCHAR(20),`lname` VARCHAR(20)); +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); -- Insert a row of data into the table tablename1. This assumes that the -- table has been defined to accept these values as appropriate for it. -- cgit v1.2.3 From e59fd86ee14240c6967ff117d6f685bed1c50b0f Mon Sep 17 00:00:00 2001 From: AlburIvan Date: Sun, 4 Nov 2018 21:40:27 -0400 Subject: Fix tildes & other miss translated words --- es-es/coldfusion-es.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/es-es/coldfusion-es.html.markdown b/es-es/coldfusion-es.html.markdown index 5bddcb85..50c3787c 100644 --- a/es-es/coldfusion-es.html.markdown +++ b/es-es/coldfusion-es.html.markdown @@ -21,7 +21,7 @@ ColdFusion comenzó como un lenguaje basado en etiquetas. Casi toda la funcional " ---> @@ -153,7 +153,7 @@ ColdFusion comenzó como un lenguaje basado en etiquetas. Casi toda la funcional
        -

        Tipos de conversión

        +

        Conversión de tipos