Merge pull request #1 from adambard/master

ff
This commit is contained in:
SmuSmu 2018-10-29 10:38:48 +01:00 committed by GitHub
commit 1372607b2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
246 changed files with 31626 additions and 3134 deletions

View File

@ -81,7 +81,7 @@ supports R5RS and R7RS (work in progress) standards and many extensions.
(string-append "pine" "apple") ;; => "pineapple"
(string-ref "tapioca" 3) ;; => #\i;; character 'i' is at index 3
(string->list "CHICKEN") ;; => (#\C #\H #\I #\C #\K #\E #\N)
(string->intersperse '("1" "2") ":") ;; => "1:2"
(string-intersperse '("1" "2") ":") ;; => "1:2"
(string-split "1:2:3" ":") ;; => ("1" "2" "3")

View File

@ -71,3 +71,10 @@ contributors:
lang: ep-ep
---
```
### Should I add myself as a Contributor?
If you want to add yourself to contributors, keep in mind that contributors get
equal billing, and the first contributor usually wrote the whole article. Please
use your judgement when deciding if your contribution constitutes a substantial
addition or not.

View File

@ -1,3 +1,12 @@
## Is this a major issue that you cannot fix?
**Being a community driven documents of languages and tools,"YOUR" contributions
are also important.
If the issue you're reporting is trivial to report to maintainers why not contribute
to fix it. In that way, you will have contributed to an awesome open-source project.
The changes can be typo fix, fixing of data in examples or grammar fix. If you found it,
why not do it and take full credit for it?**
Make sure the issue title is prepended with '[language/lang-code]' if the language is
already on the site.
If it's a request for a new language, use: '[Request] [language/lang-code]'

663
ansible.html.markdown Normal file
View File

@ -0,0 +1,663 @@
---
category: tool
tool: ansible
contributors:
- ["Jakub Muszynski" , "http://github.com/sirkubax"]
filename: LearnAnsible.txt
---
```yml
---
"{{ 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
# Universal way
$ pip install ansible
# Debian, Ubuntu
$ apt-get 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)
```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"
}
```
### Shell 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!
### Module
_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).
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 execution - `ping`, `shell`
```bash
$ 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. The command module is more secure, because it will not be affected by the users environment. For more complex command - use shell module.
```bash
$ ansible -m command -a 'date; whoami' # FAILURE
$ ansible -m command -a 'date' all
$ 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)
### 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`. See above how you were using them already.
### 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.
You can think that playbook is very advanced CLI script that you are executing.
#### Example of the playbook:
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
```yml
- hosts: all
tasks:
- name: "ping all"
ping:
- name: "execute a shell command"
shell: "date; whoami; df -h;"
```
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
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
1.2.3.4
[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 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.
**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 via your playbook).
```yml
- 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
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: https://github.com/sirkubax/ansible-for-learnXinYminutes
```bash
$ # 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
$
$ # First lets execute the simple_playbook.yml
(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_playbook.yml
```
Run the 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/simple_role.yml
```
#### Role directory structure:
```
roles/
some_role/
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 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
[read more](http://docs.ansible.com/ansible/latest/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable)
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 (load shell command output into variable!)
* file
* stream
* etcd
* password management tools
* url
```bash
# read playbooks/lookup.yml
# then 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 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.
```
(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/register_and_when.yml
```
```yaml
---
- 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 }}"
# when: example
- 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 - 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`)
```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
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, and then run only the tagged resources
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
--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
ansible-playbook playbooks/simple_playbook.yml --limmit localhost
--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.
```jinja2
Some static content
{{ a_variable }}
{% for item in loop_items %}
this line item is {{ item }}
{% endfor %}
```
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
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.
```jinja
# get first item of the list
{{ some_list | first() }}
# if variable is undefined - use default value
{{ some_variable | default('default_value') }}
```
[Read More](http://docs.ansible.com/ansible/latest/playbooks_filters.html)
### ansible-vault
To maintain **ifrastructure as a code** you need to store secrets.
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.
```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 use env
$ export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file
$ ansible-playbook playbooks/vault_example.yml
# encrypt 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.
[AWS example](http://docs.ansible.com/ansible/latest/intro_dynamic_inventory.html#example-aws-ec2-external-inventory-script)
```bash
$ etc/inv/ec2.py --refresh
$ ansible -m ping all -i etc/inv/ec2.py
```
[Read more](http://docs.ansible.com/ansible/latest/intro_dynamic_inventory.html)
### 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 built-in callback for task execution profiling
```
vi ansible.cfg
#set this to:
callback_whitelist = profile_tasks
```
### 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.
```
vi ansible.cfg
# 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
```
I like to use `jsonfile` as my backend. It allows to use another project
`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 [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
- 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
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 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
$ rm -rf venv2
$ source environment2.sh
# execute playbook
(venv2)$ ansible-playbook playbooks/ansible1.9_playbook.yml # would fail - deprecated syntax
# 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!
# please note that you have both venv1.9 and venv2 present - you need to (de)activate one - that is all
```
#### 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)
## Tips and tricks
#### --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 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'
```bash
ansible -m ping web*
```
####
Host groups can be joined, negated, etc
```bash
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 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 - 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.
#### Conditionals: when:
#### 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.
'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...)
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
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
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.
#### 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.
#### 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).
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.

View File

@ -155,7 +155,7 @@ Small-o, commonly written as **o**, is an Asymptotic Notation to denote the
upper bound (that is not asymptotically tight) on the growth rate of runtime
of an algorithm.
`f(n)` is o(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
`f(n)` is o(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is < `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of O-notation and o-notation are similar. The main difference
@ -168,7 +168,7 @@ Small-omega, commonly written as **ω**, is an Asymptotic Notation to denote
the lower bound (that is not asymptotically tight) on the growth rate of
runtime of an algorithm.
`f(n)` is ω(g(n)), if for some real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
`f(n)` is ω(g(n)), if for all real constants c (c > 0) and n<sub>0</sub> (n<sub>0</sub> > 0), `f(n)` is > `c g(n)`
for every input size n (n > n<sub>0</sub>).
The definitions of Ω-notation and ω-notation are similar. The main difference

View File

@ -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.
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? 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
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 = 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 += 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(a, b) # 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)

View File

@ -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
---
@ -25,7 +26,7 @@ Nearly all examples below can be a part of a shell script or executed directly i
[Read more here.](http://www.gnu.org/software/bash/manual/bashref.html)
```bash
#!/bin/bash
#!/usr/bin/env bash
# First line of the script is shebang which tells the system how to execute
# the script: http://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured, comments start with #. Shebang is also a comment.
@ -76,6 +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: -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"}
@ -83,6 +89,25 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.
# Declare an array with 6 elements
array0=(one two three four five six)
# Print first element
echo $array0 # => "one"
# Print first element
echo ${array0[0]} # => "one"
# Print all elements
echo ${array0[@]} # => "one two three four five six"
# Print number of elements
echo ${#array0[@]} # => "6"
# Print number of characters in third element
echo ${#array0[2]} # => "5"
# Print 2 elements starting from forth
echo ${array0[@]:3:2} # => "four five"
# Print all elements. Each of them on new line.
for i in "${array0[@]}"; do
echo "$i"
done
# Brace Expansion { }
# Used to generate arbitrary strings
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
@ -155,6 +180,23 @@ 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 http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
# Redefine command 'ping' as alias to send only 5 packets
alias ping='ping -c 5'
# Escape alias and use command with this name instead
\ping 192.168.1.1
# Print all aliases
alias -p
# Expressions are denoted with the following format:
echo $(( 10 + 5 )) # => 15
@ -202,10 +244,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")
@ -230,6 +275,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:

View File

@ -1,6 +1,6 @@
---
language: "Brainfuck"
filename: brainfuck.bf
language: bf
filename: bf.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]

View File

@ -0,0 +1,593 @@
---
language: Logtalk
filename: llearnlogtalk-bg.lgt
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) за повече информация.

View File

@ -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 <cstdio>
//The C standard version:
#include <stdio.h>
int main()
{
printf("Hello, world!\n");
@ -1051,6 +1057,8 @@ 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 efficient but
// do not preserve order. unordered_set is available since C++11
// Map
// Maps store elements formed by a combination of a key value
@ -1078,6 +1086,8 @@ cout << it->second;
// Output: 26
// NOTE: For hash maps, use unordered_map. They are more efficient but do
// not preserve order. unordered_map is available since C++11.
///////////////////////////////////
// Logical and Bitwise operators
@ -1127,7 +1137,6 @@ compl 4 // Performs a bitwise not
```
Further Reading:
An up-to-date language reference can be found at
<http://cppreference.com/w/cpp>
Additional resources may be found at <http://cplusplus.com>
* 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).

View File

@ -8,6 +8,8 @@ contributors:
- ["Marco Scannadinari", "https://marcoms.github.io"]
- ["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.
@ -17,13 +19,14 @@ 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. Using some
> stricter compiler flags is recommended. Here is an example you can
> tweak to your liking:
>
> `-Wall -Wextra -Werror -O0 -ansi -pedantic -std=c11`
> 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:
>
> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic`
>
> For information on what these flags do as well as other flags, consult the man page for your C compiler (e.g. `man 1 gcc`) or just search online.
```c
// Single-line comments start with // - only available in C99 and later.
@ -87,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;
@ -99,7 +104,7 @@ int main (int argc, char** argv)
char y_char = 'y'; // Char literals are quoted with ''
// longs are often 4 to 8 bytes; long longs are guaranteed to be at least
// 64 bits
// 8 bytes
long x_long = 0;
long long x_long_long = 0;
@ -139,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
@ -372,8 +388,8 @@ int main (int argc, char** argv)
// respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from <limits.h>
// 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);
///////////////////////////////////////
@ -431,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
@ -447,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));
@ -520,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;
@ -587,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**
///////////////////////////////////////
@ -701,7 +727,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 %

View File

@ -2,11 +2,11 @@
language: chapel
filename: learnchapel.chpl
contributors:
- ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"]
- ["Ben Harshbarger", "http://github.com/benharsh/"]
- ["Ian J. Bertolacci", "https://www.cs.arizona.edu/~ianbertolacci/"]
- ["Ben Harshbarger", "https://github.com/benharsh/"]
---
You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com).
You can read all about Chapel at [Cray's official Chapel website](https://chapel-lang.org).
In short, Chapel is an open-source, high-productivity, parallel-programming
language in development at Cray Inc., and is designed to run on multi-core PCs
as well as multi-kilocore supercomputers.
@ -100,7 +100,7 @@ writeln(varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg);
// be made to alias a variable other than the variable it is initialized with.
// Here, refToActual refers to actual.
var actual = 10;
ref refToActual = actual;
ref refToActual = actual;
writeln(actual, " == ", refToActual); // prints the same value
actual = -123; // modify actual (which refToActual refers to)
writeln(actual, " == ", refToActual); // prints the same value
@ -444,7 +444,7 @@ arrayFromLoop = [value in arrayFromLoop] value + 1;
// Procedures
// Chapel procedures have similar syntax functions in other languages.
// Chapel procedures have similar syntax functions in other languages.
proc fibonacci(n : int) : int {
if n <= 1 then return n;
return fibonacci(n-1) + fibonacci(n-2);
@ -893,7 +893,6 @@ foo();
// We can declare a main procedure, but all the code above main still gets
// executed.
proc main() {
writeln("PARALLELISM START");
// A begin statement will spin the body of that statement off
// into one new task.
@ -1124,16 +1123,16 @@ This tutorial is for people who want to learn the ropes of chapel without
having to hear about what fiber mixture the ropes are, or how they were
braided, or how the braid configurations differ between one another. It won't
teach you how to develop amazingly performant code, and it's not exhaustive.
Refer to the [language specification](http://chapel.cray.com/language.html) and
the [module documentation](http://chapel.cray.com/docs/latest/) for more
Refer to the [language specification](https://chapel-lang.org/docs/latest/language/spec.html) and
the [module documentation](https://chapel-lang.org/docs/latest/) for more
details.
Occasionally check back here and on the [Chapel site](http://chapel.cray.com)
Occasionally check back here and on the [Chapel site](https://chapel-lang.org)
to see if more topics have been added or more tutorials created.
### What this tutorial is lacking:
* Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html)
* Exposition of the [standard modules](https://chapel-lang.org/docs/latest/modules/standard.html)
* Multiple Locales (distributed memory system)
* Records
* Parallel iterators
@ -1141,11 +1140,13 @@ to see if more topics have been added or more tutorials created.
Your input, questions, and discoveries are important to the developers!
-----------------------------------------------------------------------
The Chapel language is still in-development (version 1.16.0), so there are
The Chapel language is still in active development, so there are
occasional hiccups with performance and language features. The more information
you give the Chapel development team about issues you encounter or features you
would like to see, the better the language becomes. Feel free to email the team
and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman).
would like to see, the better the language becomes.
There are several ways to interact with the developers:
+ [Gitter chat](https://gitter.im/chapel-lang/chapel)
+ [sourceforge email lists](https://sourceforge.net/p/chapel/mailman)
If you're really interested in the development of the compiler or contributing
to the project, [check out the master GitHub repository](https://github.com/chapel-lang/chapel).
@ -1154,12 +1155,14 @@ It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0)
Installing the Compiler
-----------------------
[The Official Chapel documentation details how to download and compile the Chapel compiler.](https://chapel-lang.org/docs/usingchapel/QUICKSTART.html)
Chapel can be built and installed on your average 'nix machine (and cygwin).
[Download the latest release version](https://github.com/chapel-lang/chapel/releases/)
and it's as easy as
1. `tar -xvf chapel-1.16.0.tar.gz`
2. `cd chapel-1.16.0`
1. `tar -xvf chapel-<VERSION>.tar.gz`
2. `cd chapel-<VERSION>`
3. `source util/setchplenv.bash # or .sh or .csh or .fish`
4. `make`
5. `make check # optional`

212
citron.html.markdown Normal file
View File

@ -0,0 +1,212 @@
---
language: citron
filename: learncitron.ctr
contributors:
- ["AnotherTest", ""]
lang: en-us
---
```ruby
# Comments start with a '#'
# All comments encompass a single line
###########################################
## 1. Primitive Data types and Operators
###########################################
# You have numbers
3. # 3
# Numbers are all doubles in interpreted mode
# Mathematical operator precedence is not respected.
# binary 'operators' are evaluated in ltr order
1 + 1. # 2
8 - 4. # 4
10 + 2 * 3. # 36
# Division is always floating division
35 / 2 # 17.5.
# Integer division is non-trivial, you may use floor
(35 / 2) floor # 17.
# Booleans are primitives
True.
False.
# Boolean messages
True not. # False
False not. # True
1 = 1. # True
1 !=: 1. # False
1 < 10. # True
# Here, `not` is a unary message to the object `Boolean`
# Messages are comparable to instance method calls
# And they have three different forms:
# 1. Unary messages: Length > 1, and they take no arguments:
False not.
# 2. Binary Messages: Length = 1, and they take a single argument:
False & True.
# 3. Keyword messages: must have at least one ':', they take as many arguments
# as they have `:` s
False either: 1 or: 2. # 2
# Strings
'This is a string'.
'There are no character types exposed to the user'.
# "You cannot use double quotes for strings" <- Error
# Strins can be summed
'Hello, ' + 'World!'. # 'Hello, World!'
# Strings allow access to their characters
'This is a beautiful string' at: 0. # 'T'
###########################################
## intermission: Basic Assignment
###########################################
# You may assign values to the current scope:
var name is value. # assignes `value` into `name`
# You may also assign values into the current object's namespace
my name is value. # assigns `value` into the current object's `name` property
# Please note that these names are checked at compile (read parse if in interpreted mode) time
# but you may treat them as dynamic assignments anyway
###########################################
## 2. Lists(Arrays?) and Tuples
###########################################
# Arrays are allowed to have multiple types
Array new < 1 ; 2 ; 'string' ; Nil. # Array new < 1 ; 2 ; 'string' ; Nil
# Tuples act like arrays, but are immutable.
# Any shenanigans degrade them to arrays, however
[1, 2, 'string']. # [1, 2, 'string']
# They can interoperate with arrays
[1, 'string'] + (Array new < 'wat'). # Array new < 1 ; 'string' ; 'wat'
# Indexing into them
[1, 2, 3] at: 1. # 2
# Some array operations
var arr is Array new < 1 ; 2 ; 3.
arr head. # 1
arr tail. # Array new < 2 ; 3.
arr init. # Array new < 1 ; 2.
arr last. # 3
arr push: 4. # Array new < 1 ; 2 ; 3 ; 4.
arr pop. # 4
arr pop: 1. # 2, `arr` is rebound to Array new < 1 ; 3.
# List comprehensions
[x * 2 + y,, arr, arr + [4, 5],, x > 1]. # Array ← 7 ; 9 ; 10 ; 11
# fresh variable names are bound as they are encountered,
# so `x` is bound to the values in `arr`
# and `y` is bound to the values in `arr + [4, 5]`
#
# The general format is: [expr,, bindings*,, predicates*]
####################################
## 3. Functions
####################################
# A simple function that takes two variables
var add is {:a:b ^a + b.}.
# this function will resolve all its names except the formal arguments
# in the context it is called in.
# Using the function
add applyTo: 3 and: 5. # 8
add applyAll: [3, 5]. # 8
# Also a (customizable -- more on this later) pseudo-operator allows for a shorthand
# of function calls
# By default it is REF[args]
add[3, 5]. # 8
# To customize this behaviour, you may simply use a compiler pragma:
#:callShorthand ()
# And then you may use the specified operator.
# Note that the allowed 'operator' can only be made of any of these: []{}()
# And you may mix-and-match (why would anyone do that?)
add(3, 5). # 8
# You may also use functions as operators in the following way:
3 `add` 5. # 8
# This call binds as such: add[(3), 5]
# because the default fixity is left, and the default precedance is 1
# You may change the precedence/fixity of this operator with a pragma
#:declare infixr 1 add
3 `add` 5. # 8
# now this binds as such: add[3, (5)].
# There is another form of functions too
# So far, the functions were resolved in a dynamic fashion
# But a lexically scoped block is also possible
var sillyAdd is {\:x:y add[x,y].}.
# In these blocks, you are not allowed to declare new variables
# Except with the use of Object::'letEqual:in:`
# And the last expression is implicitly returned.
# You may also use a shorthand for lambda expressions
var mul is \:x:y x * y.
# These capture the named bindings that are not present in their
# formal parameters, and retain them. (by ref)
###########################################
## 5. Control Flow
###########################################
# inline conditional-expressions
var citron is 1 = 1 either: 'awesome' or: 'awful'. # citron is 'awesome'
# multiple lines is fine too
var citron is 1 = 1
either: 'awesome'
or: 'awful'.
# looping
10 times: {:x
Pen writeln: x.
}. # 10. -- side effect: 10 lines in stdout, with numbers 0 through 9 in them
# Citron properly supports tail-call recursion in lexically scoped blocks
# So use those to your heart's desire
# mapping most data structures is as simple as `fmap:`
[1, 2, 3, 4] fmap: \:x x + 1. # [2, 3, 4, 5]
# You can use `foldl:accumulator:` to fold a list/tuple
[1, 2, 3, 4] foldl: (\:acc:x acc * 2 + x) accumulator: 4. # 90
# That expression is the same as
(2 * (2 * (2 * (2 * 4 + 1) + 2) + 3) + 4)
###################################
## 6. IO
###################################
# IO is quite simple
# With `Pen` being used for console output
# and Program::'input' and Program::'waitForInput' being used for console input
Pen writeln: 'Hello, ocean!' # prints 'Hello, ocean!\n' to the terminal
Pen writeln: Program waitForInput. # reads a line and prints it back
```

View File

@ -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

View File

@ -4,82 +4,91 @@ language: "Common Lisp"
filename: commonlisp.lisp
contributors:
- ["Paul Nathan", "https://github.com/pnathan"]
- ["Rommel Martinez", "https://ebzzry.io"]
---
ANSI Common Lisp is a general purpose, multi-paradigm programming
language suited for a wide variety of industry applications. It is
frequently referred to as a programmable programming language.
Common Lisp is a general-purpose, multi-paradigm programming language suited for a wide variety of
industry applications. It is frequently referred to as a programmable programming language.
The classic starting point is [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/)
Another popular and recent book is
[Land of Lisp](http://landoflisp.com/).
The classic starting point is [Practical Common Lisp](http://www.gigamonkeys.com/book/). Another
popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book about best practices,
[Common Lisp Recipes](http://weitz.de/cl-recipes/), was recently published.
```common_lisp
```lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;-----------------------------------------------------------------------------
;;; 0. Syntax
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;-----------------------------------------------------------------------------
;;; General form.
;;; General form
;; Lisp has two fundamental pieces of syntax: the ATOM and the
;; S-expression. Typically, grouped S-expressions are called `forms`.
;;; CL has two fundamental pieces of syntax: ATOM and S-EXPRESSION.
;;; Typically, grouped S-expressions are called `forms`.
10 ; an atom; it evaluates to itself
:THING ;Another atom; evaluating to the symbol :thing.
t ; another atom, denoting true.
(+ 1 2 3 4) ; an s-expression
'(4 :foo t) ;another one
10 ; an atom; it evaluates to itself
:thing ; another atom; evaluating to the symbol :thing
t ; another atom, denoting true
(+ 1 2 3 4) ; an s-expression
'(4 :foo t) ; another s-expression
;;; Comments
;; Single line comments start with a semicolon; use two for normal
;; comments, three for section comments, and four for file-level
;; comments.
;;; Single-line comments start with a semicolon; use four for file-level
;;; comments, three for section descriptions, two inside definitions, and one
;;; for single lines. For example,
#| Block comments
can span multiple lines and...
;;;; life.lisp
;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph.
;;; Needed by the function LINULUKO.
(defun meaning (life)
"Return the computed meaning of LIFE"
(let ((meh "abc"))
;; Invoke krakaboom
(loop :for x :across meh
:collect x))) ; store values into x, then return it
;;; Block comments, on the other hand, allow for free-form comments. They are
;;; delimited with #| and |#
#| This is a block comment which
can span multiple lines and
#|
they can be nested!
|#
|#
;;; Environment.
;; A variety of implementations exist; most are
;; standard-conformant. CLISP is a good starting one.
;;; Environment
;; Libraries are managed through Quicklisp.org's Quicklisp system.
;;; A variety of implementations exist; most are standards-conformant. SBCL
;;; is a good starting point. Third party libraries can be easily installed with
;;; Quicklisp
;; Common Lisp is usually developed with a text editor and a REPL
;; (Read Evaluate Print Loop) running at the same time. The REPL
;; allows for interactive exploration of the program as it is "live"
;; in the system.
;;; CL is usually developed with a text editor and a Real Eval Print
;;; Loop (REPL) running at the same time. The REPL allows for interactive
;;; exploration of the program while it is running "live".
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 1. Primitive Datatypes and Operators
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;-----------------------------------------------------------------------------
;;; 1. Primitive datatypes and operators
;;;-----------------------------------------------------------------------------
;;; Symbols
'foo ; => FOO Notice that the symbol is upper-cased automatically.
;; Intern manually creates a symbol from a string.
;;; INTERN manually creates a symbol from a string.
(intern "AAAA") ; => AAAA
(intern "aaa") ; => |aaa|
(intern "AAAA") ; => AAAA
(intern "aaa") ; => |aaa|
;;; Numbers
9999999999999999999999 ; integers
#b111 ; binary => 7
#o111 ; octal => 73
@ -89,313 +98,363 @@ t ; another atom, denoting true.
1/2 ; ratios
#C(1 2) ; complex numbers
;;; Function application are written as (f x y z ...) where f is a function and
;;; x, y, z, ... are the arguments.
;; Function application is written (f x y z ...)
;; where f is a function and x, y, z, ... are operands
;; If you want to create a literal list of data, use ' to stop it from
;; being evaluated - literally, "quote" the data.
'(+ 1 2) ; => (+ 1 2)
;; You can also call a function manually:
(funcall #'+ 1 2 3) ; => 6
;; Some arithmetic operations
(+ 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)
(+ 1 2) ; => 3
;;; Booleans
t ; for true (any not-nil value is true)
nil ; for false - and the empty list
(not nil) ; => t
(and 0 t) ; => t
(or 0 nil) ; => 0
;;; If you want to create literal data, use QUOTE to prevent it from being
;;; evaluated
;;; Characters
#\A ; => #\A
#\λ ; => #\GREEK_SMALL_LETTER_LAMDA
#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA
(quote (+ 1 2)) ; => (+ 1 2)
(quote a) ; => A
;;; The shorthand for QUOTE is '
'(+ 1 2) ; => (+ 1 2)
'a ; => A
;;; Basic arithmetic operations
(+ 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)
;;; Booleans
t ; true; any non-NIL value is true
nil ; false; also, the empty list: ()
(not nil) ; => T
(and 0 t) ; => T
(or 0 nil) ; => 0
;;; Characters
#\A ; => #\A
#\λ ; => #\GREEK_SMALL_LETTER_LAMDA
#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA
;;; Strings are fixed-length arrays of characters
;;; Strings are fixed-length arrays of characters.
"Hello, world!"
"Benjamin \"Bugsy\" Siegel" ; backslash is an escaping character
;; Strings can be concatenated too!
(concatenate 'string "Hello " "world!") ; => "Hello world!"
;;; Strings can be concatenated
(concatenate 'string "Hello, " "world!") ; => "Hello, world!"
;;; A string can be treated like a sequence of characters
;; A string can be treated like a sequence of characters
(elt "Apple" 0) ; => #\A
;; format can be used to format strings:
(format nil "~a can be ~a" "strings" "formatted")
;;; FORMAT is used to create formatted output, which ranges from simple string
;;; interpolation to loops and conditionals. The first argument to FORMAT
;;; determines where will the formatted string go. If it is NIL, FORMAT
;;; simply returns the formatted string as a value; if it is T, FORMAT outputs
;;; to the standard output, usually the screen, then it returns NIL.
;; Printing is pretty easy; ~% is the format specifier for newline.
(format t "Common Lisp is groovy. Dude.~%")
(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!"
(format t "~A, ~A!" "Hello" "world") ; => NIL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2. Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; You can create a global (dynamically scoped) using defparameter
;; a variable name can use any character except: ()",'`;#|\
;;;-----------------------------------------------------------------------------
;;; 2. Variables
;;;-----------------------------------------------------------------------------
;; Dynamically scoped variables should have earmuffs in their name!
;;; You can create a global (dynamically scoped) variable using DEFVAR and
;;; DEFPARAMETER. The variable name can use any character except: ()",'`;#|\
;;; The difference between DEFVAR and DEFPARAMETER is that re-evaluating a
;;; DEFVAR expression doesn't change the value of the variable. DEFPARAMETER,
;;; on the other hand, does.
;;; By convention, dynamically scoped variables have earmuffs in their name.
(defparameter *some-var* 5)
*some-var* ; => 5
;; You can also use unicode characters.
;;; You can also use unicode characters.
(defparameter *AΛB* nil)
;;; Accessing a previously unbound variable results in an UNBOUND-VARIABLE
;;; error, however it is defined behavior. Don't do it.
;; Accessing a previously unbound variable is an
;; undefined behavior (but possible). 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
;;; the value of the last `form` in the LET form.
(let ((me "dance with you")) me) ; => "dance with you"
;; Local binding: `me` is bound to "dance with you" only within the
;; (let ...). Let always returns the value of the last `form` in the
;; let form.
;;;-----------------------------------------------------------------------------;
;;; 3. Structs and collections
;;;-----------------------------------------------------------------------------;
(let ((me "dance with you"))
me)
;; => "dance with you"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 3. Structs and Collections
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Structs
;; Structs
(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*) ; => true #| -p signifies "predicate". It's used to
check if *rover* is an instance of dog. |#
*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
(dog-p *rover*) ; => T
(dog-name *rover*) ; => "rover"
;; Dog-p, make-dog, and dog-name are all created by defstruct!
;;; DOG-P, MAKE-DOG, and DOG-NAME are all automatically created by DEFSTRUCT
;;; Pairs
;; `cons' constructs pairs, `car' and `cdr' extract the first
;; and second elements
(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB)
(car (cons 'SUBJECT 'VERB)) ; => SUBJECT
(cdr (cons 'SUBJECT 'VERB)) ; => VERB
;;; CONS constructs pairs. CAR and CDR return the head and tail of a CONS-pair.
(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB)
(car (cons 'SUBJECT 'VERB)) ; => SUBJECT
(cdr (cons 'SUBJECT 'VERB)) ; => VERB
;;; Lists
;; Lists are linked-list data structures, made of `cons' pairs and end
;; with a `nil' (or '()) to mark the end of the list
(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3)
;; `list' is a convenience variadic constructor for lists
(list 1 2 3) ; => '(1 2 3)
;; and a quote can also be used for a literal list value
'(1 2 3) ; => '(1 2 3)
;;; Lists are linked-list data structures, made of CONS pairs and end with a
;;; NIL (or '()) to mark the end of the list
;; Can still use `cons' to add an item to the beginning of a list
(cons 4 '(1 2 3)) ; => '(4 1 2 3)
(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3)
;; Use `append' to - surprisingly - append lists together
(append '(1 2) '(3 4)) ; => '(1 2 3 4)
;;; LIST is a convenience variadic constructor for lists
;; Or use concatenate -
(list 1 2 3) ; => '(1 2 3)
(concatenate 'list '(1 2) '(3 4))
;;; When the first argument to CONS is an atom and the second argument is a
;;; list, CONS returns a new CONS-pair with the first argument as the first
;;; item and the second argument as the rest of the CONS-pair
(cons 4 '(1 2 3)) ; => '(4 1 2 3)
;;; Use APPEND to join lists
(append '(1 2) '(3 4)) ; => '(1 2 3 4)
;;; Or CONCATENATE
(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4)
;;; Lists are a very central type, so there is a wide variety of functionality for
;;; them, a few examples:
;; Lists are a very central type, so there is a wide variety of functionality for
;; them, a few examples:
(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
(every #'evenp '(1 2 3 4)) ; => NIL
(some #'oddp '(1 2 3 4)) ; => T
(butlast '(subject verb object)) ; => (SUBJECT VERB)
;;; Vectors
;; Vector's literals are fixed-length arrays
;;; Vector's literals are fixed-length arrays
#(1 2 3) ; => #(1 2 3)
;; Use concatenate to add vectors together
;;; Use CONCATENATE to add vectors together
(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6)
;;; Arrays
;; Both vectors and strings are special-cases of arrays.
;;; Both vectors and strings are special-cases of arrays.
;; 2D arrays
;;; 2D arrays
(make-array (list 2 2))
(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 2)) works as well.
;;; Caution: the default initial values of MAKE-ARRAY are implementation-defined.
;;; To explicitly specify them:
; => #2A((0 0) (0 0))
(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET)
(make-array (list 2 2 2))
;;; To access the element at 1, 1, 1:
; => #3A(((0 0) (0 0)) ((0 0) (0 0)))
;; Caution- the default initial values are
;; implementation-defined. Here's how to define them:
(make-array '(2) :initial-element 'unset)
; => #(UNSET UNSET)
;; And, to access the element at 1,1,1 -
(aref (make-array (list 2 2 2)) 1 1 1)
; => 0
(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
;; Adjustable vectors have the same printed representation
;; as fixed-length vector's literals.
;;; Adjustable vectors have the same printed representation as
;;; fixed-length vector's literals.
(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
:adjustable t :fill-pointer t))
:adjustable t :fill-pointer t))
*adjvec* ; => #(1 2 3)
;; Adding new element:
(vector-push-extend 4 *adjvec*) ; => 3
;;; Adding new elements
*adjvec* ; => #(1 2 3 4)
(vector-push-extend 4 *adjvec*) ; => 3
*adjvec* ; => #(1 2 3 4)
;;; Sets, naively, are just lists:
;;; Naively, sets are just lists:
(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)
(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)
;; But you'll want to use a better data structure than a linked list
;; for performant work!
;;; However, you'll need a better data structure than linked lists when working
;;; with larger data sets
;;; Dictionaries are implemented as hash tables.
;; Create a hash table
;;; Create a hash table
(defparameter *m* (make-hash-table))
;; set a value
;;; Set value
(setf (gethash 'a *m*) 1)
;; Retrieve a value
(gethash 'a *m*) ; => 1, t
;;; Retrieve value
;; Detail - Common Lisp has multiple return values possible. gethash
;; returns t in the second value if anything was found, and nil if
;; not.
(gethash 'a *m*) ; => 1, T
;; Retrieving a non-present value returns nil
(gethash 'd *m*) ;=> nil, nil
;;; CL expressions have the ability to return multiple values.
(values 1 2) ; => 1, 2
;;; which can be bound with MULTIPLE-VALUE-BIND
(multiple-value-bind (x y)
(values 1 2)
(list y x))
; => '(2 1)
;;; GETHASH is an example of a function that returns multiple values. The first
;;; value it return is the value of the key in the hash table; if the key is
;;; not found it returns NIL.
;;; The second value determines if that key is indeed present in the hash
;;; table. If a key is not found in the table it returns NIL. This behavior
;;; allows us to check if the value of a key is actually NIL.
;;; Retrieving a non-present value returns nil
(gethash 'd *m*) ;=> NIL, NIL
;;; You can provide a default value for missing keys
;; You can provide a default value for missing keys
(gethash 'd *m* :not-found) ; => :NOT-FOUND
;; Let's handle the multiple return values here in code.
;;; Let's handle the multiple return values here in code.
(multiple-value-bind
(a b)
(multiple-value-bind (a b)
(gethash 'd *m*)
(list a b))
; => (NIL NIL)
(multiple-value-bind
(a b)
(multiple-value-bind (a b)
(gethash 'a *m*)
(list a b))
; => (1 T)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 3. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Use `lambda' to create anonymous functions.
;; A function always returns the value of its last expression.
;; The exact printable representation of a function will vary...
;;;-----------------------------------------------------------------------------
;;; 3. Functions
;;;-----------------------------------------------------------------------------
;;; Use LAMBDA to create anonymous functions. Functions always returns the
;;; value of the last expression. The exact printable representation of a
;;; function varies between implementations.
(lambda () "Hello World") ; => #<FUNCTION (LAMBDA ()) {1004E7818B}>
;; Use funcall to call lambda functions
(funcall (lambda () "Hello World")) ; => "Hello World"
;;; Use FUNCALL to call anonymous functions
;; Or Apply
(funcall (lambda () "Hello World")) ; => "Hello World"
(funcall #'+ 1 2 3) ; => 6
;;; A call to FUNCALL is also implied when the lambda expression is the CAR of
;;; an unquoted list
((lambda () "Hello World")) ; => "Hello World"
((lambda (val) val) "Hello World") ; => "Hello World"
;;; FUNCALL is used when the arguments are known beforehand. Otherwise, use APPLY
(apply #'+ '(1 2 3)) ; => 6
(apply (lambda () "Hello World") nil) ; => "Hello World"
;; De-anonymize the function
(defun hello-world ()
"Hello World")
;;; To name a function, use DEFUN
(defun hello-world () "Hello World")
(hello-world) ; => "Hello World"
;; The () in the above is the list of arguments for the function
(defun hello (name)
(format nil "Hello, ~a" name))
;;; The () in the definition above is the list of arguments
(defun hello (name) (format nil "Hello, ~A" name))
(hello "Steve") ; => "Hello, Steve"
;; Functions can have optional arguments; they default to nil
;;; Functions can have optional arguments; they default to NIL
(defun hello (name &optional from)
(if from
(format t "Hello, ~a, from ~a" name from)
(format t "Hello, ~a" name)))
(if from
(format t "Hello, ~A, from ~A" name from)
(format t "Hello, ~A" name)))
(hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas
(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas
;;; The default values can also be specified
;; And the defaults can be set...
(defun hello (name &optional (from "The world"))
(format t "Hello, ~a, from ~a" name from))
(format nil "Hello, ~A, from ~A" name from))
(hello "Steve")
; => Hello, Steve, from The world
(hello "Steve") ; => Hello, Steve, from The world
(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas
(hello "Steve" "the alpacas")
; => Hello, Steve, from the alpacas
;; And of course, keywords are allowed as well... usually more
;; flexible than &optional.
;;; Functions also have keyword arguments to allow non-positional arguments
(defun generalized-greeter (name &key (from "the world") (honorific "Mx"))
(format t "Hello, ~a ~a, from ~a" honorific name from))
(format t "Hello, ~A ~A, from ~A" honorific name from))
(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world
(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. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Common Lisp has a sophisticated equality system. A couple are covered here.
;;;-----------------------------------------------------------------------------
;;; 4. Equality
;;;-----------------------------------------------------------------------------
;; for numbers use `='
(= 3 3.0) ; => t
(= 2 1) ; => nil
;;; CL has a sophisticated equality system. Some are covered here.
;; for object identity (approximately) use `eql`
(eql 3 3) ; => t
(eql 3 3.0) ; => nil
(eql (list 3) (list 3)) ; => nil
;;; For numbers, use `='
(= 3 3.0) ; => T
(= 2 1) ; => NIL
;; for lists, strings, and bit-vectors use `equal'
(equal (list 'a 'b) (list 'a 'b)) ; => t
(equal (list 'a 'b) (list 'b 'a)) ; => nil
;;; For object identity (approximately) use EQL
(eql 3 3) ; => T
(eql 3 3.0) ; => NIL
(eql (list 3) (list 3)) ; => NIL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 5. Control Flow
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; for lists, strings, and bit-vectors use EQUAL
(equal (list 'a 'b) (list 'a 'b)) ; => T
(equal (list 'a 'b) (list 'b 'a)) ; => NIL
;;;-----------------------------------------------------------------------------
;;; 5. Control Flow
;;;-----------------------------------------------------------------------------
;;; Conditionals
@ -404,71 +463,75 @@ nil ; for false - and the empty list
"this is false") ; else expression
; => "this is true"
;; In conditionals, all non-nil values are treated as true
;;; In conditionals, all non-NIL values are treated as true
(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO)
(if (member 'Groucho '(Harpo Groucho Zeppo))
'yep
'nope)
; => 'YEP
;; `cond' chains a series of tests to select a result
;;; COND chains a series of tests to select a result
(cond ((> 2 2) (error "wrong!"))
((< 2 2) (error "wrong again!"))
(t 'ok)) ; => 'OK
;; Typecase switches on the type of the value
;;; TYPECASE switches on the type of the value
(typecase 1
(string :string)
(integer :int))
; => :int
;;; Looping
;;; Recursion
(defun fact (n)
(if (< n 2)
1
(* n (fact(- n 1)))))
(fact 5) ; => 120
;;; Iteration
;; Of course recursion is supported:
(defun fact (n)
(loop :for result = 1 :then (* result i)
:for i :from 2 :to n
:finally (return result)))
(defun walker (n)
(if (zerop n)
:walked
(walker (- n 1))))
(walker 5) ; => :walked
;; Most of the time, we use DOLIST or LOOP
(fact 5) ; => 120
(loop :for x :across "abcd" :collect x)
; => (#\a #\b #\c #\d)
(dolist (i '(1 2 3 4))
(format t "~a" i))
(format t "~A" i))
; => 1234
(loop for i from 0 below 10
collect i)
; => (0 1 2 3 4 5 6 7 8 9)
;;;-----------------------------------------------------------------------------
;;; 6. Mutation
;;;-----------------------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 6. Mutation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Use `setf' to assign a new value to an existing variable. This was
;; demonstrated earlier in the hash table example.
;;; Use SETF to assign a new value to an existing variable. This was
;;; demonstrated earlier in the hash table example.
(let ((variable 10))
(setf variable 2))
; => 2
; => 2
;;; Good Lisp style is to minimize the use of destructive functions and to avoid
;;; mutation when reasonable.
;; Good Lisp style is to minimize destructive functions and to avoid
;; mutation when reasonable.
;;;-----------------------------------------------------------------------------
;;; 7. Classes and objects
;;;-----------------------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 7. Classes and Objects
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; No more Animal classes, let's have Human-Powered Mechanical
;; Conveyances.
;;; No more animal classes. Let's have Human-Powered Mechanical
;;; Conveyances.
(defclass human-powered-conveyance ()
((velocity
@ -479,14 +542,16 @@ nil ; for false - and the empty list
:initarg :average-efficiency))
(:documentation "A human powered conveyance"))
;; defclass, followed by name, followed by the superclass list,
;; followed by slot list, followed by optional qualities such as
;; :documentation.
;;; The arguments to DEFCLASS, in order are:
;;; 1. class name
;;; 2. superclass list
;;; 3. slot list
;;; 4. optional specifiers
;; When no superclass list is set, the empty list defaults to the
;; standard-object class. This *can* be changed, but not until you
;; know what you're doing. Look up the Art of the Metaobject Protocol
;; for more information.
;;; When no superclass list is set, the empty list defaults to the
;;; standard-object class. This *can* be changed, but not until you
;;; know what you're doing. Look up the Art of the Metaobject Protocol
;;; for more information.
(defclass bicycle (human-powered-conveyance)
((wheel-size
@ -500,7 +565,7 @@ nil ; for false - and the empty list
(defclass recumbent (bicycle)
((chain-type
:accessor chain-type
:initarg :chain-type)))
:initarg :chain-type)))
(defclass unicycle (human-powered-conveyance) nil)
@ -509,8 +574,7 @@ nil ; for false - and the empty list
:accessor number-of-rowers
:initarg :number-of-rowers)))
;; Calling DESCRIBE on the human-powered-conveyance class in the REPL gives:
;;; Calling DESCRIBE on the HUMAN-POWERED-CONVEYANCE class in the REPL gives:
(describe 'human-powered-conveyance)
@ -532,47 +596,42 @@ nil ; for false - and the empty list
; Readers: AVERAGE-EFFICIENCY
; Writers: (SETF AVERAGE-EFFICIENCY)
;; Note the reflective behavior available to you! Common Lisp is
;; designed to be an interactive system
;;; Note the reflective behavior available. CL was designed to be an
;;; interactive system
;; To define a method, let's find out what our circumference of the
;; bike wheel turns out to be using the equation: C = d * pi
;;; To define a method, let's find out what our circumference of the
;;; bike wheel turns out to be using the equation: C = d * pi
(defmethod circumference ((object bicycle))
(* pi (wheel-size object)))
;; pi is defined in Lisp already for us!
;;; PI is defined as a built-in in CL
;; Let's suppose we find out that the efficiency value of the number
;; of rowers in a canoe is roughly logarithmic. This should probably be set
;; in the constructor/initializer.
;;; Let's suppose we find out that the efficiency value of the number
;;; of rowers in a canoe is roughly logarithmic. This should probably be set
;;; in the constructor/initializer.
;; Here's how to initialize your instance after Common Lisp gets done
;; constructing it:
;;; To initialize your instance after CL gets done constructing it:
(defmethod initialize-instance :after ((object canoe) &rest args)
(setf (average-efficiency object) (log (1+ (number-of-rowers object)))))
;; Then to construct an instance and check the average efficiency...
;;; Then to construct an instance and check the average efficiency...
(average-efficiency (make-instance 'canoe :number-of-rowers 15))
; => 2.7725887
;;;-----------------------------------------------------------------------------
;;; 8. Macros
;;;-----------------------------------------------------------------------------
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8. Macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Macros let you extend the syntax of the language
;; Common Lisp doesn't come with a WHILE loop- let's add one.
;; If we obey our assembler instincts, we wind up with:
;;; Macros let you extend the syntax of the language. CL doesn't come
;;; with a WHILE loop, however, it's trivial to write one. If we obey our
;;; assembler instincts, we wind up with:
(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
@ -584,47 +643,47 @@ nil ; for false - and the empty list
(go ,block-name)
,done)))
;; Let's look at the high-level version of this:
;;; Let's look at the high-level version of this:
(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)))
;; However, with a modern compiler, this is not required; the LOOP
;; form compiles equally well and is easier to read.
;;; However, with a modern compiler, this is not required; the LOOP form
;;; compiles equally well and is easier to read.
;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator
;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting"
;; variables. @ interpolates lists.
;;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator
;;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting"
;;; variables. @ interpolates lists.
;; Gensym creates a unique symbol guaranteed to not exist elsewhere in
;; the system. This is because macros are expanded at compile time and
;; variables declared in the macro can collide with variables used in
;; regular code.
;;; GENSYM creates a unique symbol guaranteed to not exist elsewhere in
;;; the system. This is because macros are expanded at compile time and
;;; variables declared in the macro can collide with variables used in
;;; regular code.
;; See Practical Common Lisp for more information on macros.
;;; See Practical Common Lisp and On Lisp for more information on macros.
```
## Further Reading
## Further reading
* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/)
* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf)
- [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)
## Extra Info
## Extra information
* [CLiki](http://www.cliki.net/)
* [common-lisp.net](https://common-lisp.net/)
* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl)
- [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/)
## Credits.
## Credits
Lots of thanks to the Scheme people for rolling up a great starting
point which could be easily moved to Common Lisp.

View File

@ -301,7 +301,6 @@ end
(1..3).each do |index|
puts "Index: #{index}"
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3
@ -422,7 +421,7 @@ class Human
@name
end
# The above functionality can be encapsulated using the attr_accessor method as follows
# The above functionality can be encapsulated using the propery method as follows
property :name
# Getter/setter methods can also be created individually like this

View File

@ -75,8 +75,8 @@ List.head [] -- Nothing
-- K získání hodnot z dvojice použijte funkce first a second.
-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
fst ("elm", 42) -- "elm"
snd ("elm", 42) -- 42
Tuple.first ("elm", 42) -- "elm"
Tuple.second ("elm", 42) -- 42
-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
-- Je to jediná hodnota svého typu, který se také nazývá "Unit".

View File

@ -9,33 +9,28 @@ 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,
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 , jakožto překladatele,
na [martinek@ludis.me](mailto:martinek@ludis.me).
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 jádra z
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čí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 */
// 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ů
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();
// 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.
@ -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 *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
// 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.
///////////////////////////////////
// 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,114 +158,136 @@ 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
// jazycích: je to neuspořádaná množina páru hodnot - klíč:hodnota.
var mujObjekt = {klic1: "Ahoj", klic2: "světe"};
// 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
// Klíče jsou řetězce, ale nejsou povinné uvozovky, pokud jsou validní
// JavaScriptové identifikátory. Hodnoty můžou být jakéhokoliv typu-
// 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: "Hello", klic2: "World"};
// 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
} 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
// 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
// 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
}
}
}
// Cyklus For-in iteruje přes každou vlastnost prototypu
var popis = "";
var osoba = {prijmeni:"Paul", jmeno:"Ken", vek:18};
for (var x in osoba){
popis += osoba[x] + " ";
}
} // popis = 'Paul Ken 18 '
//Když chcete iterovat přes vlastnosti, které jsou přímo na objektu a nejsou
//zděněné z prototypů, kontrolujte vlastnosti přes hasOwnProperty()
var popis = "";
var osoba = {prijmeni:"Jan", jmeno:"Novák", vek:18};
for (var x in osoba){
if (osoba.hasOwnProperty(x)){
popis += osoba[x] + " ";
}
}
// 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á"){
dum.obsahuje = "medvěd";
}
if (barva == "červená" || barva == "modrá"){
// barva je červená nebo modt
// barva je červená nebo mod
}
// && 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í 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 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,33 +377,33 @@ 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
///////////////////////////////////////////////////
// 5. Více o objektech, konstuktorech a prototypech
// 5. Více o objektech, konstruktorech 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 prování funkcí
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.
// 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ý 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
// 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!"
mujText: "Hello world!"
};
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 objektu 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í konstruktoru. 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);
@ -521,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);
@ -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](http://www.learneroo.com/modules/64/nodes/350) je varianta tohoto
návodu i s úkoly-
[Learn Javascript by Example and with Challenges][4]
je varianta tohoto návodu i s úkoly.
[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 Garden][5] je sbírka příkladů těch nejnepředvídatelnějších částí
tohoto jazyka.
[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/)
je klasická výuková kniha.
[JavaScript: The Definitive Guide][6] je klasická výuková kniha.
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.
[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í
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á
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 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
[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/

View File

@ -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
<!-- Markdown je nadstavba nad HTML, takže jakýkoliv kód HTML je validní
Markdown, to znamená, že můžeme používat HTML elementy, třeba jako komentář, a
nebudou ovlivněny parserem Markdownu. Avšak, pokud vytvoříte HTML element v

View File

@ -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]

View File

@ -132,6 +132,12 @@ namespace Learning.CSharp
DateTime fooDate = DateTime.Now;
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
// Verbatim String
// You can use the @ symbol before a string literal to escape all characters in the string
string path = "C:\\Users\\User\\Desktop";
string verbatimPath = @"C:\Users\User\Desktop";
Console.WriteLine(path == verbatimPath); // => true
// You can split a string over two lines with the @ symbol. To escape " use ""
string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";
@ -634,6 +640,54 @@ on a new line! ""Wow!"", the masses cried";
}
}
// DELEGATES AND EVENTS
public class DelegateTest
{
public static int count = 0;
public static int Increment()
{
// increment count then return it
return ++count;
}
// A delegate is a reference to a method
// To reference the Increment method,
// first declare a delegate with the same signature
// ie. takes no arguments and returns an int
public delegate int IncrementDelegate();
// An event can also be used to trigger delegates
// Create an event with the delegate type
public static event IncrementDelegate MyEvent;
static void Main(string[] args)
{
// Refer to the Increment method by instantiating the delegate
// and passing the method itself in as an argument
IncrementDelegate inc = new IncrementDelegate(Increment);
Console.WriteLine(inc()); // => 1
// Delegates can be composed with the + operator
IncrementDelegate composedInc = inc;
composedInc += inc;
composedInc += inc;
// composedInc will run Increment 3 times
Console.WriteLine(composedInc()); // => 4
// Subscribe to the event with the delegate
MyEvent += new IncrementDelegate(Increment);
MyEvent += new IncrementDelegate(Increment);
// Trigger the event
// ie. run all delegates subscribed to this event
Console.WriteLine(MyEvent()); // => 6
}
}
// Class Declaration Syntax:
// <public/private/protected/internal> class <class name>{
// //data fields, constructors, functions all inside.
@ -949,6 +1003,7 @@ on a new line! ""Wow!"", the masses cried";
// String interpolation by prefixing the string with $
// and wrapping the expression you want to interpolate with { braces }
// You can also combine both interpolated and verbatim strings with $@
public class Rectangle
{
public int Length { get; set; }
@ -961,6 +1016,9 @@ on a new line! ""Wow!"", the masses cried";
{
Rectangle rect = new Rectangle { Length = 5, Width = 3 };
Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");
string username = "User";
Console.WriteLine($@"C:\Users\{username}\Desktop");
}
}
@ -1096,25 +1154,144 @@ namespace Learning.More.CSharp
}
}
//New C# 7 Feature
//Install Microsoft.Net.Compilers Latest from Nuget
//Install System.ValueTuple Latest from Nuget
using System;
namespace Csharp7
{
//New C# 7 Feature
//Install Microsoft.Net.Compilers Latest from Nuget
//Install System.ValueTuple Latest from Nuget
class Program
{
static void Main(string[] args)
{
//Type 1 Declaration
(string FirstName, string LastName) names1 = ("Peter", "Parker");
Console.WriteLine(names1.FirstName);
// TUPLES, DECONSTRUCTION AND DISCARDS
class TuplesTest
{
public (string, string) GetName()
{
// Fields in tuples are by default named Item1, Item2...
var names1 = ("Peter", "Parker");
Console.WriteLine(names1.Item2); // => Parker
//Type 2 Declaration
var names2 = (First:"Peter", Last:"Parker");
Console.WriteLine(names2.Last);
}
}
// Fields can instead be explicitly named
// Type 1 Declaration
(string FirstName, string LastName) names2 = ("Peter", "Parker");
// Type 2 Declaration
var names3 = (First:"Peter", Last:"Parker");
Console.WriteLine(names2.FirstName); // => Peter
Console.WriteLine(names3.Last); // => Parker
return names3;
}
public string GetLastName() {
var fullName = GetName();
// Tuples can be deconstructed
(string firstName, string lastName) = fullName;
// Fields in a deconstructed tuple can be discarded by using _
var (_, last) = fullName;
return last;
}
// Any type can be deconstructed in the same way by
// specifying a Deconstruct method
public int randomNumber = 4;
public int anotherRandomNumber = 10;
public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
{
randomNumber = this.randomNumber;
anotherRandomNumber = this.anotherRandomNumber;
}
static void Main(string[] args)
{
var tt = new TuplesTest();
(int num1, int num2) = tt;
Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10
Console.WriteLine(tt.GetLastName());
}
}
// PATTERN MATCHING
class PatternMatchingTest
{
public static (string, int)? CreateLogMessage(object data)
{
switch(data)
{
// Additional filtering using when
case System.Net.Http.HttpRequestException h when h.Message.Contains("404"):
return (h.Message, 404);
case System.Net.Http.HttpRequestException h when h.Message.Contains("400"):
return (h.Message, 400);
case Exception e:
return (e.Message, 500);
case string s:
return (s, s.Contains("Error") ? 500 : 200);
case null:
return null;
default:
return (data.ToString(), 500);
}
}
}
// REFERENCE LOCALS
// Allow you to return a reference to an object instead of just its value
class RefLocalsTest
{
// note ref in return
public static ref string FindItem(string[] arr, string el)
{
for(int i=0; i<arr.Length; i++)
{
if(arr[i] == el) {
// return the reference
return ref arr[i];
}
}
throw new Exception("Item not found");
}
public static void SomeMethod()
{
string[] arr = {"this", "is", "an", "array"};
// note refs everywhere
ref string item = ref FindItem(arr, "array");
item = "apple";
Console.WriteLine(arr[3]); // => apple
}
}
// LOCAL FUNCTIONS
class LocalFunctionTest
{
private static int _id = 0;
public int id;
public LocalFunctionTest()
{
id = generateId();
// This local function can only be accessed in this scope
int generateId()
{
return _id++;
}
}
public static void AnotherMethod()
{
var lf1 = new LocalFunctionTest();
var lf2 = new LocalFunctionTest();
Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1
int id = generateId();
// error CS0103: The name 'generateId' does not exist in the current context
}
}
}
```

View File

@ -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
#################### */

View File

@ -16,19 +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 :
@ -40,7 +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.
@ -49,16 +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.
@ -67,16 +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) :
@ -230,13 +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.

View File

@ -500,8 +500,8 @@ main() {
Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
useful Try Dart online.
http://www.dartlang.org/
http://try.dartlang.org/
[https://www.dartlang.org](https://www.dartlang.org)
[https://try.dartlang.org](https://try.dartlang.org)

View File

@ -0,0 +1,188 @@
---
language: LOLCODE
filename: learnLOLCODE-de.lol
contributors:
- ["abactel", "https://github.com/abactel"]
translators:
- ["Henrik Jürges", "http://github.com/santifa"]
lang: de-de
---
LOLCODE ist eine esoterische Programmiersprache die die Sprache der [lolcats](https://upload.wikimedia.org/wikipedia/commons/a/ab/Lolcat_in_folder.jpg?1493656347257) nachahmt.
```
BTW Das ist ein Kommentar
BTW Das Programm muss mit `HAI <language version>` beginnen und mit `KTHXBYE` enden.
HAI 1.3
CAN HAS STDIO? BTW Standard Header importieren
OBTW
==========================================================================
============================== Grundlegendes =============================
==========================================================================
TLDR
BTW Texte anzeigen:
VISIBLE "HELLO WORLD"
BTW Variablen deklarieren:
I HAS A MESSAGE ITZ "CATZ ARE GOOD"
VISIBLE MESSAGE
OBTW
Variablen sind dynamisch typisiert und der Typ muss nicht explizit
angegeben werden. Die möglichen Typen sind:
TLDR
I HAS A STRING ITZ "DOGZ ARE GOOOD" BTW Typ ist YARN
I HAS A INTEGER ITZ 42 BTW Typ ist NUMBR
I HAS A FLOAT ITZ 3.1415 BTW Typ ist NUMBAR
I HAS A BOOLEAN ITZ WIN BTW Typ ist TROOF
I HAS A UNTYPED BTW Typ ist NOOB
BTW Eingaben von Nutzern:
I HAS A AGE
GIMMEH AGE
BTW Die Variable wird als YARN gespeichert und kann in eine
BTW NUMBR konvertiert werden:
AGE IS NOW A NUMBR
OBTW
==========================================================================
================================== MATHE =================================
==========================================================================
TLDR
BTW LOLCODE benutzt polnische Notation für Mathe.
BTW grundlegende mathematische Notationen:
SUM OF 21 AN 33 BTW 21 + 33
DIFF OF 90 AN 10 BTW 90 - 10
PRODUKT OF 12 AN 13 BTW 12 * 13
QUOSHUNT OF 32 AN 43 BTW 32 / 43
MOD OF 43 AN 64 BTW 43 modulo 64
BIGGR OF 23 AN 53 BTW max(23, 53)
SMALLR OF 53 AN 45 BTW min(53, 45)
BTW binäre Notation:
BOTH OF WIN AN WIN BTW und: WIN if x=WIN, y=WIN
EITHER OF FAIL AN WIN BTW oder: FAIL if x=FAIL, y=FAIL
WON OF WIN AN FAIL BTW exklusives oder: FAIL if x=y
NOT FAIL BTW unäre Negation: WIN if x=FAIL
ALL OF WIN AN WIN MKAY BTW beliebige Stelligkeit bei AND
ANY OF WIN AN FAIL MKAY BTW beliebige Stelligkeit bei OR
BTW Vergleiche:
BOTH SAEM "CAT" AN "DOG" BTW WIN wenn x == y
DIFFRINT 732 AN 184 BTW WIN wenn x != y
BOTH SAEM 12 AN BIGGR OF 12 AN 4 BTW x >= y
BOTH SAEM 43 AN SMALLR OF 43 AN 56 BTW x <= y
DIFFRINT 64 AN SMALLR OF 64 AN 2 BTW x > y
DIFFRINT 75 AN BIGGR OF 75 AN 643 BTW x < y
OBTW
==========================================================================
============================= Flusskontrolle =============================
==========================================================================
TLDR
BTW If/then Statement:
I HAS A ANIMAL
GIMMEH ANIMAL
BOTH SAEM ANIMAL AN "CAT", O RLY?
YA RLY
VISIBLE "YOU HAV A CAT"
MEBBE BOTH SAEM ANIMAL AN "MAUS"
VISIBLE "NOM NOM NOM. I EATED IT."
NO WAI
VISIBLE "AHHH IS A WOOF WOOF"
OIC
BTW Case Statement:
I HAS A COLOR
GIMMEH COLOR
COLOR, WTF?
OMG "R"
VISIBLE "RED FISH"
GTFO
OMG "Y"
VISIBLE "YELLOW FISH"
BTW Weil hier kein `GTFO` ist wird auch das nächste Statement überprüft
OMG "G"
OMG "B"
VISIBLE "FISH HAS A FLAVOR"
GTFO
OMGWTF
VISIBLE "FISH IS TRANSPARENT OHNO WAT"
OIC
BTW For Schleife:
I HAS A TEMPERATURE
GIMMEH TEMPERATURE
TEMPERATURE IS NOW A NUMBR
IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN TEMPERATURE
VISIBLE ITERATOR
IM OUTTA YR LOOP
BTW While Schleife:
IM IN YR LOOP NERFIN YR ITERATOR WILE DIFFRINT ITERATOR AN -10
VISIBLE ITERATOR
IM OUTTA YR LOOP
OBTW
=========================================================================
================================ Strings ================================
=========================================================================
TLDR
BTW Zeilenumbrüche:
VISIBLE "FIRST LINE :) SECOND LINE"
BTW Tabulatoren:
VISIBLE ":>SPACES ARE SUPERIOR"
BTW Bell (macht beep):
VISIBLE "NXT CUSTOMER PLS :o"
BTW Anführungszeichen in Strings:
VISIBLE "HE SAID :"I LIKE CAKE:""
BTW Doppelpunkte in Strings :
VISIBLE "WHERE I LIVE:: CYBERSPACE"
OBTW
=========================================================================
=============================== Funktionen ==============================
=========================================================================
TLDR
BTW Definieren einer neuen Funktion:
HOW IZ I SELECTMOVE YR MOVE BTW `MOVE` ist ein Argument
BOTH SAEM MOVE AN "ROCK", O RLY?
YA RLY
VISIBLE "YOU HAV A ROCK"
NO WAI
VISIBLE "OH NO IS A SNIP-SNIP"
OIC
GTFO BTW Gibt NOOB zurück
IF U SAY SO
BTW Eine Funktion deklarieren und einen Wert zurückgeben:
HOW IZ I IZYELLOW
FOUND YR "YELLOW"
IF U SAY SO
BTW Eine Funktion aufrufen:
I IZ IZYELLOW MKAY
KTHXBYE
```
## Weiterführende Informationen:
- [LCI compiler](https://github.com/justinmeza/lci)
- [Official spec](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md)

View File

@ -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

View File

@ -0,0 +1,77 @@
---
category: Algorithms & Data Structures
name: Dynamic Programming
contributors:
- ["Akashdeep Goel", "http://github.com/akashdeepgoel"]
translators:
- ["Henrik Jürges", "http://github.com/santifa"]
lang: de-de
---
# Dynamische Programmierung
## Einführung
Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung
einer bestimmten Klasse von Problemen verwendet wird.
Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe
gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu
vermeiden, das gleiche Problem noch einmal zu lösen.
Denken Sie immer daran!
"Diejenigen, die sich nicht an die Vergangenheit erinnern können,
sind dazu verdammt, sie zu wiederholen."
## Wege zur Lösung solcher Probleme
1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen.
Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die
gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und
speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr
intuitiv. Er wird als Memoization bezeichnet.
2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher
Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der
Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird
sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden.
Dies wird als Dynamische Programmierung bezeichnet.
## Ein Beispiel für Dynamische Programmierung
Das Problem mit der längsten ansteigenden Subsequenz besteht darin,
die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden.
Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`,
müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j<i`
in der Teilmenge `aj<ai` gilt.
Zuerst müssen wir bei jedem Index i den Wert der längsten Subsequenzen (LSi)
finden, wobei das letzte Element der Sequenz ai ist. Dann wäre die größte LSi
die längste Subsequenz in der gegebenen Sequenz. Am Anfang wird der LSi mit
eins belegt, da ai ein Element der Sequenz (Letztes Element) ist.
Dann ist für alle `j` mit `j<i` und `aj<ai`, so dass wir den größten LSj finden
und zum LSi hinzufügen. Der Algorithmus hat eine Laufzeit von *O(n2)*.
Pseudocode zur Bestimmung der Länge der am längsten ansteigenden Subsequenz:
Die Komplexität des Algorithmus könnte durch eine bessere Datenstruktur anstelle
von Arrays reduziert werden. Das Speichern von Vorgänger-Array's und Variablen
wie `largest_sequences_so_far` und dessen Index würde eine Menge Zeit sparen.
Ein ähnliches Konzept könnte auch bei der Suche nach dem längsten Weg
in gerichteten azyklischen Graphen angewandt werden.
```python
for i=0 to n-1
LS[i]=1
for j=0 to i-1
if (a[i] > a[j] and LS[i]<LS[j])
LS[i] = LS[j]+1
for i=0 to n-1
if (largest < LS[i])
```
### 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]()
## Online Ressourcen
* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)

112
de-de/edn-de.html.markdown Normal file
View File

@ -0,0 +1,112 @@
---
language: edn
filename: learnedn-de.edn
contributors:
- ["Jason Yeo", "https://github.com/jsyeo"]
- ["Jonathan D Johnston", "https://github.com/jdjohnston"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
lang: de-de
---
Extensible Data Notation (EDN) ist ein Format für serialisierte Daten.
EDN ist ein Subset der von Clojure verwendeten Syntax. Das Lesen von Daten, die durch EDN definiert werden, ist
sicherer als das, was durch die vollständige Clojure-Syntax definiert wird, insbesondere von nicht
vertrauenswürdigen Quellen. EDN ist beschränkt auf Daten, kein Code. Es ist ähnlich in seinen Zielen zu JSON.
Obwohl es mehr in Clojure verwendet wird, gibt es verschiedene Implementationen von EDN in vielen
verschiedenen anderen Sprachen.
Der Hauptvorteil von EDN im Gegensatz zu JSON und YAML ist, dass es erweiterbar ist.
Wir werden später sehen wie es erweitert werden kann.
```clojure
; Kommentare starten mit einem Semikolon.
; Alles nach dem Semikolon wird ignoriert.
;;;;;;;;;;;;;;;;;;;
;;; Basistypen ;;;
;;;;;;;;;;;;;;;;;;;
nil ; auch bekannt in anderen Sprachen als null
; Booleans
true
false
; Strings werden in Gänsefüßchen eingeschlossen.
"hungarian breakfast"
"farmer's cheesy omelette"
; Charaktere werden einem Backslash vorangestellt
\g \r \a \c \e
; Schlüsselwörter beginnen mit einem Doppelpunkt. Sie verhalten sich wie Enums.
; Ähnlich, wie Symbole in Ruby.
:eggs
:cheese
:olives
; Symbole werden verwendet um Identifier zu repräsentieren. Sie beginnen mit einem #.
; Du kannst einen Namespace für Symbole nutzen, wenn du / verwendest. Egal was / vorangestellt wird
; ist der Namespace dieses Namens.
#spoon
#kitchen/spoon ; nicht das selbe, wie #spoon
#kitchen/fork
#github/fork ; damit kannst du nicht essen
; Integers und Floats
42
3.14159
; Listen sind Sequenzen von Werten
(:bun :beef-patty 9 "yum!")
; Vektoren erlauben zufälligen Zugriff
[:gelato 1 2 -2]
; Maps sind assoziative Datenstrukturen, die einen Schlüssel mit einem Wert verbinden.
{:eggs 2
:lemon-juice 3.5
:butter 1}
; Du bist nicht beschränkt ausschließlich Schlüsselwörter als Schlüssel zu verwenden.
{[1 2 3 4] "tell the people what she wore",
[5 6 7 8] "the more you see the more you hate"}
; Du kannst Kommas für eine bessere Lesbarkeit verwenden. Sie werden wie Leerraum behandelt.
; Sets sind Sammlungen, die eindeutige Elemente enthalten.
#{:a :b 88 "huat"}
;;;;;;;;;;;;;;;;;;;;;;;;;
;;; markierte Elemente ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;
; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden.
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
; Lass mich das mit einem Clojure Beispiel erklären.
; Angenommen ich möchte dieses Stück EDM in einen MenuItem record umwandeln.
(defrecord MenuItem [name rating])
; Um EDN in clojure Werte umzuwandeln, muss ich den eingebauten EDN Leser
; edn/read-string verwenden
(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
; -> {:eggs 2 :butter 1 :flour 5}
; Definiere die Leserfunktion, um markierte Elemente zu transformieren
; und übergebe eine Map, die Tags den Lesefunktionen als edn / read-string zuweisen
(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
"#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
```
# Referenzen
- [EDN spec](https://github.com/edn-format/edn)
- [Implementationen](https://github.com/edn-format/edn/wiki/Implementations)
- [makierte Elemente](http://www.compoundtheory.com/clojure-edn-walkthrough/)

View File

@ -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

View File

@ -94,7 +94,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
// Arrays haben bei Kompile-Zeit festgelegte Größen
var a4 [4]int // Ein Array mit 4 ints, alle mit Initialwert 0
a3 := [...]int{3, 1, 5} // Ein Array mit 4 ints, Initialwerte wie angezeigt
a3 := [...]int{3, 1, 5} // Ein Array mit 3 ints, Initialwerte wie angezeigt
// "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre
// Vorzüge, aber slices werden viel häufiger verwendet

View File

@ -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)

View File

@ -2,6 +2,7 @@
language: make
contributors:
- ["Robert Steed", "https://github.com/robochat"]
- ["Stephan Fuhrmann", "https://github.com/sfuhrm"]
translators:
- ["Martin Schimandl", "https://github.com/Git-Jiro"]
filename: Makefile-de
@ -58,7 +59,7 @@ file2.txt file3.txt: file0.txt file1.txt
touch file3.txt
# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt.
# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
# Leere Rezepte zählen nicht und können dazu verwendet werden weitere
# Voraussetzungen hinzuzufügen.
#-----------------------------------------------------------------------
@ -182,9 +183,9 @@ echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb
# Ein paar Variablen die von Make automatisch definiert werden.
echo_inbuilt:
echo $(CC)
echo ${CXX)}
echo ${CXX}
echo $(FC)
echo ${CFLAGS)}
echo ${CFLAGS}
echo $(CPPFLAGS)
echo ${CXXFLAGS}
echo $(LDFLAGS)

View File

@ -14,7 +14,7 @@ Syntax, in der sich Dokumente leicht schreiben *und* lesen lassen. Außerdem
sollte Markdown sich leicht nach HTML (und in andere Formate) konvertieren
lassen.
```markdown
```md
<!-- Markdown ist eine Obermenge von HTML - jede valide HTML-Datei ist also
automatisch valides Markdown - was heisst dass wir jedes HTML-Element (also auch
Kommentare) in Markdown benutzen können, ohne dass der Parser sie verändert.
@ -253,4 +253,4 @@ Ganz schön hässlich | vielleicht doch lieber | wieder aufhören
Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax)
und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).
Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown).

358
de-de/nix-de.html.markdown Normal file
View File

@ -0,0 +1,358 @@
---
language: nix
filename: learnnix-de.nix
contributors:
- ["Chris Martin", "http://chris-martin.org/"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
lang: de-de
---
Nix ist eine simple funktionale Programmiersprache, die für den
[Nix package manager](https://nixos.org/nix/) und
[NixOS](https://nixos.org/) entwickelt wurde.
Du kannst Nix Ausdrücke evaluieren mithilfe von
[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate)
oder [`nix-repl`](https://github.com/edolstra/nix-repl).
```
with builtins; [
# Kommentare
#=========================================
# Inline Kommentare sehen so aus.
/* Multizeilen Kommentare
sehen so aus. */
# Booleans
#=========================================
(true && false) # Und
#=> false
(true || false) # Oder
#=> true
(if 3 < 4 then "a" else "b") # Bedingungen
#=> "a"
# Integers
#=========================================
# Integers sind die einzigen numerischen Typen.
1 0 42 (-3) # Einige integers
(4 + 6 + 12 - 2) # Addition
#=> 20
(7 / 2) # Division
#=> 3
# Strings
#=========================================
"String Literale sind in Anführungszeichen."
"
String Literale können mehrere
Zeilen umspannen.
"
''
Dies wird als Literal mit eingerückten String bezeichnet.
Es entfernt intelligent führende Leerzeichen.
''
''
a
b
''
#=> "a\n b"
("ab" + "cd") # String Konkatenation
#=> "abcd"
# Mit Antiquotation kannst du Werte in Strings einbetten.
("Dein Homeverzeichnis ist ${getEnv "HOME"}")
#=> "Dein Homeverzeichnis ist /home/alice"
# Paths
#=========================================
# Nix besitzt einen primitiven Datentyp für Pfade
/tmp/tutorials/learn.nix
# Ein relativer Pfad wird beim Parsing zu einem absoluten Pfad aufgelöst,
# relativ zu der Datei in der es auftritt.
tutorials/learn.nix
#=> /the-base-path/tutorials/learn.nix
# Ein Pfad muss mindestens einen Schrägstrich enthalten. Ein Pfad für eine
# Datei im selben Verzeichnis benötigt ein ./ Präfix.
./learn.nix
#=> /the-base-path/learn.nix
# Der / Operator muss von Leerraum umgeben sein wenn du dividieren möchtest.
7/2 # Das ist ein Pfadliteral
(7 / 2) # Das ist ein Integerliteral
# Importe
#=========================================
# Eine nix Datei besitzt einen einzelnen top-level Ausdruck mit keinen freien Variablen.
# Ein Import-Ausdruck wird zum Wert der Datei, die importiert wird, ausgewertet.
(import /tmp/foo.nix)
# Importe können ebenso mit Strings spezifiziert werden.
(import "/tmp/foo.nix")
# Import Pfade müssen absolut sein. Pfadliterale
# sind automatisch aufgelöst, das ist ein Ordnung.
(import ./foo.nix)
# Jedoch passiert dies nicht mit Strings.
(import "./foo.nix")
#=> error: string foo.nix doesn't represent an absolute path
# Let
#=========================================
# `let` Blöcke erlauben es uns Werte zu Variablen zu binden.
(let x = "a"; in
x + x + x)
#=> "aaa"
# Bindungen können auf sich gegenseitig verweisen. Die Reihenfolge spielt
# keine Rolle.
(let y = x + "b";
x = "a"; in
y + "c")
#=> "abc"
# Innere Bindungen überschatten Äußere.
(let a = 1; in
let a = 2; in
a)
#=> 2
# Funktionen
#=========================================
(n: n + 1) # Funktion, die 1 addiert
((n: n + 1) 5) # Dieselbe Funktion angewendet auf 5.
#=> 6
# Es gibt keine spezielle Syntax für benannte Funktionen, aber sie
# können mit `let` Blöcken, wie jeder andere Wert auch, gebunden werden.
(let succ = (n: n + 1); in succ 5)
#=> 6
# Eine Funktion hat genau ein Argument.
# Mehrere Argumente können erreicht werden mithilfe von Currying.
((x: y: x + "-" + y) "a" "b")
#=> "a-b"
# Benannte Funktionsargumente gibt es auch. Diese werden wir einführen, nachdem wir uns Sets
# angeschaut haben.
# Listen
#=========================================
# Listen werden durch eckige Klammern gekennzeichnet.
(length [1 2 3 "x"])
#=> 4
([1 2 3] ++ [4 5])
#=> [1 2 3 4 5]
(concatLists [[1 2] [3 4] [5]])
#=> [1 2 3 4 5]
(head [1 2 3])
#=> 1
(tail [1 2 3])
#=> [2 3]
(elemAt ["a" "b" "c" "d"] 2)
#=> "c"
(elem 2 [1 2 3])
#=> true
(elem 5 [1 2 3])
#=> false
(filter (n: n < 3) [1 2 3 4])
#=> [ 1 2 ]
# Sets
#=========================================
# Ein "Set" ist eine ungeordnete Zuordnung mit Stringschlüsseln.
{ foo = [1 2]; bar = "x"; }
# Der . Operator nimmt einen Wert aus dem Set.
{ a = 1; b = 2; }.a
#=> 1
# Der ? Operator testet, ob der Schlüssel in dem Set vorhanden ist.
({ a = 1; b = 2; } ? a)
#=> true
({ a = 1; b = 2; } ? c)
#=> false
# Der // Operator mergt zwei Sets.
({ a = 1; } // { b = 2; })
#=> { a = 1; b = 2; }
# Werte auf der rechten Seite überschreiben die Werte auf der linken Seite.
({ a = 1; b = 2; } // { a = 3; c = 4; })
#=> { a = 3; b = 2; c = 4; }
# Das Schlüsselwort rec bezeichenet ein "rekursives Set", in dem sich Attribute
# aufeinander beziehen können.
(let a = 1; in { a = 2; b = a; }.b)
#=> 1
(let a = 1; in rec { a = 2; b = a; }.b)
#=> 2
# Verschachtelte Sets können stückweise definiert werden.
{
a.b = 1;
a.c.d = 2;
a.c.e = 3;
}.a.c
#=> { d = 2; e = 3; }
# Die Nachkommen eines Attributs können in diesem Feld nicht zugeordnet werden, wenn
# das Attribut selbst nicht zugewiesen wurde.
{
a = { b = 1; };
a.c = 2;
}
#=> error: attribute a already defined
# With
#=========================================
# Der Körper eines Sets Blocks wird mit der Zuordnung eines Satzes an die Variablen gebunden.
(with { a = 1; b = 2; };
a + b)
# => 3
# Innere Bindungen überschatten äußere Bindungen.
(with { a = 1; b = 2; };
(with { a = 5; };
a + b))
#=> 7
# Die erste Linie diese Tutorials startet mit "with builtins;",
# weil builtins ein Set mit allen eingebauten
# Funktionen (length, head, tail, filter, etc.) umfasst.
# Das erspart uns beispielsweise "builtins.length" zu schreiben,
# anstatt nur "length".
# Set patterns
#=========================================
# Sets sind nützlich, wenn du mehrere Werte einer Funktion
# übergeben musst.
(args: args.x + "-" + args.y) { x = "a"; y = "b"; }
#=> "a-b"
# Dies kann mit Hilfe von Set patterns deutlicher geschrieben werden.
({x, y}: x + "-" + y) { x = "a"; y = "b"; }
#=> "a-b"
# Standardmäßig schlägt das Muster bei Sets mit zusätzlichen Schlüsseln fehl.
({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; }
#=> error: anonymous function called with unexpected argument z
# Durch Hinzufügen von ", ..." können zusätzliche Schlüssel ignoriert werden.
({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; }
#=> "a-b"
# Errors
#=========================================
# `throw` bewirkt, dass die Auswertung mit einer Fehlermeldung abgebrochen wird.
(2 + (throw "foo"))
#=> error: foo
# `tryEval` fängt geworfene Fehler.
(tryEval 42)
#=> { success = true; value = 42; }
(tryEval (2 + (throw "foo")))
#=> { success = false; value = false; }
# `abort` ist ähnlich wie throw, aber es ist fatal. Es kann nicht gefangen werden.
(tryEval (abort "foo"))
#=> error: evaluation aborted with the following error message: foo
# `assert` evaluiert zu dem gegebenen Wert, wenn die Bedingung wahr ist, sonst
# löst es eine abfangbare Exception aus.
(assert 1 < 2; 42)
#=> 42
(assert 1 > 2; 42)
#=> error: assertion failed at (string):1:1
(tryEval (assert 1 > 2; 42))
#=> { success = false; value = false; }
# Impurity
#=========================================
# Da die Wiederholbarkeit von Builds für den Nix Packetmanager entscheidend ist,
# werden in der Nix Sprache reine funktionale Elemente betont. Es gibt aber ein paar
# unreine Elemente.
# Du kannst auf Umgebungsvariablen verweisen.
(getEnv "HOME")
#=> "/home/alice"
# Die trace Funktion wird zum Debugging verwendet. Sie gibt das erste Argument zu stderr aus
# und evaluiert das zweite Argument.
(trace 1 2)
#=> trace: 1
#=> 2
# Du kannst Dateien in den Nix Store schreiben. Obwohl unrein, kannst du dir relativ sicher sein,
# dass es sicher ist, da der Dateiname aus dem Hash des Inhalts abgeleitet wird.
# Du kannst Dateien von überall lesen. In diesem Beispiel schreiben wir Dateien in den Store
# und lesen wieder davon.
(let filename = toFile "foo.txt" "hello!"; in
[filename (builtins.readFile filename)])
#=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ]
# Außerdem können wir Dateien in den Nix Store herunterladen.
(fetchurl "https://example.com/package-1.2.3.tgz")
#=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz"
]
```
### Weitere Ressourcen
* [Nix Manual - Nix expression language]
(https://nixos.org/nix/manual/#ch-expression-language)
* [James Fisher - Nix by example - Part 1: The Nix expression language]
(https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55)
* [Susan Potter - Nix Cookbook - Nix By Example]
(http://funops.co/nix-cookbook/nix-by-example/)

View File

@ -0,0 +1,153 @@
---
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]()
* [https://docs.opencv.org/master/]()

View File

@ -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 <http://learnxinyminutes.com/docs/racket/>.
```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.
```

View File

@ -0,0 +1,89 @@
---
category: tool
tool: PyQT
filename: learnpyqt-de.py
contributors:
- ["Nathan Hughes", "https://github.com/sirsharpest"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
lang: de-de
---
**Qt** ist eine weit bekanntes Framework mit den man plattformunabhängige Programme schreiben kann,
die auf verschiedenen Sotfware und Hardware Plattformen laufen mit kleinen oder keinen Änderungen im Code.
Dabei besitzen sie trozdem die Power und Geschwindigkeit von nativen Anwendungen.
**Qt** wurde ursprünglich in *C++** geschrieben.
Das ist eine Adaption von dem C++ Intro für QT von [Aleksey Kholovchuk](https://github.com/vortexxx192),
manche der Codebeispiele sollte in der selben Funktionalität resultieren.
Diese Version wurde in pyqt erstellt.
```python
import sys
from PyQt4 import QtGui
def window():
# Erschafft ein Anwendungsobjekt.
app = QtGui.QApplication(sys.argv)
# Erschafft ein Widget, auf dem unser Label platziert wird.
w = QtGui.QWidget()
# Fügt ein Label zu dem Widget hinzu.
b = QtGui.QLabel(w)
# Setzt einen Text für das Label.
b.setText("Hello World!")
# Setzt die Größe und die Platzierungsinfomationen.
w.setGeometry(100, 100, 200, 50)
b.move(50, 20)
# Setzt unserem Fenster einen schönen Titel.
w.setWindowTitle("PyQt")
# Lässt alles anzeigen.
w.show()
# Führe alles aus, nachdem wir alles aufgebaut haben.
sys.exit(app.exec_())
if __name__ == '__main__':
window()
```
Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können,
müssen wir anfangen zusätzliche Elemente zu bauen.
Hier zeigen wir wie man eine Dialog Popup Box einführt.
Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen.
```Python
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
def window():
app = QApplication(sys.argv)
w = QWidget()
# Erschafft einen Knopf und fügt das Widget w hinzu
b = QPushButton(w)
b.setText("drücke mich")
b.move(50, 50)
# Wenn b gedrückt wird, wird diese Funktion aufgerufen.
# Bemerke das Fehlen von () bei dem Funktionsaufruf.
b.clicked.connect(showdialog)
w.setWindowTitle("PyQt Dialog")
w.show()
sys.exit(app.exec_())
# Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen.
# Der Knopf wartet bis er geklickt wird und beendet das Programm
def showdialog():
d = QDialog()
b1 = QPushButton("ok", d)
b1.move(50, 50)
d.setWindowTitle("Dialog")
# Diese Modalität sagt dem Popup, dass es den Parent blocken soll, solange es aktiv ist.
d.setWindowModality(Qt.ApplicationModal)
# Beim klicken möchte ich, dass der gesamte Prozess beendet wird.
b1.clicked.connect(sys.exit)
d.exec_()
if __name__ == '__main__':
window()
```

View File

@ -152,7 +152,7 @@ print("Ich bin Python. Schön, dich kennenzulernen!")
some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm
some_var #=> 5
# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus.
# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus.
# Unter "Kontrollstruktur" kann noch mehr über
# Ausnahmebehandlung erfahren werden.
some_unknown_var # Löst einen NameError aus
@ -225,7 +225,7 @@ a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3
# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen
d, e, f = 4, 5, 6
# Es ist kinderleicht zwei Werte zu tauschen
e, d = d, e # d is now 5 and e is now 4
e, d = d, e # d ist nun 5 und e ist nun 4
# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare
@ -379,8 +379,8 @@ with open("meineDatei.txt") as f:
print(line)
# Python bietet ein fundamentales Konzept der Iteration.
# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
# Die range Method gibt ein solches Objekt aus.
# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable".
# Die range Methode gibt ein solches Objekt aus.
filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
@ -396,8 +396,8 @@ our_iterable[1] # TypeError
# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft.
our_iterator = iter(our_iterable)
# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen.
# Das jeweeils nächste Objekt bekommen wir mit "next()"
# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen.
# Das jeweils nächste Objekt bekommen wir mit "next()"
next(our_iterator) #=> "one"
# Es hält den vorherigen Status
@ -442,7 +442,7 @@ def keyword_args(**kwargs):
# Rufen wir es mal auf, um zu sehen, was passiert
keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
# Wir können beides gleichzeitig machem, wenn wir wollen
# Wir können beides gleichzeitig machen, wenn wir wollen
def all_the_args(*args, **kwargs):
print(args)
print(kwargs)

175
de-de/qt-de.html.markdown Normal file
View File

@ -0,0 +1,175 @@
---
category: tool
tool: Qt Framework
language: c++
filename: learnqt-de.cpp
contributors:
- ["Aleksey Kholovchuk", "https://github.com/vortexxx192"]
translators:
- ["Dennis Keller", "https://github.com/denniskeller"]
lang: de-de
---
**Qt** ist ein weithin bekanntes Framework zum Entwickeln von cross-platform Software,
die auf verschiedenen Hard- und Softwareplatformen mit wenig oder keinen Veränderungen im Code läuft.
Dabei besitzt man die Power und Geschiwindigkeit von nativen Anwendungen.
Obwohl **Qt** ursprünglich in *C++* geschrieben wurde,
gibt es verschiedene Ports für andere Sprachen: *[PyQt](https://learnxinyminutes.com/docs/pyqt/)*, *QtRuby*, *PHP-Qt*, etc.
**Qt** eignet sich hervorragend zum Erstellen von Anwendungen mit grafischer Benutzeroberfläche (GUI).
Dieses Tutorial zeigt, wie man das in *C++* macht.
```c++
/*
* Lass uns klassisch starten
*/
// Alle Header vom Qt Framework starten mit dem Großbuchstaben 'Q'.
#include <QApplication>
#include <QLineEdit>
int main(int argc, char *argv[]) {
// Erstellt ein Objekt um applikationsweit die Resourcen zu managen.
QApplication app(argc, argv);
// Erstellt ein Line edit Widget und zeigt es auf dem Bildschirm
QLineEdit lineEdit("Hello world!");
lineEdit.show();
// Startet die Event Loop der Anwendung.
return app.exec();
}
```
Die GUI bezogene Teile von **Qt** bestehen aus *Widgets* und den *Verbindungen*
dazwischen.
[Lies mehr über Widgets](http://doc.qt.io/qt-5/qtwidgets-index.html)
```c++
/*
* Lass uns Label und einen Button machen.
* Ein Label soll auftauchen, wenn der Button gedrückt wird.
*
* Der Qt Code spricht für sich selbst.
*/
#include <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDialog dialogWindow;
dialogWindow.show();
// Füge ein vertikales Layout hinzu
QVBoxLayout layout;
dialogWindow.setLayout(&layout);
QLabel textLabel("Danke für das Knopf drücken");
layout.addWidget(&textLabel);
textLabel.hide();
QPushButton button("Drück mich");
layout.addWidget(&button);
// Zeigt verstecktes Label, wenn der Button gedrückt wird.
QObject::connect(&button, &QPushButton::pressed,
&textLabel, &QLabel::show);
return app.exec();
}
```
Beachte den *QObject::connect* Teil. Diese Methode wird verwendet,
um *Signale* eines Objekts mit den *Slots* eines Objektes zu verbinden.
**Signale** werden ausgegeben, wenn bestimmte Dinge mit Objekten passieren.
Beispielsweise wird das *pressed* Signal ausgegeben,
wenn der Benutzer auf das QPushButton Objekt drückt.
**Slots** sind Aktionen, die als Reaktion auf empfangene Signale ausgeführt werden können.
[Lies mehr über Slots und Signale](http://doc.qt.io/qt-5/signalsandslots.html)
Als Nächstes lernen wir, dass wir nicht nur Standard Widgets verwenden können,
sondern auch ihr Verhalten mithilfe von Vererbung verändern können.
Lass uns einen Button erschaffen, der zählt, wie häufig er gedrückt wird.
Dafür definieren wir unsere eigene Klasse *CounterLabel*.
Diese muss wegen der speziellen Qt Architektur in einer seperaten Datei deklariert werden.
```c++
// counterlabel.hpp
#ifndef COUNTERLABEL
#define COUNTERLABEL
#include <QLabel>
class CounterLabel : public QLabel {
Q_OBJECT // Qt definiertes Makro, welches in jedem modifizierten Widget vorhanden sein muss.
public:
CounterLabel() : counter(0) {
setText("Zähler wurde noch nicht erhöht."); // Methode von QLabel
}
public slots:
// Aktion, die ausgeführt wird, wenn der Button gedrückt wird.
void increaseCounter() {
setText(QString("Zähler Wert: %1").arg(QString::number(++counter)));
}
private:
int counter;
};
#endif // Zähllabel
```
```c++
// main.cpp
// Fast das Gleiche, wie das vorherige Beispiel
#include <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QString>
#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("Drück mich nochmal.");
layout.addWidget(&button);
QObject::connect(&button, &QPushButton::pressed,
&counterLabel, &CounterLabel::increaseCounter);
return app.exec();
}
```
Das wars! Natürlich ist das Qt Framework erheblich größer, als der der Teil der in diesem Tutorial behandelt wurde.
Das heißt, es gibt viel zu lesen und zu üben.
## Further reading
- [Qt 4.8 tutorials](http://doc.qt.io/qt-4.8/tutorials.html)
- [Qt 5 tutorials](http://doc.qt.io/qt-5/qtexamplesandtutorials.html)
Viel Erfolg und viel Spaß!

119
de-de/rst-de.html.markdown Normal file
View File

@ -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 <https://github.com/>`_ .
.. _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)

View File

@ -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
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/?gfe_rd=cr&amp;ei=huczWcj3GfTW8gfq0paQDA">
here
</A>.
</BODY></HTML>
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)

View File

@ -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

View File

@ -84,22 +84,26 @@ github/fork ; you can't eat with this
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
; Let me explain this with a clojure example. Suppose I want to transform that
; Let me explain this with a Clojure example. Suppose I want to transform that
; piece of EDN into a MenuItem record.
(defrecord MenuItem [name rating])
; To transform EDN to clojure values, I will need to use the built in EDN
; reader, edn/read-string
; defrecord defined, among other things, map->MenuItem which will take a map
; of field names (as keywords) to values and generate a user.MenuItem record
(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
; To transform EDN to Clojure values, I will need to use the built-in EDN
; reader, clojure.edn/read-string
(clojure.edn/read-string "{:eggs 2 :butter 1 :flour 5}")
; -> {:eggs 2 :butter 1 :flour 5}
; To transform tagged elements, define the reader function and pass a map
; that maps tags to reader functions to edn/read-string like so
; To transform tagged elements, pass to clojure.edn/read-string an option map
; with a :readers map that maps tag symbols to data-reader functions, like so
(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}}
"#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
(clojure.edn/read-string
{:readers {'MyYelpClone/MenuItem map->MenuItem}}
"#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
; -> #user.MenuItem{:name "eggs-benedict", :rating 10}
```

View File

@ -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

View File

@ -72,8 +72,8 @@ List.head [] -- Nothing
-- Access the elements of a pair with the first and second functions.
-- (This is a shortcut; we'll come to the "real way" in a bit.)
fst ("elm", 42) -- "elm"
snd ("elm", 42) -- 42
Tuple.first ("elm", 42) -- "elm"
Tuple.second ("elm", 42) -- 42
-- The empty tuple, or "unit", is sometimes used as a placeholder.
-- It is the only value of its type, also called "Unit".

View File

@ -166,7 +166,7 @@ function arithmetic_functions(a, b, c, localvar) {
# trigonométricas estándar
localvar = sin(a)
localvar = cos(a)
localvar = atan2(a, b) # arcotangente de b / a
localvar = atan2(b, a) # arcotangente de b / a
# Y cosas logarítmicas
localvar = exp(a)

View File

@ -1,6 +1,6 @@
---
language: Brainfuck
filename: brainfuck-es.bf
language: bf
filename: bf-es.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]

View File

@ -823,7 +823,6 @@ v.swap(vector<Foo>());
```
Otras lecturas:
Una referencia del lenguaje hasta a la fecha se puede encontrar en
<http://cppreference.com/w/cpp>
Recursos adicionales se pueden encontrar en <http://cplusplus.com>
* 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).

View File

@ -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
---

View File

@ -0,0 +1,293 @@
---
language: erlang
lang: es-es
contributors:
- ["Giovanni Cappellotto", "http://www.focustheweb.com/"]
translators:
- ["Ernesto Pelayo", "http://github.com/ErnestoPelayo"]
filename: learnerlang-es.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".**
## 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 <erl_eval.6.17052888>
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.
## 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).**
## 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 <erl_eval.20.67289768>
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>**
## 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
``**

View File

@ -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
[<AbstractClass>]
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<_>()
[<CLIEvent>]
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/).

View File

@ -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

View File

@ -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
<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
válido, eso significa que podemos usar elementos HTML en Markdown como, por
ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún

View File

@ -0,0 +1,568 @@
---
language: Matlab
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 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 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íneas.
% Los comentarios comienzan con un símbolo de porcentaje.
%{
Los Comentarios de multiples líneas 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)
%% 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
%% 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ó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 '...'
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 "texto" en la pantalla
% Variables y expresiones
myVariable = 4 % Espacio de trabajo de aviso muestra la variable recién creada
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
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 = 'MiCadena'
length(a) % ans = 8
a(2) % ans = y
[a,a] % ans = MiCadenaMiCadena
% Celdas
a = {'uno', 'dos', 'tres'}
a(1) % ans = 'uno' - retorna una celda
char(a(1)) % ans = uno - 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, los í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(fila, columna)
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 % Multiplicación de matrices
A .* B % Multiplica cada elemento en A por su elemento correspondiente en B
% 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
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 % 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
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, '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'); % 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
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í
% 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 espacio de trabajo
% 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 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
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('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('Mayor que 15')
elseif (a == 23)
disp('a es 23')
else
disp('Ninguna condicion se ha cumplido')
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 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
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) % 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
[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 % producto de elementos
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 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.
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 estructuras de Matlab.
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/)

View File

@ -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
```objectivec
// Los comentarios de una sola línea inician con //
/*

1935
es-es/perl6-es.html.markdown Normal file

File diff suppressed because it is too large Load Diff

View File

@ -14,8 +14,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 +37,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 +87,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 +104,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 +174,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 +200,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 +217,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 +257,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 +266,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 +279,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 +326,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 +423,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

View File

@ -10,7 +10,7 @@ filename: learnvisualbasic-es.vb
lang: es-es
---
```vb
```
Module Module1
Sub Main()

View File

@ -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.

View File

@ -10,7 +10,7 @@ lang: fi-fi
John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi).
```markdown
```md
<!-- Jokainen HTML-tiedosto on pätevää Markdownia. Tämä tarkoittaa että voimme
käyttää HTML-elementtejä Markdownissa, kuten kommentteja, ilman että markdown
-jäsennin vaikuttaa niihin. Tästä johtuen et voi kuitenkaan käyttää markdownia

View File

@ -910,7 +910,6 @@ v.swap(vector<Foo>());
```
Lecture complémentaire :
Une référence à jour du langage est disponible à
<http://cppreference.com/w/cpp>
Des ressources supplémentaires sont disponibles à <http://cplusplus.com>
* 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).

View File

@ -305,7 +305,6 @@ end
(1..3).each do |index|
puts "Index: #{index}"
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3

View File

@ -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<i` et `aj<ai`, nous trouvons le plus grand LSj et ajoutons le à LSi. L'algorithme fonctionne en temps *O(n2)*.
Pseudo-code pour trouver la longueur de la plus grande sous-chaîne croissante :
La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme plus_grande_chaîne_jusqu'à_maintenant et son index, nous pourrions sauver beaucoup de temps.
La complexité de cet algorithme peut être réduite en utilisant une meilleure structure de données qu'un tableau. Par exemple, si nous sauvegardions le tableau d'origine, ou une variable comme `plus_grande_chaîne_jusqu'à_maintenant` et son index, nous pourrions sauver beaucoup de temps.
Le même concept peut être appliqué pour trouver le chemin le plus long dans un graphe acyclique orienté.
@ -43,12 +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

View File

@ -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

View File

@ -13,6 +13,7 @@ jQuery est une bibliothèque JavaScript dont le but est de permettre de "faire p
C'est pourquoi aujourd'hui, jQuery est utilisée par de nombreuses grandes entreprises et par des développeurs du monde entier.
Étant donné que jQuery est une bibliothèque JavaScript, vous devriez d'abord [apprendre le JavaScript](https://learnxinyminutes.com/docs/fr-fr/javascript-fr/)
```js
@ -138,5 +139,5 @@ $('p').each(function() {
});
``
```

View File

@ -0,0 +1,106 @@
---
category: Algorithms & Data Structures
name: Lambda Calculus
contributors:
- ["Max Sun", "http://github.com/maxsun"]
translators:
- ["Yvan Sraka", "https://github.com/yvan-sraka"]
lang: fr-fr
---
# 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 | `<nom>` | `x` | une variable nommée "x" |
| Fonction | `λ<paramètres>.<corps>` | `λx.x` | une fonction avec le paramètre "x" et le corps "x"|
| Application | `<fonction><variable ou function>` | `(λ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.<corps>` est utilisé de manière interchangeable avec: `λx.λy.<corps>`
----
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: <code>n = λf.f<sup>n</sup></code> 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)

View File

@ -0,0 +1,367 @@
---
language: markdown
contributors:
- ["Andrei Curelaru", "http://www.infinidad.fr"]
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 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)
## Balises HTML
Markdown est un sur-ensemble du HTML, donc tout fichier HTML est un ficher
Markdown valide.
```md
<!-- Ce qui veut dire que 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 l'analyseur syntaxique du Markdown.
Toutefois, si vous voulez créer une balise HTML dans un fichier Markdown,
vous ne pourrez pas utiliser du Markdown à l'intérieur de cette derniere. -->
```
## En-têtes
Vous pouvez facilement créer des balises HTML `<h1>` à `<h6>` 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 <h1>
## Ceci est un <h2>
### Ceci est un <h3>
#### Ceci est un <h4>
##### Ceci est un <h5>
###### Ceci est un <h6>
```
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._
**Ce texte est en gras.**
__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é.
```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.
Je suis toujours dans le paragraphe 2!
Puis là, eh oui, le paragraphe 3!
```
Si jamais vous souhaitez insérer une balise HTML `<br />`, 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).
Bigre, il y a un <br /> 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
> de la citation.
> La taille ne compte pas^^ tant que chaque ligne commence par un `>`.
> 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
```
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 `<code>`), 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 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
va utiliser une coloration syntaxique pour le langage indiqué après les ```.
## Ligne Horizontale
Pour insérer une ligne horizontale, utilisez trois ou plusieurs astérisques ou tirets, avec ou sans espaces entre.
```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 `Title`, collez-le entre guillemets, avec 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/ "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 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
<http://testwebsite.com/> est équivalent à :
[http://testwebsite.com/](http://testwebsite.com/)
```
### Liens Automatiques pour emails
```md
<foo@bar.com>
```
### Caracteres d'echappement
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\*.
```
### Touches de clavier
Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `<kdb>`
pour représenter une touche du clavier.
```md
Ton ordinateur a planté? Essayer de taper :
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
```
### 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 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 [](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).

View File

@ -1,289 +0,0 @@
---
language: markdown
contributors:
- ["Andrei Curelaru", "http://www.infinidad.fr"]
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).
Faites moi autant de retours que vous voulez! Sentez vous libre de "forker"
et envoyer des pull request!
```markdown
<!-- 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. -->
<!-- Toutefois, si vous voulez créer un élément HTML dans un fichier Markdown,
vous ne pourrez pas utiliser du Markdown à l'intérieur de ce dernier. -->
<!-- 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. -->
<!-- Headers ( En-têtes ) -->
<!-- Vous pouvez facilement créer des éléments HTML <h1> à <h6> 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é. -->
# Ceci est un <h1>
## Ceci est un <h2>
### Ceci est un <h3>
#### Ceci est un <h4>
##### Ceci est un <h5>
###### Ceci est un <h6>
<!--
Markdown fournit également une façon alternative de marquer les h1 et h2
-->
Ceci est un h1
=============
Ceci est un h2
-------------
<!-- Styles basiques pour du texte -->
<!-- On peut facilement rendre un texte "gras" ou "italique" en Markdown -->
*Ce texte est en italique.*
_Celui-ci aussi._
**Ce texte est en gras.**
__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 strikethrough ( texte barré ) : -->
~~Ce texte est barré avec strikethrough.~~
<!-- Les Paragraphes sont représentés par une ou plusieurs lignes de texte
séparées par une ou plusieurs lignes vides. -->
Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non?
Maintenant je suis dans le paragraphe 2.
Je suis toujours dans le paragraphe 2!
Puis là, eh oui, le paragraphe 3!
<!--
Si jamais vous souhaitez insérer une balise HTML <br />, 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).
Bigre, il y a un <br /> au dessus de moi!
<!-- Les 'Blocs de Citations' sont générés aisément, grâce au caractère > -->
> 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
> de la citation.
> La taille ne compte pas^^ tant que chaque ligne commence par un `>`.
> 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. -->
* Item
* Item
* Un autre item
ou
+ Item
+ Item
+ Encore un item
ou
- Item
- Item
- Un dernier item
<!-- les Listes Ordonnées sont générées via un nombre suivi d'un point -->
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é.-->
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 -->
1. Item un
2. Item deux
3. Item trois
* Sub-item
* Sub-item
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.
- [ ] Première tache à réaliser.
- [ ] Une autre chose à faire.
La case suivante sera une case à cocher HTML cochée.
- [x] Ça ... c'est fait!
<!-- les Blocs de Code -->
<!-- Pour marquer du texte comme étant du code, il suffit de commencer
chaque ligne en tapant 4 espaces (ou un Tab) -->
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 -->
my_array.each do |item|
puts item
end
<!-- Des bouts de code en mode 'inline' s'ajoutent en les entourant de ` -->
La fonction `run()` ne vous oblige pas à aller courir!
<!-- Via GitHub Flavored Markdown, vous pouvez utiliser
des syntaxes spécifiques -->
\`\`\`ruby
<!-- mais enlevez les backslashes quand vous faites ça,
gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )-->
def foobar
puts "Hello world!"
end
\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin -->
<-- 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 (<hr />) -->
<!-- Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets,
avec ou sans espaces entre chaque un. -->
***
---
- - -
****************
<!-- 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.
-->
[Clic moi!](http://test.com/)
<!--
Pour ajouter un attribut Title, collez le entre guillemets, avec le lien.
-->
[Clic moi!](http://test.com/ "Lien vers Test.com")
<!-- les Liens Relatifs marchent aussi -->
[En avant la musique](/music/).
<!-- Les liens façon "références" sont eux aussi disponibles en Markdown -->
[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, ...) quoi que ce soit tant qu'ils sont uniques -->
<!-- Il y a également le "nommage implicite" qui transforme le texte du lien
en identifiant -->
[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! -->
![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel")
<!-- Là aussi, on peut utiliser le mode "références" -->
![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 -->
<http://testwebsite.com/> est équivalent à :
[http://testwebsite.com/](http://testwebsite.com/)
<!-- Liens Automatiques pour emails -->
<foo@bar.com>
<!-- Escaping -->
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 :
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 :
-->
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| Alignement Gauche | Centé | Alignement Droite |
| bla | bla | bla |
<!-- ou bien, pour un résultat équivalent : -->
Col 1 | Col2 | Col3
:-- | :-: | --:
Ough que c'est moche | svp | arrêtez
<!-- Fin! -->
```
Pour plus d'information :
consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe,
et [](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard.

View File

@ -6,10 +6,11 @@ contributors:
- ["Trismegiste", "https://github.com/Trismegiste"]
translators:
- ["Pascal Boutin", "http://pboutin.net/"]
- ["Julien M'Poy", "https://github.com/groovytron"]
lang: fr-fr
---
This document describes PHP 5+.
Ce document décrit PHP 5+.
```php
// Le code PHP doit être placé à l'intérieur de balises '<?php'
@ -48,7 +49,7 @@ Hello World Again!
// Un nom de variable valide commence par une lettre ou un souligné,
// suivi de n'importe quelle lettre, nombre ou de soulignés.
// Les valeurs booléenes ne sont pas sensibles à la casse
// Les valeurs booléennes ne sont pas sensibles à la casse
$boolean = true; // ou TRUE ou True
$boolean = false; // ou FALSE ou False
@ -84,30 +85,30 @@ $number /= $float; // Divise et assigne le quotient à $number
$sgl_quotes = '$String'; // => '$String'
// Évitez les guillemets sauf pour inclure le contenu d'une autre variable
$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.'
$dbl_quotes = "Ceci est une $sgl_quotes."; // => 'Ceci est une $String.'
// Les caractères spéciaux sont seulement échappés avec des guillemets
$escaped = "This contains a \t tab character.";
$unescaped = 'This just contains a slash and a t: \t';
$escaped = "Ceci contient \t une tabulation.";
$unescaped = 'Ceci contient juste un slash et un t: \t';
// En cas de besoin, placez la variable dans des accolades
$money = "I have $${number} in the bank.";
$money = "J'ai $${number} sur mon compte en banque.";
// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes
// multi-lignes non-interprétées
$nowdoc = <<<'END'
Multi line
string
String
mutli-lignes
END;
// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées
$heredoc = <<<END
Multi line
$sgl_quotes
multi-lignes
END;
// La concaténation de chaînes se fait avec un .
echo 'This string ' . 'is concatenated';
echo 'Cette string ' . 'est concatenée'; // => 'Cette string est concaténée'
/********************************
@ -122,7 +123,7 @@ echo 'This string ' . 'is concatenated';
define("FOO", "something");
// on peut accéder à une constante en utilisant directement son nom
echo 'This outputs '.FOO;
echo 'Ceci affiche ' . FOO;
/********************************
@ -149,6 +150,14 @@ $array[] = 'Four';
// Retrait d'un élément du tableau
unset($array[3]);
// Depuis PHP 7, il est possible de déclarer des tableaux constants en
// utilisant 'define'.
define('ANIMAUX', [
'chien',
'chat',
'oiseau',
]);
/********************************
* Affichage
*/
@ -159,11 +168,13 @@ echo('Hello World!');
print('Hello World!'); // Pareil à "écho"
// Pour écho, vous n'avez pas besoin des parenthèses
// 'echo' et 'print' sont des language constructs.
// Il n'ont pas besoin de parenthèses car ils sont traités comme
// des opérateurs unaires.
echo 'Hello World!';
print 'Hello World!'; // Pour print non plus
print 'Hello World!';
$paragraph = 'paragraph';
$paragraph = 'paragraphe';
echo 100; // Affichez un scalaire directement
echo $paragraph; // ou des variables
@ -202,7 +213,8 @@ $b = '0';
$c = '1';
$d = '1';
// assert affiche un avertissement dans son argument n'est pas vrai
// assert affiche un avertissement quand l'expression booléenne passée
// en argument n'est pas vraie.
// Ces comparaisons vont toujours être vraies, même si leurs
// types ne sont pas les mêmes.
@ -315,7 +327,7 @@ if ($x === '0') {
switch ($x) {
case '0':
print 'Les switch font du transtypage implicite';
break; // Il est important de déclaré un 'break', sinon les cas
break; // Il est important de déclarer un 'break', sinon les cas
// 'two' et 'three' seront évalués
case 'two':
case 'three':
@ -390,9 +402,10 @@ function my_function () {
echo my_function(); // => "Hello"
// Les noms de fonction débutent par le symbole $
// Un nom de variable valide commence par une lettre ou un souligné,
// Un nom de fonction valide commence par une lettre ou un souligné,
// suivi de n'importe quelle lettre, nombre ou de soulignés.
// Les noms des arguments d'une fonction doivent respecter le même format que
// celui des variables.
function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1
$result = $x + $y;
@ -519,7 +532,7 @@ class MyClass
public static function myStaticMethod()
{
print 'I am static';
print 'Je suis static';
}
}
@ -527,7 +540,7 @@ class MyClass
echo MyClass::MY_CONST; // Outputs 'value';
echo MyClass::$staticVar; // Retourne 'static';
MyClass::myStaticMethod(); // Retourne 'I am static';
MyClass::myStaticMethod(); // Retourne 'Je suis static';
// On peut instancier une classe en utilisant le mot clé 'new'
$my_class = new MyClass('An instance property');
@ -584,7 +597,7 @@ echo $x->property; // Va utiliser la méthode __get()
$x->property = 'Something'; // Va utiliser la méthode __set()
// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou
// elle peuvent implémenter une interface (en utilisant le mot clé 'implement').
// elle peuvent implémenter une interface (en utilisant le mot clé 'implements').
// Une interface peut être déclarée avec le mot clé 'interface'
@ -637,6 +650,35 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo
}
}
// Il est possible de déclarer des classes internes anonymes depuis PHP 7
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger()); // => 'object(class@anonymous)#2 (0) {}'
/********************************
* Espaces de noms (namespaces)
*/

View File

@ -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()
```
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
from PyQt4.QtGui import *
from PyQt4.QtCore import *
def window():
app = QApplication(sys.argv)
w = QWidget()
# Creation d'un bouton attaché au widget w
b = QPushButton(w)
b.setText("Press me")
b.move(50, 50)
# 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_())
# 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")
# 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)
d.exec_()
if __name__ == '__main__':
window()
```

View File

@ -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
@ -306,7 +307,7 @@ module DataTypeExamples =
// ------------------------------------
// Union types (aka variants) have a set of choices
// Only case can be valid at a time.
// Only one case can be valid at a time.
// ------------------------------------
// Use "type" with bar/pipe to define a union type

View File

@ -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 <remote> <branch>, git
# branch commits onto your local repo, like: "git fetch <remote> <branch>, git
# rebase <remote>/<branch>"
$ 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)

View File

@ -15,15 +15,15 @@ contributors:
---
Go was created out of the need to get work done. It's not the latest trend
in computer science, but it is the newest fastest way to solve real-world
in programming language theory, but it is a way to solve real-world
problems.
It has familiar concepts of imperative languages with static typing.
It draws concepts from imperative languages with static typing.
It's fast to compile and fast to execute, it adds easy-to-understand
concurrency to leverage today's multi-core CPUs, and has features to
help with large-scale programming.
concurrency because multi-core CPUs are now common, and it's used successfully
in large codebases (~100 million loc at Google, Inc.).
Go comes with a great standard library and an enthusiastic community.
Go comes with a good standard library and a sizeable community.
```go
// Single line comment
@ -48,7 +48,7 @@ import (
// executable program. Love it or hate it, Go uses brace brackets.
func main() {
// Println outputs a line to stdout.
// Qualify it with the package name, fmt.
// It comes from the package fmt.
fmt.Println("Hello world!")
// Call another function within this package.
@ -180,7 +180,7 @@ func learnFlowControl() {
if true {
fmt.Println("told ya")
}
// Formatting is standardized by the command line command "go fmt."
// Formatting is standardized by the command line command "go fmt".
if false {
// Pout.
} else {
@ -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

View File

@ -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
----------------------------------------------------
-- 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
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
@ -203,11 +206,11 @@ 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.
-- the expression on its right is applied as a parameter to the function on its left.
-- before
even (fib 7) -- false
@ -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

View File

@ -770,19 +770,18 @@ 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/).
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:
* [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).

1
hre.csv Normal file
View File

@ -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
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

View File

@ -1,31 +1,47 @@
---
language: html
filename: learnhtml.html
filename: learnhtml.txt
contributors:
- ["Christophe THOMAS", "https://github.com/WinChris"]
translators:
- ["Robert Steed", "https://github.com/robochat"]
---
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.
HTML stands for HyperText Markup Language.
**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.
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.
**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
<!-- Comments are enclosed like this line! -->
<!--
Comments
can
span
multiple
lines!
-->
<!-- #################### The Tags #################### -->
<!-- Here is an example HTML file that we are going to analyse. -->
<!doctype html>
<html>
<head>
@ -33,7 +49,9 @@ This article is concerned principally with HTML syntax and some useful tips.
</head>
<body>
<h1>Hello, world!</h1>
<a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows</a>
<a href="http://codepen.io/anon/pen/xwjLbZ">
Come look at what this shows
</a>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ul>
@ -44,7 +62,9 @@ This article is concerned principally with HTML syntax and some useful tips.
</body>
</html>
<!-- An HTML file always starts by indicating to the browser that the page is HTML. -->
<!--
An HTML file always starts by indicating to the browser that the page is HTML.
-->
<!doctype html>
<!-- After this, it starts by opening an <html> tag. -->
@ -58,10 +78,17 @@ This article is concerned principally with HTML syntax and some useful tips.
<!-- Inside (between the opening and closing tags <html></html>), we find: -->
<!-- A header defined by <head> (it must be closed with </head>). -->
<!-- The header contains some description and additional information which are not displayed; this is metadata. -->
<!--
The header contains some description and additional information which are not
displayed; this is metadata.
-->
<head>
<title>My Site</title><!-- The tag <title> indicates to the browser the title to show in browser window's title bar and tab name. -->
<!--
The tag <title> indicates to the browser the title to show in browser
window's title bar and tab name.
-->
<title>My Site</title>
</head>
<!-- After the <head> section, we find the tag - <body> -->
@ -69,13 +96,28 @@ This article is concerned principally with HTML syntax and some useful tips.
<!-- We must fill the body with the content to be displayed. -->
<body>
<h1>Hello, world!</h1> <!-- The h1 tag creates a title. -->
<!-- There are also subtitles to <h1> from the most important (h2) to the most precise (h6). -->
<a href = "http://codepen.io/anon/pen/xwjLbZ">Come look at what this shows</a> <!-- a hyperlink to the url given by the attribute href="" -->
<p>This is a paragraph.</p> <!-- The tag <p> lets us include text in the html page. -->
<!-- The h1 tag creates a title. -->
<h1>Hello, world!</h1>
<!--
There are also subtitles to <h1> from the most important (h2) to the most
precise (h6).
-->
<!-- a hyperlink to the url given by the attribute href="" -->
<a href="http://codepen.io/anon/pen/xwjLbZ">
Come look at what this shows
</a>
<!-- The tag <p> lets us include text in the html page. -->
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ul> <!-- The tag <ul> creates a bullet list. -->
<!-- To have a numbered list instead we would use <ol> giving 1. for the first element, 2. for the second, etc. -->
<!-- The tag <ul> creates a bullet list. -->
<!--
To have a numbered list instead we would use <ol> giving 1. for the first
element, 2. for the second, etc.
-->
<ul>
<li>This is an item in a non-enumerated list (bullet list)</li>
<li>This is another item</li>
<li>And this is the last item on the list</li>
@ -86,21 +128,33 @@ This article is concerned principally with HTML syntax and some useful tips.
<!-- But it is possible to add many additional types of HTML tags. -->
<!-- To insert an image. -->
<img src="http://i.imgur.com/XWG0O.gif"/> <!-- The source of the image is indicated using the attribute src="" -->
<!-- The source can be an URL or even path to a file on your computer. -->
<!-- The <img /> tag is used to insert an image. -->
<!--
The source of the image is indicated using the attribute src=""
The source can be an URL or even path to a file on your computer.
-->
<img src="http://i.imgur.com/XWG0O.gif"/>
<!-- It is also possible to create a table. -->
<table> <!-- We open a <table> element. -->
<tr> <!-- <tr> allows us to create a row. -->
<th>First Header</th> <!-- <th> allows us to give a title to a table column. -->
<!-- We open a <table> element. -->
<table>
<!-- <tr> allows us to create a row. -->
<tr>
<!-- <th> allows us to give a title to a table column. -->
<th>First Header</th>
<th>Second Header</th>
</tr>
<tr>
<td>first row, first column</td> <!-- <td> allows us to create a table cell. -->
<!-- <td> allows us to create a table cell. -->
<td>first row, first column</td>
<td>first row, second column</td>
</tr>
<tr>
<td>second row, first column</td>
<td>second row, second column</td>
@ -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)

View File

@ -0,0 +1,816 @@
---
language: python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "https://aminb.org"]
- ["Andre Polykanine", "https://github.com/Oire"]
- ["evuez", "http://github.com/evuez"]
- ["asyne", "https://github.com/justblah"]
- ["habi", "http://github.com/habi"]
translators:
- ["Tamás Diószegi", "https://github.com/ditam"]
filename: learnpython-hu.py
lang: hu-hu
---
A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az
egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem
bele. Tulajdonképpen futtatható pszeudokód.
Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/)
ajánlott.
Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x
verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával.
A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami
Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott.
```python
# Az egysoros kommentek kettőskereszttel kezdődnek
""" Többsoros stringeket három darab " közé
fogva lehet írni, ezeket gyakran használják
több soros kommentként.
"""
####################################################
# 1. Egyszerű adattípusok és operátorok
####################################################
# Használhatsz számokat
3 # => 3
# Az alapműveletek meglepetésektől mentesek
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része
# lesz az eredmény
5 / 2 # => 2
# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk
2.0 # Ez egy float
11.0 / 4.0 # => 2.75 áh... máris jobb
# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # floatok esetén is
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
# Ha importáljuk a division modult (ld. 6. Modulok rész),
# akkor a '/' jellel pontos osztást tudunk végezni.
from __future__ import division
11 / 4 # => 2.75 ...sima osztás
11 // 4 # => 2 ...egész osztás
# Modulo művelet
7 % 3 # => 1
# Hatványozás (x az y. hatványra)
2 ** 4 # => 16
# A precedencia zárójelekkel befolyásolható
(1 + 3) * 2 # => 8
# Logikai operátorok
# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes
True and False # => False
False or True # => True
# A logikai operátorok egészeken is használhatóak
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True
# Negálni a not kulcsszóval lehet
not True # => False
not False # => True
# Egyenlőségvizsgálat ==
1 == 1 # => True
2 == 1 # => False
# Egyenlőtlenség !=
1 != 1 # => False
2 != 1 # => True
# További összehasonlítások
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# Az összehasonlítások láncolhatóak!
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# Stringeket " vagy ' jelek közt lehet megadni
"Ez egy string."
'Ez egy másik string.'
# A stringek összeadhatóak!
"Hello " + "world!" # => "Hello world!"
# '+' jel nélkül is összeadhatóak
"Hello " "world!" # => "Hello world!"
# ... illetve szorozhatóak
"Hello" * 3 # => "HelloHelloHello"
# Kezelhető karakterek indexelhető listájaként
"This is a string"[0] # => 'T'
# A string hosszát a len függvény adja meg
len("This is a string") # => 16
# String formázáshoz a % jel használható
# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog
# kerülni, de azért jó tudni, hogyan működik.
x = 'alma'
y = 'citrom'
z = "A kosárban levő elemek: %s és %s" % (x, y)
# A string formázás újabb módja a format metódus használatával történik.
# Jelenleg ez a javasolt megoldás.
"{} egy {} szöveg".format("Ez", "helytartó")
"A {0} pedig {1}".format("string", "formázható")
# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók.
"{name} kedvence a {food}".format(name="Bob", food="lasagna")
# None egy objektum
None # => None
# A None-nal való összehasonlításhoz ne használd a "==" jelet,
# használd az "is" kulcsszót helyette
"etc" is None # => False
None is None # => True
# Az 'is' operátor objektum egyezést vizsgál.
# Primitív típusok esetén ez nem túl hasznos,
# objektumok esetén azonban annál inkább.
# Bármilyen objektum használható logikai kontextusban.
# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek):
# - None
# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j)
# - üres sorozatok (pl. '', (), [])
# - üres konténerek (pl., {}, set())
# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint,
# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
#
# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki)
bool(0) # => False
bool("") # => False
####################################################
# 2. Változók és kollekciók
####################################################
# Létezik egy print utasítás
print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you!
# Így lehet egyszerűen bemenetet kérni a konzolról:
input_string_var = raw_input(
"Enter some data: ") # Visszatér a megadott stringgel
input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként
# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni
# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve
# A változókat nem szükséges a használat előtt deklarálni
some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas
some_var # => 5
# Érték nélküli változóra hivatkozás hibát dob.
# Lásd a Control Flow szekciót a kivételkezelésről.
some_other_var # name error hibát dob
# az if használható kifejezésként
# a C nyelv '?:' ternáris operátorával egyenértékűen
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# A listákban sorozatok tárolhatóak
li = []
# Már inicializáláskor megadhatóak elemek
other_li = [4, 5, 6]
# A lista végére az append metódus rak új elemet
li.append(1) # li jelenleg [1]
li.append(2) # li jelenleg [1, 2]
li.append(4) # li jelenleg [1, 2, 4]
li.append(3) # li jelenleg [1, 2, 4, 3]
# A végéről a pop metódus távolít el elemet
li.pop() # => 3 és li jelenleg [1, 2, 4]
# Rakjuk vissza
li.append(3) # li jelenleg [1, 2, 4, 3], újra.
# A lista elemeket tömb indexeléssel lehet hivatkozni
li[0] # => 1
# A már inicializált értékekhez a = jellel lehet új értéket rendelni
li[0] = 42
li[0] # => 42
li[0] = 1 # csak visszaállítjuk az eredeti értékére
# Így is lehet az utolsó elemre hivatkozni
li[-1] # => 3
# A túlindexelés eredménye IndexError
li[4] # IndexError hibát dob
# A lista részeit a slice szintaxissal lehet kimetszeni
# (Matekosoknak ez egy zárt/nyitott intervallum.)
li[1:3] # => [2, 4]
# A lista eleje kihagyható így
li[2:] # => [4, 3]
# Kihagyható a vége
li[:3] # => [1, 2, 4]
# Minden második elem kiválasztása
li[::2] # =>[1, 4]
# A lista egy másolata, fordított sorrendben
li[::-1] # => [3, 4, 2, 1]
# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek
# li[start:end:step]
# Listaelemek a "del" paranccsal törölhetőek
del li[2] # li jelenleg [1, 2, 3]
# A listák összeadhatóak
li + other_li # => [1, 2, 3, 4, 5, 6]
# Megjegyzés: az eredeti li és other_li értékei változatlanok
# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal
li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6]
# Egy elem első előfordulásának eltávolítása
li.remove(2) # li jelenleg [1, 3, 4, 5, 6]
li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában
# Elemek beszúrhatóak tetszőleges helyre
li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét
# Egy elem első előfordulási helye
li.index(2) # => 1
li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában
# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető
1 in li # => True
# A lista hossza a "len()" függvénnyel
len(li) # => 6
# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # TypeError hibát dob
# Az összes lista-műveletet ezeken is használható
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# Az N-esek (és listák) kicsomagolhatóak külön változókba
a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3
d, e, f = 4, 5, 6 # a zárójel elhagyható
# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik
g = 4, 5, 6 # => (4, 5, 6)
# Nézd, milyen egyszerű két értéket megcserélni
e, d = d, e # d most már 5 és az e 4
# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók
empty_dict = {}
# Ez pedig rögtön értékekkel van inicializálva
filled_dict = {"one": 1, "two": 2, "three": 3}
# Egy dictionary értékei [] jelek közt indexelhetőek
filled_dict["one"] # => 1
# A "keys()" metódus visszatér a kulcsok listájával
filled_dict.keys() # => ["three", "two", "one"]
# Megjegyzés: egy dictionary párjainak sorrendje nem garantált
# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket.
# Az értékek listája a "values()" metódussal kérhető le
filled_dict.values() # => [3, 2, 1]
# ld. a fenti megjegyzést az elemek sorrendjéről.
# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal
filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)]
# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben
"one" in filled_dict # => True
1 in filled_dict # => False
# Nem létező kulcs hivatkozása KeyError hibát dob
filled_dict["four"] # KeyError
# A "get()" metódus használatával elkerülhető a KeyError
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
# Megjegyzés: ettől még filled_dict.get("four") => None
# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben)
# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek:
filled_dict["four"] = 4 # ez után filled_dict["four"] => 4
# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva
filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re
filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5
# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat
empty_set = set()
# Inicializáljuk ezt a halmazt néhány elemmel
some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4])
# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet
another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4])
# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Új halmaz-elemek hozzáadása
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Halmaz metszés a & operátorral
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
# Halmaz unió | operátorral
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Halmaz különbség -
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Szimmetrikus differencia ^
{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit
{1, 2} >= {1, 2, 3} # => False
# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak
{1, 2} <= {1, 2, 3} # => True
# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható
2 in filled_set # => True
10 in filled_set # => False
####################################################
# 3. Control Flow
####################################################
# Legyen egy változónk
some_var = 5
# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben!
# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél"
if some_var > 10:
print "some_var nagyobb, mint 10."
elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben.
print "some_var kisebb 10-nél"
else: # Ez sem kötelező.
print "some_var kereken 10."
"""
For ciklusokkal végigiterálhatunk listákon
a kimenet:
A(z) kutya emlős
A(z) macska emlős
A(z) egér emlős
"""
for animal in ["kutya", "macska", "egér"]:
# A {0} kifejezéssel formázzuk a stringet, ld. korábban.
print "A(z) {0} emlős".format(animal)
"""
"range(number)" visszatér számok listájával 0-től number-ig
a kimenet:
0
1
2
3
"""
for i in range(4):
print i
"""
"range(lower, upper)" visszatér a lower és upper közti számok listájával
a kimenet:
4
5
6
7
"""
for i in range(4, 8):
print i
"""
A while ciklus a feltétel hamissá válásáig fut.
a kimenet:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # Rövidítés az x = x + 1 kifejezésre
# A kivételek try/except blokkokkal kezelhetőek
# Python 2.6-tól felfele:
try:
# A "raise" szóval lehet hibát dobni
raise IndexError("Ez egy index error")
except IndexError as e:
pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat.
except (TypeError, NameError):
pass # Ha szükséges, egyszerre több hiba típus is kezelhető
else: # Az except blokk után opcionálisan megadható
print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák
finally: # Mindenképpen lefut
print "Itt felszabadíthatjuk az erőforrásokat például"
# Az erőforrások felszabadításához try/finally helyett a with használható
with open("myfile.txt") as f:
for line in f:
print line
####################################################
# 4. Függvények
####################################################
# A "def" szóval hozhatunk létre új függvényt
def add(x, y):
print "x is {0} and y is {1}".format(x, y)
return x + y # A return szóval tudunk értékeket visszaadni
# Így hívunk függvényt paraméterekkel
add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11
# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt
add(y=6, x=5) # Ez esetben a sorrendjük nem számít
# Változó számú paramétert fogadó függvény így definiálható.
# A * használatával a paramétereket egy N-esként kapjuk meg.
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
# Változó számú nevesített paramétert fogadó függvény is megadható,
# a ** használatával a paramétereket egy dictionary-ként kapjuk meg
def keyword_args(**kwargs):
return kwargs
# Nézzük meg, mi történik
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# A két módszer egyszerre is használható
def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) kimenete:
(1, 2)
{"a": 3, "b": 4}
"""
# Függvények hívásakor a fenti args és kwargs módszerek inverze használható
# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4)
all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4)
all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4)
# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek,
# a * illetve ** operátorokkal kifejtve
def pass_all_the_args(*args, **kwargs):
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
# Függvény scope
x = 5
def set_x(num):
# A lokális x változó nem ugyanaz, mint a globális x
x = num # => 43
print x # => 43
def set_global_x(num):
global x
print x # => 5
x = num # a globális x-et 6-ra állítjuk
print x # => 6
set_x(43)
set_global_x(6)
# A pythonban a függvény elsőrendű (ún. "first class") típus
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# Névtelen függvények is definiálhatóak
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# Léteznek beépített magasabb rendű függvények
map(add_10, [1, 2, 3]) # => [11, 12, 13]
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel
[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]
# halmaz és dictionary képzők is léteznek
{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'}
{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
####################################################
# 5. Osztályok
####################################################
# Az object osztály egy alosztályát képezzük
class Human(object):
# Osztály szintű mező: az osztály összes példányában azonos
species = "H. sapiens"
# Ez a függvény meghívódik az osztály példányosításakor.
# Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python
# előre definiált, a nyelv által belsőleg használt, de a felhasználó által
# is látható objektumok és mezők neveire.
# Ne vezessünk be új, ilyen elnevezési sémát használó neveket!
def __init__(self, name):
# A paramétert értékül adjuk a példány name attribútumának
self.name = name
# Inicializálunk egy mezőt
self.age = 0
# Példány metódus. Minden metódus első paramétere a "self", a példány maga
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
# Egy osztálymetódus az osztály összes példány közt meg van osztva.
# Hívásukkor az első paraméter mindig a hívó osztály.
@classmethod
def get_species(cls):
return cls.species
# Egy statikus metódus osztály és példányreferencia nélkül hívódik
@staticmethod
def grunt():
return "*grunt*"
# Egy property jelölésű függvény olyan, mint egy getter.
# Használatával az age mező egy csak-olvasható attribútummá válik.
@property
def age(self):
return self._age
# Így lehet settert megadni egy mezőhöz
@age.setter
def age(self, age):
self._age = age
# Így lehet egy mező törlését engedélyezni
@age.deleter
def age(self):
del self._age
# Példányosítsuk az osztályt
i = Human(name="Ian")
print i.say("hi") # kimenet: "Ian: hi"
j = Human("Joel")
print j.say("hello") # kimenet: "Joel: hello"
# Hívjuk az osztály metódusunkat
i.get_species() # => "H. sapiens"
# Változtassuk meg az osztály szintű attribútumot
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# Hívjuk meg a statikus metódust
Human.grunt() # => "*grunt*"
# Adjunk új értéket a mezőnek
i.age = 42
# Kérjük le a mező értékét
i.age # => 42
# Töröljük a mezőt
del i.age
i.age # => AttributeError hibát dob
####################################################
# 6. Modulok
####################################################
# Modulokat így lehet importálni
import math
print math.sqrt(16) # => 4
# Lehetséges csak bizonyos függvényeket importálni egy modulból
from math import ceil, floor
print ceil(3.7) # => 4.0
print floor(3.7) # => 3.0
# Egy modul összes függvénye is importálható
# Vigyázat: ez nem ajánlott.
from math import *
# A modulok nevei lerövidíthetőek
import math as m
math.sqrt(16) == m.sqrt(16) # => True
# Meggyőződhetünk róla, hogy a függvények valóban azonosak
from math import sqrt
math.sqrt == m.sqrt == sqrt # => True
# A Python modulok egyszerű fájlok.
# Írhatsz sajátot és importálhatod is.
# A modul neve azonos a tartalmazó fájl nevével.
# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul.
import math
dir(math)
# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos
# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett.
# A lokális mappa prioritást élvez a beépített könyvtárak felett.
####################################################
# 7. Haladóknak
####################################################
# Generátorok
# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket.
# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit,
# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat!
def double_numbers(iterable):
double_arr = []
for i in iterable:
double_arr.append(i + i)
return double_arr
# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk
# ezt a nagy listát a ciklus vezérléséhez.
for value in double_numbers(range(1000000)): # `test_non_generator`
print value
if value > 5:
break
# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet,
# amikor azt kérik tőle
def double_numbers_generator(iterable):
for i in iterable:
yield i + i
# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt.
# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak
# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!).
for value in double_numbers_generator(xrange(1000000)): # `test_generator`
print value
if value > 5:
break
# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén
# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a
# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range`
# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük
# - esetünkben a ciklus következő iterációjakor
# A lista képzéshez hasonlóan generátor képzőket is használhatunk
# ("generator comprehensions").
values = (-x for x in [1, 2, 3, 4, 5])
for x in values:
print(x) # kimenet: -1 -2 -3 -4 -5
# Egy generátor összes generált elemét listaként is elkérhetjük:
values = (-x for x in [1, 2, 3, 4, 5])
gen_to_list = list(values)
print(gen_to_list) # => [-1, -2, -3, -4, -5]
# Dekorátorok
# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény.
# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény
# kimenetébe beszúrja az 'Apple' elemet.
def add_apples(func):
def get_fruits():
fruits = func()
fruits.append('Apple')
return fruits
return get_fruits
@add_apples
def get_fruits():
return ['Banana', 'Mango', 'Orange']
# A kimenet tartalmazza az 'Apple' elemet:
# Banana, Mango, Orange, Apple
print ', '.join(get_fruits())
# Ebben a példában a beg dekorátorral látjuk el a say függvényt.
# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor
# megváltoztatja az eredmény mondatot.
from functools import wraps
def beg(target_function):
@wraps(target_function)
def wrapper(*args, **kwargs):
msg, say_please = target_function(*args, **kwargs)
if say_please:
return "{} {}".format(msg, "Please! I am poor :(")
return msg
return wrapper
@beg
def say(say_please=False):
msg = "Can you buy me a beer?"
return msg, say_please
print say() # Can you buy me a beer?
print say(say_please=True) # Can you buy me a beer? Please! I am poor :(
```
## Még több érdekel?
### Ingyenes online tartalmak
* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com)
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
* [The Official Docs](http://docs.python.org/2/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
* [First Steps With Python](https://realpython.com/learn/python-first-steps/)
* [LearnPython](http://www.learnpython.org/)
* [Fullstack Python](https://www.fullstackpython.com/)
### Könyvek
* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)

86
id-id/bf-id.html.markdown Normal file
View File

@ -0,0 +1,86 @@
---
language: bf
filename: brainfuck-id.bf
contributors:
- ["Prajit Ramachandran", "http://prajitr.github.io/"]
- ["Mathias Bynens", "http://mathiasbynens.be/"]
translators:
- ["Muhammad Rifqi Fatchurrahman", "http://muhrifqii.github.io/"]
lang: id-id
---
Brainfuck (tidak dalam huruf kapital kecuali pada awal kalimat) adalah sebuah
bahasa pemrograman Turing-complete yang sangat minim yang hanya memiliki 8 perintah.
Anda bisa mencoba brainfuck pada browser dengan menggunakan [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
```bf
Karakter apapun selain "><+-.,[]" (tanda kutip tidak termasuk) diabaikan.
Brainfuck direpresentasikan dengan sebuah array yang memiliki 30,000 cell yang
diinisialisasi dengan nol dan pointer data yang menunjuk ke current cell.
Terdapat delapan perintah:
+ : Menaikkan nilai pada current cell sebesar satu.
- : Menurunkan nilai pada current cell sebesar satu.
> : Menggeser pointer data ke cell selanjutnya (cell sebelah kanan).
< : Menggeser pointer data ke cell sebelumnya (cell sebelah kiri).
. : Mencetak nilai ASCII pada current cell (misal 65 = 'A').
, : Membaca sebuah karakter masukan tunggal ke dalam current cell.
[ : Jika nilai pada current cell bernilai nol, lewati hingga mencapai ] yang sesuai.
Jika tidak, pindah ke instruksi berikutnya.
] : Jika nilai pada current cell bernilai nol, pindah ke instruksi berikutnya.
Jika tidak, mundur pada instruksi hingga mencapai [ yang sesuai.
[ dan ] membentuk sebuah rekursi while. Tentu saja mereka harus seimbang.
Mari kita lihat beberapa program brainfuck dasar.
++++++ [ > ++++++++++ < - ] > +++++ .
Program ini mencetak huruf 'A'. Mula-mula, cell #1 dinaikkan ke 6.
Cell #1 akan digunakan untuk rekursi. Lalu, masuk ke rekursi ([) dan pindah
ke cell #2. Cell #2 dinaikkan 10 kali, mundur ke cell #1, dan menurunkan
cell #1. Rekursi ini berlangsung 6 kali (melakukan 6 penurunan nilai untuk
cell #1 hingga mencapai 0, di titik mana dia melewati hingga mencapai ] dan
terus berlanjut).
Pada titik ini, kita berada pada cell #1, yang memiliki nilai 0, sedangkan cell #2
memiliki sebuah nilai 60. Kita berpindah ke cell #2, menaikkan nilai 5 kali, memunculkan
nilai 65, lalu cetak nilai pada cell #2. 65 adalah 'A' pada ASCII, jadi 'A'
dicetak ke terminal.
, [ > + < - ] > .
Program ini membaca sebuah karakter dari masukan user dan menyalin karakternya ke
cell #1. Setelah itu rekursi dimulai. Geser ke cell #2, menaikkan nilai pada cell #2,
mundur ke cell #1, dan menurunkan nilai pada cell #1. Hal ini berlanjut sampai cell #1
bernilai 0, dan cell #2 menyimpan nilai lama dari cell #1. Karena kita berada di cell #1
saat ujung rekursi, geser ke cell #2, lalu cetak nilai dalam bentuk ASCII.
Perlu diingat bahwa spasi itu murni untuk memudahkan membaca. Anda bisa
menuliskannya dengan mudah seperti:
,[>+<-]>.
Coba dan cari tahu apa yang program ini lakukan:
,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
Program ini menerima dua buah angka sebagai input, lalu mengalikannya.
Intinya adalah membaca dua masukan. Lalu mulai pada rekursi terluar yang
kondisinya pada cell #1. Lalu pindah ke cell #2, dan mulai rekursi terdalam
yang kondisinya ada pada cell #2, menaikkan nilai pada cell #3. Namun,
ada suatu masalah: Pada akhir dari rekursi terdalam, cell #2 bernilai nol.
Pada kasus tersebut, rekursi terdalam tidak dapat bekerja lagi mulai setelah ini.
Untuk menyelesaikan masalah tersebut, kita juga menaikkan cell #4, dan menyalin
ulang cell #4 ke cell #2. Maka cell #3 adalah hasilnya.
```
Dan itulah brainfuck. Tidak terlalu sulit kan? Hanya untuk iseng-iseng, anda
bisa menuliskan porgram brainfuck anda sendiri, atau anda bisa menuliskan interpreter
brainfuck pada bahasa lain. Interpreternya tidak begitu sulit untuk diimplementasikan,
tapi jika anda seorang masokis, cobalah menulis sebuah interpreter brainfuck... dalam
brainfuck.

View File

@ -13,7 +13,7 @@ Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax
Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request!
```markdown
```md
<!-- Markdown adalah superset dari HTML, jadi setiap berkas HTML adalah markdown yang
valid, ini berarti kita dapat menggunakan elemen HTML dalam markdown, seperti elemen
komentar, dan ia tidak akan terpengaruh parser markdown. Namun, jika Anda membuat

View File

@ -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 <first.last@learnxinyminutes.com>
Inizio del documento
```
Autori multipli
```
= Titolo Documento
John Doe <john@go.com>; Jane Doe<jane@yo.com>; Black Beard <beardy@pirate.com>
Inizio di un documento con autori multipli.
```
Linea di revisione (richiede una linea autore)
```
= Titolo documento V1
Potato Man <chip@crunchy.com>
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 <h2>
=== Livello 2 <h3>
==== Livello 3 <h4>
===== Livello 4 <h5>
```
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.

View File

@ -1130,7 +1130,6 @@ compl 4 // Effettua il NOT bit-a-bit
```
Letture consigliate:
Un riferimento aggiornato del linguaggio può essere trovato qui
<http://cppreference.com/w/cpp>
Risorse addizionali possono essere trovate qui <http://cplusplus.com>
* 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).

View File

@ -0,0 +1,55 @@
---
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<i` nel sotto-insieme `aj<ai`.
Prima di tutto dobbiamo trovare il valore delle sottosequenze più lunghe (LSi) ad ogni indice i con l'ultimo elemento della sequenza che è ai. Quindi il più grande LSi sarebbe la sottosequenza più lunga nella sequenza data. Per iniziare LSi viene inizializzato ad 1, dato che ai è un element della sequenza (Ultimo elemento). Quindi per tutti gli `j` tale che `j<i` e `aj<ai`, troviamo il più grande LSj e lo aggiungiamo a LSi. Quindi l'algoritmo richiede un tempo di *O(n2)*.
Pseudo-codice per trovare la lunghezza della sottosequenza crescente più lunga:
Questa complessità degli algoritmi potrebbe essere ridotta usando una migliore struttura dei dati piuttosto che una matrice. La memorizzazione dell'array predecessore e della variabile come `largest_sequences_so_far` e il suo indice farebbero risparmiare molto tempo.
Un concetto simile potrebbe essere applicato nel trovare il percorso più lungo nel grafico aciclico diretto.
```python
for i=0 to n-1
LS[i]=1
for j=0 to i-1
if (a[i] > a[j] and LS[i]<LS[j])
LS[i] = LS[j]+1
for i=0 to n-1
if (largest < LS[i])
```
### 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]()
## Risorse online
* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming)

View File

@ -26,14 +26,14 @@ Aggiunge la concorrenza in maniera diretta e semplice da capire, per far
forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili
per la programmazione in larga scala.
Go comes with a great standard library and an enthusiastic community.
Go include un'ottima libreria standard e ha una community entusiasta.
```go
// Commento su riga singola
/* Commento
su riga multipla */
// In cima a ogni file è necessario specificare il package.
// In cima ad ogni file è necessario specificare il package.
// Main è un package speciale che identifica un eseguibile anziché una libreria.
package main
@ -65,19 +65,19 @@ func oltreIlCiaoMondo() {
x = 3 // Assegnazione di una variabile.
// E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente.
y := 4
// Una funzione che ritorna due valori.
somma, prod := imparaMoltepliciValoriDiRitorno(x, y)
// Una funzione che restituisce due valori.
somma, prod := imparaMoltepliciValoriRestituiti(x, y)
fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output.
imparaTipi() // < y minuti, devi imparare ancora!
}
/* <- commento su righe multiple
Le funzioni possono avere parametri e ritornare (molteplici!) valori.
Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati.
Le funzioni possono avere parametri e restituire (molteplici!) valori.
In questo esempio, x e y sono gli argomenti, mentre somma e prod sono i valori restituiti.
Da notare il fatto che x e somma vengono dichiarati come interi.
*/
func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) {
return x + y, x * y // Ritorna due valori.
func imparaMoltepliciValoriRestituiti(x, y int) (somma, prod int) {
return x + y, x * y // Restituisce due valori.
}
// Ecco alcuni tipi presenti in Go
@ -86,7 +86,7 @@ func imparaTipi() {
str := "Impara il Go!" // Tipo stringa.
s2 := `Una stringa letterale
puo' includere andata a capo.` // Sempre di tipo stringa.
può includere andata a capo.` // Sempre di tipo stringa.
// Stringa letterale non ASCII. I sorgenti Go sono in UTF-8.
g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode.
@ -144,20 +144,20 @@ puo' includere andata a capo.` // Sempre di tipo stringa.
imparaControlloDiFlusso() // Torniamo in carreggiata.
}
// In Go è possibile associare dei nomi ai valori di ritorno di una funzione.
// Assegnare un nome al tipo di dato ritornato permette di fare return in vari
// In Go è possibile associare dei nomi ai valori restituiti da una funzione.
// Assegnare un nome al tipo di dato restituito permette di fare return in vari
// punti all'interno del corpo della funzione, ma anche di usare return senza
// specificare in modo esplicito che cosa ritornare.
func imparaValoriDiRitornoConNome(x, y int) (z int) {
// specificare in modo esplicito che cosa restituire.
func imparaValoriRestituitiConNome(x, y int) (z int) {
z = x * y
return // z è implicito, perchè compare nella definizione di funzione.
}
// Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei
// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente
// incrementare un puntatore.
// puntatori. Puoi commettere errori a causa di puntatori nulli, ma non puoi
// incrementare un puntatore direttamente.
func imparaLaMemoria() (p, q *int) {
// I valori di ritorno (con nome) p e q sono puntatori a int.
// I valori restituiti (con nome) p e q sono puntatori a int.
p = new(int) // La funzione new si occupa di allocare memoria.
// L'int allocato viene inizializzato a 0, dunque p non è più nil.
s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria.
@ -207,14 +207,14 @@ func imparaControlloDiFlusso() {
}
// x == 42 qua.
// Il for è l'unica istruzione per ciclare in Go, ma ha varie forme.
// Il for è l'unica istruzione per i loop in Go, ma ha varie forme.
for { // Ciclo infinito.
break // Scherzavo.
continue // Non si arriva qua.
}
// Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale.
// range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa).
// Puoi usare range per iterare lungo un vettore, slice, stringa, mappa o canale.
// range restituisce uno (per i canali) o due valori (vettore, slice, stringa, mappa).
for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} {
// per ogni coppia dentro la mappa, stampa chiave e valore
fmt.Printf("chiave=%s, valore=%d\n", chiave, valore)
@ -236,7 +236,7 @@ func imparaControlloDiFlusso() {
// Inoltre le funzioni letterali possono essere definite e chiamate
// inline, col ruolo di parametri di funzione, a patto che:
// a) la funzione letterale venga chiamata subito (),
// b) il valore ritornato è in accordo con il tipo dell'argomento.
// b) il valore restituito è in accordo con il tipo dell'argomento.
fmt.Println("Somma e raddoppia due numeri: ",
func(a, b int) int {
return (a + b) * 2
@ -247,7 +247,7 @@ func imparaControlloDiFlusso() {
goto amore
amore:
imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente!
imparaFabbricaDiFunzioni() // Una funzione che restituisce un'altra funzione è divertente!
imparaDefer() // Un tour veloce di una parola chiave importante.
imparaInterfacce() // Arriva la roba buona!
}
@ -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 ritorni.
// 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
}

View File

@ -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ù

View File

@ -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 <tipoDato> <nomeVariabile>
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:
// <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3>
int fooInt1, fooInt2, fooInt3;
@ -71,7 +71,7 @@ public class LearnJava {
// Per inizializzare una variabile si usa
// <tipoDato> <nomeVariabile> = <valore>
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 <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore>
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:
// <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>];
// <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>];
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 <primo valore>, altrimenti usa <secondo valore>
// Se (condizione) è vera, usa <primo valore>, altrimenti usa <secondo valore>
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() {

View File

@ -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
});
```

View File

@ -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
<!-- Questo significa che possiamo usare elementi di HTML in Markdown, come per esempio i commenti,
e questi non saranno modificati dal parser di Markdown. State attenti però,
se inserite un elemento HTML nel vostro file Markdown, non potrete usare la sua sintassi
@ -39,7 +39,7 @@ all'interno del contenuto dell'elemento. -->
Potete creare gli elementi HTML da `<h1>` a `<h6>` facilmente, basta che inseriate un egual numero di caratteri cancelletto (#) prima del testo che volete all'interno dell'elemento
```markdown
```md
# Questo è un <h1>
## Questo è un <h2>
### Questo è un <h3>
@ -49,7 +49,7 @@ Potete creare gli elementi HTML da `<h1>` a `<h6>` 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 `<br />`, 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 <br /> sopra di me!
@ -101,7 +101,7 @@ C'è un <br /> 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 `<code>`) 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 (`<hr/>`) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi.
```markdown
```md
***
---
- - -
@ -215,24 +215,24 @@ Le linee orizzontali (`<hr/>`) 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
<http://testwebsite.com/> è equivalente ad
[http://testwebsite.com/](http://testwebsite.com/)
```
### Auto link per le email
```markdown
```md
<foo@bar.com>
```
### 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 `<kbd>` per raffigurare i tasti della tastiera.
```markdown
```md
Il tuo computer è crashato? Prova a premere
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Canc</kbd>
```
@ -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

View File

@ -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)

View File

@ -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

View File

@ -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()
```

File diff suppressed because it is too large Load Diff

161
it-it/qt-it.html.markdown Normal file
View File

@ -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 <QApplication>
#include <QLineEdit>
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 <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
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 <QLabel>
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 <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include <QString>
#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!

View File

@ -6,10 +6,12 @@ contributors:
- ["Andre Polykanine", "https://github.com/Oire"]
translators:
- ["Ale46", "https://github.com/Ale46"]
- ["Chris54721", "https://chris54721.net"]
lang: it-it
---
RST è un formato di file formalmente creato dalla comunità Python per scrivere documentazione (e quindi fa parte di Docutils).
RST (Restructured Text) è un formato di file inizialmente creato dalla comunità Python
per la documentazione (per questo motivo appartiene a Docutils).
I file RST sono semplici file di testo con una sintassi leggera (in confronto all'HTML).
@ -23,7 +25,7 @@ Per usare Restructured Text, sarà necessario installare [Python](http://www.pyt
$ easy_install docutils
```
O se il tuo sistema ha `pip`, puoi usare anche lui:
Oppure, se hai `pip` installato sul tuo sistema:
```bash
$ pip install docutils
@ -32,7 +34,7 @@ $ pip install docutils
## Sintassi del file
Un semplice esempio della sintassi del file:
Ecco un semplice esempio della sintassi RST:
```
.. Le righe che iniziano con due punti sono comandi speciali. Ma se non è possibile trovare alcun comando, la riga viene considerata come un commento
@ -41,16 +43,16 @@ Un semplice esempio della sintassi del file:
I titoli principali sono scritti utilizzando caratteri di uguale, sopra e sotto
===============================================================================
Si noti che devono esistere tanti caratteri di uguale quanti sono i caratteri del titolo.
Si noti che devono esserci tanti caratteri di uguale quanti caratteri del titolo.
Anche il titolo è sottolineato con caratteri di uguale
======================================================
Anche i titoli normali usano caratteri di uguale, ma solo sotto
===============================================================
Sottotitoli con i trattini
--------------------------
I sottotitoli usano i trattini
------------------------------
E sotto-sottotitoli con tildi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
E i sotto-sottotitoli le tildi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Puoi inserire il testo in *corsivo* o in **grassetto**, puoi "contrassegnare" il testo come codice con un doppio apice ``: `` print () ``.
@ -60,13 +62,13 @@ Le liste sono semplici come in Markdown:
- Secondo elemento
     - Sottoelemento
o
oppure
* Primo elemento
* Secondo elemento
     * Sottoelemento
Le tabelle sono davvero facili da scrivere:
Le tabelle sono molto semplici da inserire:
=========== ========
Stato Capitale
@ -75,22 +77,21 @@ Francia Parigi
Giappone Tokio
=========== ========
Le tabelle più complesse possono essere fatte facilmente (colonne e/o righe unite) ma ti suggerisco di leggere il documento completo per questo :)
Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o righe unite) ma ti suggerisco di leggere la documentazione completa per questo :)
Esistono diversi modi per creare collegamenti:
- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo modo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile).
- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile).
- Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento)
- Facendo un collegamento simile a Markdown: `Github <https://github.com/>`_ .
- Utilizzando una sintassi simile a Markdown: `Github <https://github.com/>`_ .
.. _Github https://github.com/
```
## Come usarlo
RST viene fornito con docutils che dispone di `rst2html`, per esempio:
RST viene fornito con docutils, che dispone di `rst2html`, per esempio:
```bash
$ rst2html miofile.rst output.html

653
it-it/ruby-it.html.markdown Normal file
View File

@ -0,0 +1,653 @@
---
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"]
translators:
- ["abonte", "https://github.com/abonte"]
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 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 ("*") 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:
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.

276
it-it/toml-it.html.markdown Normal file
View File

@ -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)

Some files were not shown because too many files have changed in this diff Show More